showdown/src/subParsers/githubCodeBlocks.js

46 lines
1.2 KiB
JavaScript
Raw Normal View History

2015-01-16 05:21:33 +08:00
/**
* Handle github codeblocks prior to running HashHTML so that
* HTML contained within the codeblock gets escaped properly
* Example:
* ```ruby
* def hello_world(x)
* puts "Hello, #{x}"
* end
* ```
*/
showdown.subParser('githubCodeBlocks', function (text, options, globals) {
2015-01-19 19:37:21 +08:00
'use strict';
2015-01-16 05:21:33 +08:00
// early exit if option is not enabled
if (!options.ghCodeBlocks) {
return text;
}
2015-01-19 19:37:21 +08:00
text += '~0';
2015-01-16 05:21:33 +08:00
2015-01-19 19:37:21 +08:00
text = text.replace(/(?:^|\n)```(.*)\n([\s\S]*?)\n```/g, function (wholeMatch, m1, m2) {
var language = m1,
codeblock = m2,
end = '\n';
2015-01-16 05:21:33 +08:00
2015-01-19 19:37:21 +08:00
if (options.omitExtraWLInCodeBlocks) {
end = '';
}
2015-01-16 05:21:33 +08:00
2015-01-19 19:37:21 +08:00
codeblock = showdown.subParser('encodeCode')(codeblock);
codeblock = showdown.subParser('detab')(codeblock);
codeblock = codeblock.replace(/^\n+/g, ''); // trim leading newlines
codeblock = codeblock.replace(/\n+$/g, ''); // trim trailing whitespace
2015-01-16 05:21:33 +08:00
codeblock = '<pre><code' + (language ? ' class="' + language + ' language-' + language + '"' : '') + '>' + codeblock + end + '</code></pre>';
2015-01-16 05:21:33 +08:00
2015-01-19 19:37:21 +08:00
return showdown.subParser('hashBlock')(codeblock, options, globals);
});
2015-01-16 05:21:33 +08:00
2015-01-19 19:37:21 +08:00
// attacklab: strip sentinel
text = text.replace(/~0/, '');
2015-01-16 05:21:33 +08:00
2015-01-19 19:37:21 +08:00
return text;
2015-01-16 05:21:33 +08:00
});