Coverage for src/pyTRLCConverter/marko/md2rst_renderer.py: 81%

102 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-12-01 11:26 +0000

1"""reStructuredText renderer for Marko. 

2 It is used to convert CommonMark AST to reStructuredText format. 

3 

4 Author: Andreas Merkle (andreas.merkle@newtec.de) 

5""" 

6 

7# pyTRLCConverter - A tool to convert TRLC files to specific formats. 

8# Copyright (c) 2024 - 2026 NewTec GmbH 

9# 

10# This file is part of pyTRLCConverter program. 

11# 

12# The pyTRLCConverter program is free software: you can redistribute it and/or modify it under 

13# the terms of the GNU General Public License as published by the Free Software Foundation, 

14# either version 3 of the License, or (at your option) any later version. 

15# 

16# The pyTRLCConverter program is distributed in the hope that it will be useful, but 

17# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 

18# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 

19# 

20# You should have received a copy of the GNU General Public License along with pyTRLCConverter. 

21# If not, see <https://www.gnu.org/licenses/>. 

22 

23# Imports ********************************************************************** 

24 

25from __future__ import annotations 

26import hashlib 

27import os 

28from typing import TYPE_CHECKING, Any, cast, Optional 

29from marko import Renderer 

30from pyTRLCConverter.plantuml import PlantUML 

31 

32if TYPE_CHECKING: 

33 from . import block, inline 

34 

35# Variables ******************************************************************** 

36 

37# Classes ********************************************************************** 

38 

39# pylint: disable-next=too-many-public-methods 

40class Md2RstRenderer(Renderer): 

41 # lobster-trace: SwRequirements.sw_req_rst_render_md 

42 # lobster-trace: SwRequirements.sw_req_rst_render_list 

43 # lobster-trace: SwRequirements.sw_req_rst_render_plantuml 

44 # lobster-trace: SwRequirements.sw_req_plantuml 

45 """Renderer for reStructuredText output. 

46 

47 Converts CommonMark Markdown to reStructuredText format. Fenced code 

48 blocks tagged ``plantuml`` are rendered as SVG images referenced via 

49 ``.. image::`` directives. 

50 """ 

51 

52 # Destination directory where generated PNG images are written. 

53 image_dir: Optional[str] = None 

54 

55 # List of ``(source_path, local_name)`` tuples collected during rendering. 

56 external_files: Optional[list] = None 

57 

58 def render_paragraph(self, element: block.Paragraph) -> str: 

59 """ 

60 Renders a paragraph element. 

61 

62 Args: 

63 element (block.Paragraph): The paragraph element to render. 

64 

65 Returns: 

66 str: The rendered paragraph as a string. 

67 """ 

68 return self.render_children(element) + "\n\n" 

69 

70 def render_list(self, element: block.List) -> str: 

71 """ 

72 Renders a list (ordered or unordered) element. 

73 

74 Args: 

75 element (block.List): The list element to render. 

76 

77 Returns: 

78 str: The rendered list as a string. 

79 """ 

80 items = [] 

81 

82 for index, child in enumerate(element.children): 

83 marker = f"{index + 1}." if element.ordered else "-" 

84 item = self.render_list_item(child, marker) 

85 items.append(item) 

86 

87 return "\n".join(items) + "\n" 

88 

89 def render_list_item(self, element: block.ListItem, marker="-") -> str: 

90 """ 

91 Renders a list item element. 

92 

93 Args: 

94 element (block.ListItem): The list item element to render. 

95 marker (str, optional): The marker to use for the list item. Defaults to "*". 

96 

97 Returns: 

98 str: The rendered list item as a string. 

99 """ 

100 return self._indent_list_item(marker, self.render_children(element)) 

101 

102 @staticmethod 

103 def _indent_list_item(marker: str, content: str) -> str: 

104 """ 

105 Prefixes the list item content with its marker and indents all following lines by the marker 

106 width. This keeps continuation lines, nested lists and further paragraphs inside the list item. 

107 Nested lists get their indentation from the list item that contains them. 

108 

109 Args: 

110 marker (str): The marker of the list item, e.g. "-" or "1.". 

111 content (str): The rendered content of the list item. 

112 

113 Returns: 

114 str: The rendered list item as a string. 

115 """ 

116 lines = content.rstrip("\n").split("\n") 

117 indent = " " * (len(marker) + 1) 

118 indented = [indent + line if line.strip() else "" for line in lines[1:]] 

119 

120 return f"{marker} " + "\n".join(lines[:1] + indented) + "\n" 

121 

122 def render_quote(self, element: block.Quote) -> str: 

123 """ 

124 Renders a blockquote element. 

125 

126 Args: 

127 element (block.Quote): The blockquote element to render. 

128 

129 Returns: 

130 str: The rendered blockquote as a string. 

131 """ 

132 quote = self.render_children(element) 

133 quoted = "\n".join([f" {line}" if line.strip() else "" for line in quote.splitlines()]) 

134 

135 return quoted + "\n\n" 

136 

