1# Process admonitions and pass to cb.
2
3from __future__ import annotations
4
5from collections.abc import Callable, Sequence
6from contextlib import suppress
7import re
8from typing import TYPE_CHECKING
9
10from markdown_it import MarkdownIt
11from markdown_it.rules_block import StateBlock
12
13from mdit_py_plugins.utils import is_code_block
14
15if TYPE_CHECKING:
16 from markdown_it.renderer import RendererProtocol
17 from markdown_it.token import Token
18 from markdown_it.utils import EnvType, OptionsDict
19
20
21def _get_multiple_tags(params: str) -> tuple[list[str], str]:
22 """Check for multiple tags when the title is double quoted."""
23 # This matches what r'^\s*(?P<tokens>[^"]+)\s+"(?P<title>.*)"\S*$' matches,
24 # but the tokens end on a non-space and only the last quote can close the title,
25 # so a long run of spaces or quotes cannot make it backtrack quadratically (#143).
26 re_tags = re.compile(
27 r'^\s*(?P<tokens>[^"\s](?:[^"]*[^"\s])?)\s+"(?P<title>.*)"[^\s"]*$'
28 )
29 match = re_tags.match(params)
30 if match:
31 tags = match["tokens"].strip().split(" ")
32 return [tag.lower() for tag in tags], match["title"]
33 raise ValueError("No match found for parameters")
34
35
36def _get_tag(_params: str) -> tuple[list[str], str]:
37 """Separate the tag name from the admonition title."""
38 params = _params.strip()
39 if not params:
40 return [""], ""
41
42 with suppress(ValueError):
43 return _get_multiple_tags(params)
44
45 tag, *_title = params.split(" ")
46 joined = " ".join(_title)
47
48 title = ""
49 if not joined:
50 title = tag.title()
51 elif joined != '""': # Specifically check for no title
52 title = joined
53 return [tag.lower()], title
54
55
56def _validate(params: str) -> bool:
57 """Validate the presence of the tag name after the marker."""
58 tag = params.strip().split(" ", 1)[-1] or ""
59 return bool(tag)
60
61
62MARKER_LEN = 3 # Regardless of extra characters, block indent stays the same
63MARKERS = ("!!!", "???", "???+")
64MARKER_CHARS = {_m[0] for _m in MARKERS}
65MAX_MARKER_LEN = max(len(_m) for _m in MARKERS)
66
67
68def _extra_classes(markup: str) -> list[str]:
69 """Return the list of additional classes based on the markup."""
70 if markup.startswith("?"):
71 if markup.endswith("+"):
72 return ["is-collapsible collapsible-open"]
73 return ["is-collapsible collapsible-closed"]
74 return []
75
76
77def admonition(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
78 if is_code_block(state, startLine):
79 return False
80
81 start = state.bMarks[startLine] + state.tShift[startLine]
82 maximum = state.eMarks[startLine]
83
84 # Check out the first character quickly, which should filter out most of non-containers
85 if state.src[start] not in MARKER_CHARS:
86 return False
87
88 # Check out the rest of the marker string
89 marker = ""
90 marker_len = MAX_MARKER_LEN
91 while marker_len > 0:
92 marker_pos = start + marker_len
93 markup = state.src[start:marker_pos]
94 if markup in MARKERS:
95 marker = markup
96 break
97 marker_len -= 1
98 else:
99 return False
100
101 params = state.src[marker_pos:maximum]
102
103 if not _validate(params):
104 return False
105
106 # Since start is found, we can report success here in validation mode
107 if silent:
108 return True
109
110 old_parent = state.parentType
111 old_line_max = state.lineMax
112 old_indent = state.blkIndent
113
114 blk_start = marker_pos
115 while blk_start < maximum and state.src[blk_start] == " ":
116 blk_start += 1
117
118 state.parentType = "admonition"
119 # Correct block indentation when extra marker characters are present
120 marker_alignment_correction = MARKER_LEN - len(marker)
121 state.blkIndent += blk_start - start + marker_alignment_correction
122
123 was_empty = False
124
125 # Search for the end of the block
126 next_line = startLine
127 while True:
128 next_line += 1
129 if next_line >= endLine:
130 # unclosed block should be autoclosed by end of document.
131 # also block seems to be autoclosed by end of parent
132 break
133 pos = state.bMarks[next_line] + state.tShift[next_line]
134 maximum = state.eMarks[next_line]
135 is_empty = state.sCount[next_line] < state.blkIndent
136
137 # two consecutive empty lines autoclose the block
138 if is_empty and was_empty:
139 break
140 was_empty = is_empty
141
142 if pos < maximum and state.sCount[next_line] < state.blkIndent:
143 # non-empty line with negative indent should stop the block:
144 # - !!!
145 # test
146 break
147
148 # this will prevent lazy continuations from ever going past our end marker
149 state.lineMax = next_line
150
151 tags, title = _get_tag(params)
152 tag = tags[0]
153
154 token = state.push("admonition_open", "div", 1)
155 token.markup = markup
156 token.block = True
157 token.attrs = {"class": " ".join(["admonition", *tags, *_extra_classes(markup)])}
158 token.meta = {"tag": tag}
159 token.content = title
160 token.info = params
161 token.map = [startLine, next_line]
162
163 if title:
164 title_markup = f"{markup} {tag}"
165 token = state.push("admonition_title_open", "p", 1)
166 token.markup = title_markup
167 token.attrs = {"class": "admonition-title"}
168 token.map = [startLine, startLine + 1]
169
170 token = state.push("inline", "", 0)
171 token.content = title
172 token.map = [startLine, startLine + 1]
173 token.children = []
174
175 token = state.push("admonition_title_close", "p", -1)
176
177 state.md.block.tokenize(state, startLine + 1, next_line)
178
179 token = state.push("admonition_close", "div", -1)
180 token.markup = markup
181 token.block = True
182
183 state.parentType = old_parent
184 state.lineMax = old_line_max
185 state.blkIndent = old_indent
186 state.line = next_line
187
188 return True
189
190
191def admon_plugin(md: MarkdownIt, render: Callable[..., str] | None = None) -> None:
192 """Plugin to use
193 `python-markdown style admonitions
194 <https://python-markdown.github.io/extensions/admonition>`_.
195
196 .. code-block:: md
197
198 !!! note
199 *content*
200
201 `And mkdocs-style collapsible blocks
202 <https://squidfunk.github.io/mkdocs-material/reference/admonitions/#collapsible-blocks>`_.
203
204 .. code-block:: md
205
206 ???+ note
207 *content*
208
209 Note, this is ported from
210 `markdown-it-admon
211 <https://github.com/commenthol/markdown-it-admon>`_.
212 """
213
214 def renderDefault(
215 self: RendererProtocol,
216 tokens: Sequence[Token],
217 idx: int,
218 _options: OptionsDict,
219 env: EnvType,
220 ) -> str:
221 return self.renderToken(tokens, idx, _options, env) # type: ignore[attr-defined,no-any-return]
222
223 render = render or renderDefault
224
225 md.add_render_rule("admonition_open", render)
226 md.add_render_rule("admonition_close", render)
227 md.add_render_rule("admonition_title_open", render)
228 md.add_render_rule("admonition_title_close", render)
229
230 md.block.ruler.before(
231 "fence",
232 "admonition",
233 admonition,
234 {"alt": ["paragraph", "reference", "blockquote", "list"]},
235 )