lheading.mjs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // lheading (---, ===)
  2. export default function lheading (state, startLine, endLine/*, silent */) {
  3. const terminatorRules = state.md.block.ruler.getRules('paragraph')
  4. // if it's indented more than 3 spaces, it should be a code block
  5. if (state.sCount[startLine] - state.blkIndent >= 4) { return false }
  6. const oldParentType = state.parentType
  7. state.parentType = 'paragraph' // use paragraph to match terminatorRules
  8. // jump line-by-line until empty one or EOF
  9. let level = 0
  10. let marker
  11. let nextLine = startLine + 1
  12. for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {
  13. // this would be a code block normally, but after paragraph
  14. // it's considered a lazy continuation regardless of what's there
  15. if (state.sCount[nextLine] - state.blkIndent > 3) { continue }
  16. //
  17. // Check for underline in setext header
  18. //
  19. if (state.sCount[nextLine] >= state.blkIndent) {
  20. let pos = state.bMarks[nextLine] + state.tShift[nextLine]
  21. const max = state.eMarks[nextLine]
  22. if (pos < max) {
  23. marker = state.src.charCodeAt(pos)
  24. if (marker === 0x2D/* - */ || marker === 0x3D/* = */) {
  25. pos = state.skipChars(pos, marker)
  26. pos = state.skipSpaces(pos)
  27. if (pos >= max) {
  28. level = (marker === 0x3D/* = */ ? 1 : 2)
  29. break
  30. }
  31. }
  32. }
  33. }
  34. // quirk for blockquotes, this line should already be checked by that rule
  35. if (state.sCount[nextLine] < 0) { continue }
  36. // Some tags can terminate paragraph without empty line.
  37. let terminate = false
  38. for (let i = 0, l = terminatorRules.length; i < l; i++) {
  39. if (terminatorRules[i](state, nextLine, endLine, true)) {
  40. terminate = true
  41. break
  42. }
  43. }
  44. if (terminate) { break }
  45. }
  46. if (!level) {
  47. // Didn't find valid underline
  48. return false
  49. }
  50. const content = state.getLines(startLine, nextLine, state.blkIndent, false).trim()
  51. state.line = nextLine + 1
  52. const token_o = state.push('heading_open', 'h' + String(level), 1)
  53. token_o.markup = String.fromCharCode(marker)
  54. token_o.map = [startLine, state.line]
  55. const token_i = state.push('inline', '', 0)
  56. token_i.content = content
  57. token_i.map = [startLine, state.line - 1]
  58. token_i.children = []
  59. const token_c = state.push('heading_close', 'h' + String(level), -1)
  60. token_c.markup = String.fromCharCode(marker)
  61. state.parentType = oldParentType
  62. return true
  63. }