137 def render_fenced_code(self, element: block.FencedCode) -> str: 

138 """Render a fenced code block as reStructuredText. 

139 

140 If the language tag is ``plantuml``, the diagram source is rendered as 

141 a PNG image referenced via a ``.. image::`` directive. If PlantUML is 

142 not available, an error paragraph is emitted instead. All other fenced 

143 code blocks are rendered as ``.. code-block::`` directives. 

144 

145 Args: 

146 element (block.FencedCode): The fenced code block element to render. 

147 

148 Returns: 

149 str: The rendered fenced code block as a string. 

150 """ 

151 if element.lang == "plantuml": 

152 return self._render_plantuml(element.children[0].children) 

153 

154 lang = element.lang or "" 

155 code = element.children[0].children # type: ignore 

156 

157 return f".. code-block:: {lang}\n\n " + "\n ".join(code.splitlines()) + "\n\n" 

158 

159 def _render_plantuml(self, diagram_source: str) -> str: 

160 """Render a PlantUML diagram as a PNG image reference. 

161 

162 Generates SVG bytes via the PlantUML tool, writes them to a temporary 

163 file under :attr:`image_dir`, registers the file in 

164 :attr:`external_files` so the converter can copy it next to the RST 

165 document, and returns a ``.. image::`` directive referencing the image 

166 by its local name. 

167 

168 On failure an error paragraph is emitted instead. 

169 

170 Args: 

171 diagram_source (str): The PlantUML diagram source text. 

172 

173 Returns: 

174 str: RST fragment referencing the generated image, or an error 

175 paragraph if image generation failed. 

176 """ 

177 assert Md2RstRenderer.image_dir is not None 

178 assert Md2RstRenderer.external_files is not None 

179 

180 try: 

181 plantuml = PlantUML() 

182 svg_bytes = plantuml.generate_to_bytes("svg", diagram_source) 

183 

184 digest = hashlib.sha1(diagram_source.encode("utf-8")).hexdigest()[:12] 

185 local_name = f"plantuml_{digest}.svg" 

186 svg_path = os.path.join(Md2RstRenderer.image_dir, local_name) 

187 with open(svg_path, "wb") as svg_file: 

188 svg_file.write(svg_bytes) 

189 

190 Md2RstRenderer.external_files.append((svg_path, local_name)) 

191 

192 result = f".. image:: {local_name}\n\n" 

193 except (FileNotFoundError, OSError) as exc: 

194 result = f"[PlantUML error: {exc}]\n\n" 

195 

196 return result 

197 

198 def render_code_block(self, element: block.CodeBlock) -> str: 

199 """ 

200 Renders a code block element. 

201 

202 Args: 

203 element (block.CodeBlock): The code block element to render. 

204 

205 Returns: 

206 str: The rendered code block as a string. 

207 """ 

208 return self.render_fenced_code(cast("block.FencedCode", element)) 

209 

210 def render_html_block(self, element: block.HTMLBlock) -> str: 

211 """ 

212 Renders a raw HTML block element. 

213 

214 Args: 

215 element (block.HTMLBlock): The HTML block element to render. 

216 

217 Returns: 

218 str: The rendered HTML block as a string. 

219 """ 

220 # reStructuredText does not support raw HTML, so output as a literal block. 

221 body = element.body 

222 

223 return "::\n\n " + "\n ".join(body.splitlines()) + "\n\n" 

224 

225 # pylint: disable-next=unused-argument 

226 def render_thematic_break(self, element: block.ThematicBreak) -> str: 

227 """ 

228 Renders a thematic break (horizontal rule) element as a empty line. 

229 

230 Args: 

231 element (block.ThematicBreak): The thematic break element to render. 

232 

233 Returns: 

234 str: The rendered thematic break as a empty rst line. 

235 """ 

236 return "\n|\n" 

237 

238 def render_heading(self, element: block.Heading) -> str: 

239 """ 

240 Renders a heading element as a rubric. 

241 

242 Args: 

243 element (block.Heading): The heading element to render. 

244 

245 Returns: 

246 str: The rendered heading as a string. 

247 """ 

248 text = self.render_children(element) 

249 return f".. rubric:: {text}\n" 

250 

251 def render_setext_heading(self, element: block.SetextHeading) -> str: 

252 """ 

253 Renders a setext heading element. 

254 

255 Args: 

256 element (block.SetextHeading): The setext heading element to render. 

257 

258 Returns: 

259 str: The rendered setext heading as a string. 

260 """ 

261 return self.render_heading(cast("block.Heading", element)) 

262 

263 # pylint: disable-next=unused-argument 

264 def render_blank_line(self, element: block.BlankLine) -> str: 

265 """ 

266 Renders a blank line element. 

267 

268 Args: 

269 element (block.BlankLine): The blank line element to render. 

270 

271 Returns: 

272 str: The rendered blank line as a string. 

273 """ 

274 return "\n" 

275 

276 # pylint: disable-next=unused-argument 

277 def render_link_ref_def(self, element: block.LinkRefDef) -> str: 

