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