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