githubCodeBlocks.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /**
  2. * Handle github codeblocks prior to running HashHTML so that
  3. * HTML contained within the codeblock gets escaped properly
  4. * Example:
  5. * ```ruby
  6. * def hello_world(x)
  7. * puts "Hello, #{x}"
  8. * end
  9. * ```
  10. */
  11. showdown.subParser('githubCodeBlocks', function (text, options, globals) {
  12. 'use strict';
  13. text += '~0';
  14. text = text.replace(/(?:^|\n)```(.*)\n([\s\S]*?)\n```/g, function (wholeMatch, m1, m2) {
  15. var language = m1,
  16. codeblock = m2,
  17. end = '\n';
  18. if (options.omitExtraWLInCodeBlocks) {
  19. end = '';
  20. }
  21. codeblock = showdown.subParser('encodeCode')(codeblock);
  22. codeblock = showdown.subParser('detab')(codeblock);
  23. codeblock = codeblock.replace(/^\n+/g, ''); // trim leading newlines
  24. codeblock = codeblock.replace(/\n+$/g, ''); // trim trailing whitespace
  25. codeblock = '<pre><code' + (language ? ' class="' + language + '"' : '') + '>' + codeblock + end + '</code></pre>';
  26. return showdown.subParser('hashBlock')(codeblock, options, globals);
  27. });
  28. // attacklab: strip sentinel
  29. text = text.replace(/~0/, '');
  30. return text;
  31. });