Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/mdit_py_plugins/dollarmath/index.py: 76%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

190 statements  

1from __future__ import annotations 

2 

3from collections.abc import Callable, Sequence 

4import re 

5from typing import TYPE_CHECKING, Any 

6 

7from markdown_it import MarkdownIt 

8from markdown_it.common.utils import escapeHtml, isWhiteSpace 

9from markdown_it.rules_block import StateBlock 

10from markdown_it.rules_inline import StateInline 

11 

12from mdit_py_plugins.utils import is_code_block 

13 

14if TYPE_CHECKING: 

15 from markdown_it.renderer import RendererProtocol 

16 from markdown_it.token import Token 

17 from markdown_it.utils import EnvType, OptionsDict 

18 

19 

20def dollarmath_plugin( 

21 md: MarkdownIt, 

22 *, 

23 allow_labels: bool = True, 

24 allow_space: bool = True, 

25 allow_digits: bool = True, 

26 allow_blank_lines: bool = True, 

27 double_inline: bool = False, 

28 label_normalizer: Callable[[str], str] | None = None, 

29 renderer: Callable[[str, dict[str, Any]], str] | None = None, 

30 label_renderer: Callable[[str], str] | None = None, 

31) -> None: 

32 """Plugin for parsing dollar enclosed math, 

33 e.g. inline: ``$a=1$``, block: ``$$b=2$$`` 

34 

35 This is an improved version of ``texmath``; it is more performant, 

36 and handles ``\\`` escaping properly and allows for more configuration. 

37 

38 :param allow_labels: Capture math blocks with label suffix, e.g. ``$$a=1$$ (eq1)`` 

39 :param allow_space: Parse inline math when there is space 

40 after/before the opening/closing ``$``, e.g. ``$ a $`` 

41 :param allow_digits: Parse inline math when there is a digit 

42 before/after the opening/closing ``$``, e.g. ``1$`` or ``$2``. 

43 This is useful when also using currency. 

44 :param allow_blank_lines: Allow blank lines inside ``$$``. Note that blank lines are 

45 not allowed in LaTeX, executablebooks/markdown-it-dollarmath, or the Github or 

46 StackExchange markdown dialects. Hoever, they have special semantics if used 

47 within Sphinx `..math` admonitions, so are allowed for backwards-compatibility. 

48 :param double_inline: Search for double-dollar math within inline contexts 

49 :param label_normalizer: Function to normalize the label, 

50 by default replaces whitespace with `-` 

51 :param renderer: Function to render content: `(str, {"display_mode": bool}) -> str`, 

52 by default escapes HTML. 

53 Its return value is placed inside the element as is, 

54 so a custom renderer is responsible for escaping it (the default renderer does). 

55 :param label_renderer: Function to render labels, by default creates anchor 

56 

57 The plugin does not typeset the math. 

58 Each token becomes an HTML element holding the rendered content, 

59 and typesetting is left to a library such as MathJax or KaTeX: 

60 

61 - ``math_inline`` (``$a$``): 

62 ``<span class="math inline">``, with ``display_mode=False`` 

63 - ``math_inline_double`` (``$$a$$`` inside a paragraph, with ``double_inline``): 

64 ``<div class="math inline">``, with ``display_mode=True`` 

65 - ``math_block`` (``$$a$$`` on its own lines): 

66 ``<div class="math block">``, with ``display_mode=True`` 

67 - ``math_block_label`` (``$$a$$ (eq1)``): 

68 ``<div id="eq1" class="math block">``, starting with the label anchor, 

69 with ``display_mode=True`` 

70 

71 The tag says how to display the math (``div`` for display, ``span`` for inline), 

72 and the class says where it was written (``inline`` inside a paragraph, 

73 ``block`` on its own lines), as in executablebooks/markdown-it-dollarmath. 

74 """ 

75 if label_normalizer is None: 

76 label_normalizer = lambda label: re.sub(r"\s+", "-", label) # noqa: E731 

77 

78 md.inline.ruler.before( 

79 "escape", 

80 "math_inline", 

81 math_inline_dollar(allow_space, allow_digits, double_inline), 

82 ) 

83 md.block.ruler.before( 

84 "fence", 

85 "math_block", 

86 math_block_dollar(allow_labels, label_normalizer, allow_blank_lines), 

87 ) 

88 

89 # TODO the current render rules are really just for testing 

90 # would be good to allow "proper" math rendering, 

91 # e.g. https://github.com/roniemartinez/latex2mathml 

92 

93 _renderer = ( 

94 (lambda content, _: escapeHtml(content)) if renderer is None else renderer 

95 ) 

96 

97 _label_renderer: Callable[[str], str] 

98 if label_renderer is None: 

99 _label_renderer = ( # noqa: E731 

100 lambda label: ( 

101 f'<a href="#{escapeHtml(label)}" class="mathlabel" title="Permalink to this equation">¶</a>' 

102 ) 

103 ) 

104 else: 

105 _label_renderer = label_renderer 

106 

107 def render_math_inline( 

108 self: RendererProtocol, 

109 tokens: Sequence[Token], 

110 idx: int, 

111 options: OptionsDict, 

112 env: EnvType, 

113 ) -> str: 

