1""" Atex heading (#, ##, ...) """
2from __future__ import annotations
3
4import logging
5
6from ..common.utils import isStrSpace
7from .state_block import StateBlock
8
9LOGGER = logging.getLogger(__name__)
10
11
12def heading(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
13 LOGGER.debug("entering heading: %s, %s, %s, %s", state, startLine, endLine, silent)
14
15 pos = state.bMarks[startLine] + state.tShift[startLine]
16 maximum = state.eMarks[startLine]
17
18 if state.is_code_block(startLine):
19 return False
20
21 ch: str | None = state.src[pos]
22
23 if ch != "#" or pos >= maximum:
24 return False
25
26 # count heading level
27 level = 1
28 pos += 1
29 try:
30 ch = state.src[pos]
31 except IndexError:
32 ch = None
33 while ch == "#" and pos < maximum and level <= 6:
34 level += 1
35 pos += 1
36 try:
37 ch = state.src[pos]
38 except IndexError:
39 ch = None
40
41 if level > 6 or (pos < maximum and not isStrSpace(ch)):
42 return False
43
44 if silent:
45 return True
46
47 # Let's cut tails like ' ### ' from the end of string
48
49 maximum = state.skipSpacesBack(maximum, pos)
50 tmp = state.skipCharsStrBack(maximum, "#", pos)
51 if tmp > pos and isStrSpace(state.src[tmp - 1]):
52 maximum = tmp
53
54 state.line = startLine + 1
55
56 token = state.push("heading_open", "h" + str(level), 1)
57 token.markup = "########"[:level]
58 token.map = [startLine, state.line]
59
60 token = state.push("inline", "", 0)
61 token.content = state.src[pos:maximum].strip()
62 token.map = [startLine, state.line]
63 token.children = []
64
65 token = state.push("heading_close", "h" + str(level), -1)
66 token.markup = "########"[:level]
67
68 return True