278 """ 

279 Renders a link reference definition element. 

280 

281 Args: 

282 element (block.LinkRefDef): The link reference definition element to render. 

283 

284 Returns: 

285 str: The rendered link reference definition as a string. 

286 """ 

287 # reStructuredText uses reference links differently than Markdown. 

288 # It shall not be rendered in the document. 

289 return "" 

290 

291 def render_emphasis(self, element: inline.Emphasis) -> str: 

292 """ 

293 Renders an emphasis (italic) element. 

294 

295 Args: 

296 element (inline.Emphasis): The emphasis element to render. 

297 

298 Returns: 

299 str: The rendered emphasis as a string. 

300 """ 

301 return f"*{self.render_children(element)}*" 

302 

303 def render_strong_emphasis(self, element: inline.StrongEmphasis) -> str: 

304 """ 

305 Renders a strong emphasis (bold) element. 

306 

307 Args: 

308 element (inline.StrongEmphasis): The strong emphasis element to render. 

309 

310 Returns: 

311 str: The rendered strong emphasis as a string. 

312 """ 

313 return f"**{self.render_children(element)}**" 

314 

315 def render_inline_html(self, element: inline.InlineHTML) -> str: 

316 """ 

317 Renders an inline HTML element. 

318 

319 Args: 

320 element (inline.InlineHTML): The inline HTML element to render. 

321 

322 Returns: 

323 str: The rendered inline HTML as a string. 

324 """ 

325 # Output as literal block. 

326 html_content = cast(str, element.children) 

327 return f"``{html_content}``" 

328 

329 def render_plain_text(self, element: Any) -> str: 

330 """ 

331 Renders plain text or any element with string children. 

332 

333 Args: 

334 element (Any): The element to render. 

335 

336 Returns: 

337 str: The rendered plain text as a string. 

338 """ 

339 if isinstance(element.children, str): 

340 return element.children 

341 

342 return self.render_children(element) 

343 

344 def render_link(self, element: inline.Link) -> str: 

345 """ 

346 Renders a link element. 

347 

348 Args: 

349 element (inline.Link): The link element to render. 

350 

351 Returns: 

352 str: The rendered link as a string. 

353 """ 

354 body = self.render_children(element) 

355 url = element.dest 

356 title = f" ({element.title})" if element.title else "" 

357 

358 return f"`{body} <{url}>`_{title}" 

359 

360 def render_auto_link(self, element: inline.AutoLink) -> str: 

361 """ 

362 Renders an auto link element. 

363 

364 Args: 

365 element (inline.AutoLink): The auto link element to render. 

366 

367 Returns: 

368 str: The rendered auto link as a string. 

369 """ 

370 return self.render_link(cast("inline.Link", element)) 

371 

372 def render_url(self, element: Any) -> str: 

373 """Renders a GitHub Flavored Markdown URL element. 

374 

375 Args: 

376 element (Any): The URL element. 

377 

378 Returns: 

379 str: The rendered URL as an RST link. 

380 """ 

381 return self.render_link(cast("inline.Link", element)) 

382 

383 def render_image(self, element: inline.Image) -> str: 

384 """ 

385 Renders an image element. 

386 

387 Args: 

388 element (inline.Image): The image element to render. 

389 

390 Returns: 

391 str: The rendered image as a string. 

392 """ 

393 url = element.dest 

394 alt = self.render_children(element) 

395 title = f" :alt: {alt}" if alt else "" 

396 extra_title = f" :title: {element.title}" if element.title else "" 

397 

398 return f".. image:: {url}\n{title}\n{extra_title}\n" 

399 

400 def render_literal(self, element: inline.Literal) -> str: 

401 """ 

402 Renders a literal (inline code) element. 

403 

404 Args: 

405 element (inline.Literal): The literal element to render. 

406 

407 Returns: 

408 str: The rendered literal as a string. 

409 """ 

410 return self.render_raw_text(cast("inline.RawText", element)) 

411 

412 def render_raw_text(self, element: inline.RawText) -> str: 

413 """ 

414 Renders a raw text element. 

415 

416 Args: 

417 element (inline.RawText): The raw text element to render. 

418 

419 Returns: 

420 str: The rendered raw text as a string. 

421 """ 

422 return f"{element.children}" 

423 

424 # pylint: disable-next=unused-argument 

425 def render_line_break(self, element: inline.LineBreak) -> str: 

426 """ 

427 Renders a line break element. 

428 

429 Args: 

430 element (inline.LineBreak): The line break element to render. 

431 

432 Returns: 

433 str: The rendered line break as a string. 

434 """ 

435 return "\n" 

436 

437 def render_code_span(self, element: inline.CodeSpan) -> str: 

438 """ 

439 Renders a code span (inline code) element. 

440 

441 Args: 

442 element (inline.CodeSpan): The code span element to render. 

443 

444 Returns: 

445 str: The rendered code span as a string. 

446 """ 

447 return f"``{cast(str, element.children)}``" 

448 

449# Functions ******************************************************************** 

450 

451# Main *************************************************************************