114 content = _renderer(str(tokens[idx].content).strip(), {"display_mode": False}) 

115 return f'<span class="math inline">{content}</span>' 

116 

117 def render_math_inline_double( 

118 self: RendererProtocol, 

119 tokens: Sequence[Token], 

120 idx: int, 

121 options: OptionsDict, 

122 env: EnvType, 

123 ) -> str: 

124 content = _renderer(str(tokens[idx].content).strip(), {"display_mode": True}) 

125 return f'<div class="math inline">{content}</div>' 

126 

127 def render_math_block( 

128 self: RendererProtocol, 

129 tokens: Sequence[Token], 

130 idx: int, 

131 options: OptionsDict, 

132 env: EnvType, 

133 ) -> str: 

134 content = _renderer(str(tokens[idx].content).strip(), {"display_mode": True}) 

135 return f'<div class="math block">\n{content}\n</div>\n' 

136 

137 def render_math_block_label( 

138 self: RendererProtocol, 

139 tokens: Sequence[Token], 

140 idx: int, 

141 options: OptionsDict, 

142 env: EnvType, 

143 ) -> str: 

144 content = _renderer(str(tokens[idx].content).strip(), {"display_mode": True}) 

145 _id = escapeHtml(tokens[idx].info) 

146 label = _label_renderer(tokens[idx].info) 

147 return f'<div id="{_id}" class="math block">\n{label}\n{content}\n</div>\n' 

148 

149 md.add_render_rule("math_inline", render_math_inline) 

150 md.add_render_rule("math_inline_double", render_math_inline_double) 

151 

152 md.add_render_rule("math_block", render_math_block) 

153 md.add_render_rule("math_block_label", render_math_block_label) 

154 

155 

156def is_escaped(state: StateInline, back_pos: int, mod: int = 0) -> bool: 

157 """Test if dollar is escaped.""" 

158 # count how many \ are before the current position 

159 backslashes = 0 

160 while back_pos >= 0: 

161 back_pos = back_pos - 1 

162 if state.src[back_pos] == "\\": 

163 backslashes += 1 

164 else: 

165 break 

166 

167 if not backslashes: 

168 return False 

169 

170 # if an odd number of \ then ignore 

171 if (backslashes % 2) != mod: # noqa: SIM103 

172 return True 

173 

174 return False 

175 

176 

177def math_inline_dollar( 

178 allow_space: bool = True, allow_digits: bool = True, allow_double: bool = False 

179) -> Callable[[StateInline, bool], bool]: 

180 """Generate inline dollar rule. 

181 

182 :param allow_space: Parse inline math when there is space 

183 after/before the opening/closing ``$``, e.g. ``$ a $`` 

184 :param allow_digits: Parse inline math when there is a digit 

185 before/after the opening/closing ``$``, e.g. ``1$`` or ``$2``. 

186 This is useful when also using currency. 

187 :param allow_double: Search for double-dollar math within inline contexts 

188 

189 """ 

190 

191 def _math_inline_dollar(state: StateInline, silent: bool) -> bool: 

192 """Inline dollar rule. 

193 

194 - Initial check: 

195 - check if first character is a $ 

196 - check if the first character is escaped 

197 - check if the next character is a space (if not allow_space) 

198 - check if the next character is a digit (if not allow_digits) 

199 - Advance one, if allow_double 

200 - Find closing (advance one, if allow_double) 

201 - Check closing: 

202 - check if the previous character is a space (if not allow_space) 

203 - check if the next character is a digit (if not allow_digits) 

204 - Check empty content 

205 """ 

206 

207 # TODO options: 

208 # even/odd backslash escaping 

209 

210 if state.src[state.pos] != "$": 

211 return False 

212 

213 if not allow_space: 

214 # whitespace not allowed straight after opening $ 

215 try: 

216 if isWhiteSpace(ord(state.src[state.pos + 1])): 

217 return False 

218 except IndexError: 

219 return False 

220 

221 if not allow_digits: 

222 # digit not allowed straight before opening $ 

223 try: 

224 if state.src[state.pos - 1].isdigit(): 

225 return False 

226 except IndexError: 

227 pass 

228 

229 if is_escaped(state, state.pos): 

230 return False 

231 

232 try: 

233 is_double = allow_double and state.src[state.pos + 1] == "$" 

234 except IndexError: 

235 return False 

236 

237 # find closing $ 

238 pos = state.pos + 1 + (1 if is_double else 0) 

239 found_closing = False 

240 while not found_closing: 

241 try: 

242 end = state.src.index("$", pos) 

243 except ValueError: 

244 return False 

245 

246 if is_escaped(state, end): 

247 pos = end + 1 

248 continue 

249 

250 try: 

251 if is_double and state.src[end + 1] != "$": 

252 pos = end + 1 

253 continue 

254 except IndexError: 

255 return False 

256 

257 if is_double: 

258 end += 1 

259 

260 found_closing = True 

261 

262 if not found_closing: 

263 return False 

264 

265 if not allow_space: 

266 # whitespace not allowed straight before closing $ 

267 try: 

