heading.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // heading (#, ##, ...)
  2. 'use strict';
  3. var isSpace = require('../common/utils').isSpace;
  4. module.exports = function heading(state, startLine, endLine, silent) {
  5. var ch, level, tmp, token,
  6. pos = state.bMarks[startLine] + state.tShift[startLine],
  7. max = state.eMarks[startLine];
  8. // if it's indented more than 3 spaces, it should be a code block
  9. if (state.sCount[startLine] - state.blkIndent >= 4) { return false; }
  10. ch = state.src.charCodeAt(pos);
  11. if (ch !== 0x23/* # */ || pos >= max) { return false; }
  12. // count heading level
  13. level = 1;
  14. ch = state.src.charCodeAt(++pos);
  15. while (ch === 0x23/* # */ && pos < max && level <= 6) {
  16. level++;
  17. ch = state.src.charCodeAt(++pos);
  18. }
  19. if (level > 6 || (pos < max && !isSpace(ch))) { return false; }
  20. if (silent) { return true; }
  21. // Let's cut tails like ' ### ' from the end of string
  22. max = state.skipSpacesBack(max, pos);
  23. tmp = state.skipCharsBack(max, 0x23, pos); // #
  24. if (tmp > pos && isSpace(state.src.charCodeAt(tmp - 1))) {
  25. max = tmp;
  26. }
  27. state.line = startLine + 1;
  28. token = state.push('heading_open', 'h' + String(level), 1);
  29. token.markup = '########'.slice(0, level);
  30. token.map = [ startLine, state.line ];
  31. token = state.push('inline', '', 0);
  32. token.content = state.src.slice(pos, max).trim();
  33. token.map = [ startLine, state.line ];
  34. token.children = [];
  35. token = state.push('heading_close', 'h' + String(level), -1);
  36. token.markup = '########'.slice(0, level);
  37. return true;
  38. };