headers.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. showdown.subParser('headers', function (text, options, globals) {
  2. 'use strict';
  3. var prefixHeader = options.prefixHeaderId;
  4. // Set text-style headers:
  5. // Header 1
  6. // ========
  7. //
  8. // Header 2
  9. // --------
  10. //
  11. text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm, function (wholeMatch, m1) {
  12. var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),
  13. hID = (options.noHeaderId) ? '' : 'id="' + headerId(m1) + '"',
  14. hashBlock = '<h1' + hID + '>' + spanGamut + '</h1>';
  15. return showdown.subParser('hashBlock')(hashBlock, options, globals);
  16. });
  17. text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm, function (matchFound, m1) {
  18. var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),
  19. hID = (options.noHeaderId) ? '' : 'id="' + headerId(m1) + '"',
  20. hashBlock = '<h2' + hID + '>' + spanGamut + '</h2>';
  21. return showdown.subParser('hashBlock')(hashBlock, options, globals);
  22. });
  23. // atx-style headers:
  24. // # Header 1
  25. // ## Header 2
  26. // ## Header 2 with closing hashes ##
  27. // ...
  28. // ###### Header 6
  29. //
  30. /*
  31. text = text.replace(/
  32. ^(\#{1,6}) // $1 = string of #'s
  33. [ \t]*
  34. (.+?) // $2 = Header text
  35. [ \t]*
  36. \#* // optional closing #'s (not counted)
  37. \n+
  38. /gm, function() {...});
  39. */
  40. text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm, function (wholeMatch, m1, m2) {
  41. var span = showdown.subParser('spanGamut')(m2, options, globals),
  42. hID = (options.noHeaderId) ? '' : 'id="' + headerId(m1) + '"',
  43. header = '<h' + m1.length + hID + '>' + span + '</h' + m1.length + '>';
  44. return showdown.subParser('hashBlock')(header, options, globals);
  45. });
  46. function headerId(m) {
  47. var title, escapedId = m.replace(/[^\w]/g, '').toLowerCase();
  48. if (globals.hashLinkCounts[escapedId]) {
  49. title = escapedId + '-' + (globals.hashLinkCounts[escapedId]++);
  50. } else {
  51. title = escapedId;
  52. globals.hashLinkCounts[escapedId] = 1;
  53. }
  54. // Prefix id to prevent causing inadvertent pre-existing style matches.
  55. if (prefixHeader === true) {
  56. prefixHeader = 'section';
  57. }
  58. if (showdown.helper.isString(prefixHeader)) {
  59. return prefixHeader + title;
  60. }
  61. return title;
  62. }
  63. return text;
  64. });