lheading.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # lheading (---, ==)
  2. import logging
  3. from .state_block import StateBlock
  4. LOGGER = logging.getLogger(__name__)
  5. def lheading(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
  6. LOGGER.debug("entering lheading: %s, %s, %s, %s", state, startLine, endLine, silent)
  7. level = None
  8. nextLine = startLine + 1
  9. ruler = state.md.block.ruler
  10. terminatorRules = ruler.getRules("paragraph")
  11. if state.is_code_block(startLine):
  12. return False
  13. oldParentType = state.parentType
  14. state.parentType = "paragraph" # use paragraph to match terminatorRules
  15. # jump line-by-line until empty one or EOF
  16. while nextLine < endLine and not state.isEmpty(nextLine):
  17. # this would be a code block normally, but after paragraph
  18. # it's considered a lazy continuation regardless of what's there
  19. if state.sCount[nextLine] - state.blkIndent > 3:
  20. nextLine += 1
  21. continue
  22. # Check for underline in setext header
  23. if state.sCount[nextLine] >= state.blkIndent:
  24. pos = state.bMarks[nextLine] + state.tShift[nextLine]
  25. maximum = state.eMarks[nextLine]
  26. if pos < maximum:
  27. marker = state.src[pos]
  28. if marker in ("-", "="):
  29. pos = state.skipCharsStr(pos, marker)
  30. pos = state.skipSpaces(pos)
  31. # /* = */
  32. if pos >= maximum:
  33. level = 1 if marker == "=" else 2
  34. break
  35. # quirk for blockquotes, this line should already be checked by that rule
  36. if state.sCount[nextLine] < 0:
  37. nextLine += 1
  38. continue
  39. # Some tags can terminate paragraph without empty line.
  40. terminate = False
  41. for terminatorRule in terminatorRules:
  42. if terminatorRule(state, nextLine, endLine, True):
  43. terminate = True
  44. break
  45. if terminate:
  46. break
  47. nextLine += 1
  48. if not level:
  49. # Didn't find valid underline
  50. return False
  51. content = state.getLines(startLine, nextLine, state.blkIndent, False).strip()
  52. state.line = nextLine + 1
  53. token = state.push("heading_open", "h" + str(level), 1)
  54. token.markup = marker
  55. token.map = [startLine, state.line]
  56. token = state.push("inline", "", 0)
  57. token.content = content
  58. token.map = [startLine, state.line - 1]
  59. token.children = []
  60. token = state.push("heading_close", "h" + str(level), -1)
  61. token.markup = marker
  62. state.parentType = oldParentType
  63. return True