showdown/src/subParsers/makehtml/encodeCode.js

45 lines
1.3 KiB
JavaScript

////
// makehtml/emoji.js
// Copyright (c) 2018 ShowdownJS
//
// Encode/escape certain characters inside Markdown code runs.
// The point is that in code, these characters are literals,
// and lose their special Markdown meanings.
//
// ***Author:***
// - Estêvão Soares dos Santos (Tivie) <https://github.com/tivie>
////
showdown.subParser('makehtml.encodeCode', function (text, options, globals) {
'use strict';
let startEvent = new showdown.Event('makehtml.encodeCode.onStart', text);
startEvent
.setOutput(text)
._setGlobals(globals)
._setOptions(options);
startEvent = globals.converter.dispatch(startEvent);
text = startEvent.output;
// Encode all ampersands; HTML entities are not
// entities within a Markdown code span.
text = text
.replace(/&/g, '&amp;')
// Do the angle bracket song and dance:
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
// encode "
.replace(/"/g, '&quot;')
// Now, escape characters that are magic in Markdown:
.replace(/([*_{}\[\]\\=~-])/g, showdown.helper.escapeCharactersCallback);
let afterEvent = new showdown.Event('makehtml.encodeCode.onEnd', text);
afterEvent
.setOutput(text)
._setGlobals(globals)
._setOptions(options);
afterEvent = globals.converter.dispatch(afterEvent);
return afterEvent.output;
});