268 if isWhiteSpace(ord(state.src[end - 1])): 

269 return False 

270 except IndexError: 

271 return False 

272 

273 if not allow_digits: 

274 # digit not allowed straight after closing $ 

275 try: 

276 if state.src[end + 1].isdigit(): 

277 return False 

278 except IndexError: 

279 pass 

280 

281 text = ( 

282 state.src[state.pos + 2 : end - 1] 

283 if is_double 

284 else state.src[state.pos + 1 : end] 

285 ) 

286 

287 # ignore empty 

288 if not text: 

289 return False 

290 

291 if not silent: 

292 token = state.push( 

293 "math_inline_double" if is_double else "math_inline", "math", 0 

294 ) 

295 token.content = text 

296 token.markup = "$$" if is_double else "$" 

297 

298 state.pos = end + 1 

299 

300 return True 

301 

302 return _math_inline_dollar 

303 

304 

305# reversed end of block dollar equation, with equation label 

306DOLLAR_EQNO_REV = re.compile(r"^\s*\)([^)$\r\n]+?)\(\s*\${2}") 

307 

308 

309def _math_block_content( 

310 state: StateBlock, startLine: int, startPos: int, endLine: int, end: int 

311) -> str: 

312 """Extract math body, omitting parent container prefixes on each line.""" 

313 content_start = startPos + 2 

314 if startLine == endLine: 

315 return state.src[content_start:end] 

316 

317 parts: list[str] = [state.src[content_start : state.eMarks[startLine]], "\n"] 

318 for line in range(startLine + 1, endLine): 

319 parts.append(state.src[state.bMarks[line] : state.eMarks[line]]) 

320 parts.append("\n") 

321 parts.append(state.src[state.bMarks[endLine] : end]) 

322 return "".join(parts) 

323 

324 

325def math_block_dollar( 

326 allow_labels: bool = True, 

327 label_normalizer: Callable[[str], str] | None = None, 

328 allow_blank_lines: bool = False, 

329) -> Callable[[StateBlock, int, int, bool], bool]: 

330 """Generate block dollar rule.""" 

331 

332 def _math_block_dollar( 

333 state: StateBlock, startLine: int, endLine: int, silent: bool 

334 ) -> bool: 

335 # TODO internal backslash escaping 

336 

337 if is_code_block(state, startLine): 

338 return False 

339 

340 haveEndMarker = False 

341 startPos = state.bMarks[startLine] + state.tShift[startLine] 

342 end = state.eMarks[startLine] 

343 

344 if startPos + 2 > end: 

345 return False 

346 

347 if state.src[startPos] != "$" or state.src[startPos + 1] != "$": 

348 return False 

349 

350 # search for end of block 

351 nextLine = startLine 

352 label = None 

353 

354 # search for end of block on same line 

355 lineText = state.src[startPos:end] 

356 if len(lineText.strip()) > 3: 

357 if lineText.strip().endswith("$$"): 

358 haveEndMarker = True 

359 end = end - 2 - (len(lineText) - len(lineText.strip())) 

360 else: 

361 # a closing marker present but not at end of line and not a label 

362 # suffix is ambiguous, so don't greedily scan subsequent lines for it 

363 trailing_close = "$$" in lineText[2:] 

364 if allow_labels: 

365 # reverse the line and match 

366 eqnoMatch = DOLLAR_EQNO_REV.match(lineText[::-1]) 

367 if eqnoMatch: 

368 haveEndMarker = True 

369 label = eqnoMatch.group(1)[::-1] 

370 end = end - eqnoMatch.end() 

371 elif trailing_close: 

372 return False 

373 elif trailing_close: 

374 return False 

375 

376 # search for end of block on subsequent line 

377 if not haveEndMarker: 

378 while True: 

379 nextLine += 1 

380 if nextLine >= endLine: 

381 break 

382 

383 start = state.bMarks[nextLine] + state.tShift[nextLine] 

384 end = state.eMarks[nextLine] 

385 

386 lineText = state.src[start:end] 

387 

388 if lineText.strip().endswith("$$"): 

389 haveEndMarker = True 

390 end = end - 2 - (len(lineText) - len(lineText.strip())) 

391 break 

392 if lineText.strip() == "" and not allow_blank_lines: 

393 break # blank lines are not allowed within $$ 

394 

395 # reverse the line and match 

396 if allow_labels: 

397 eqnoMatch = DOLLAR_EQNO_REV.match(lineText[::-1]) 

398 if eqnoMatch: 

399 haveEndMarker = True 

400 label = eqnoMatch.group(1)[::-1] 

401 end = end - eqnoMatch.end() 

402 break 

403 

404 if not haveEndMarker: 

405 return False 

406 

407 state.line = nextLine + (1 if haveEndMarker else 0) 

408 

409 token = state.push("math_block_label" if label else "math_block", "math", 0) 

410 token.block = True 

411 token.content = _math_block_content(state, startLine, startPos, nextLine, end) 

412 token.markup = "$$" 

413 token.map = [startLine, state.line] 

414 if label: 

415 token.info = label if label_normalizer is None else label_normalizer(label) 

416 

417 return True 

418 

419 return _math_block_dollar