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 ch: str | None = state.src[pos]
23
24 if ch != "#" or pos >= maximum:
25 return False
26
27 # count heading level
28 level = 1
29 pos += 1
30 try:
31 ch = state.src[pos]
32 except IndexError:
33 ch = None
34 while ch == "#" and pos < maximum and level <= 6:
35 level += 1
36 pos += 1
37 try:
38 ch = state.src[pos]
39 except IndexError:
40 ch = None
41
42 if level > 6 or (pos < maximum and not isStrSpace(ch)):
43 return False
44
45 if silent:
46 return True
47
48 # Let's cut tails like ' ### ' from the end of string
49
50 maximum = state.skipSpacesBack(maximum, pos)
51 tmp = state.skipCharsStrBack(maximum, "#", pos)
52 if tmp > pos and isStrSpace(state.src[tmp - 1]):
53 maximum = tmp
54
55 state.line = startLine + 1
56
57 token = state.push("heading_open", "h" + str(level), 1)
58 token.markup = "########"[:level]
59 token.map = [startLine, state.line]
60
61 token = state.push("inline", "", 0)
62 token.content = state.src[pos:maximum].strip()
63 token.map = [startLine, state.line]
64 token.children = []
65
66 token = state.push("heading_close", "h" + str(level), -1)
67 token.markup = "########"[:level]
68
69 return True