Coverage for src/pyTRLCConverter/marko/md2docx_renderer.py: 86%
206 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-01 11:26 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-01 11:26 +0000
1"""Docx Renderer for Marko.
2 It is used to convert CommonMark AST to docx format.
4 Author: Andreas Merkle (andreas.merkle@newtec.de)
5"""
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/>.
23# Imports **********************************************************************
25from __future__ import annotations
26import io
27import tempfile
28from typing import TYPE_CHECKING, Any, cast, Optional
29from marko import Renderer
30from docx.oxml import OxmlElement
31from docx.oxml.ns import qn
32from docx.blkcntnr import BlockItemContainer
33from pyTRLCConverter.plantuml import PlantUML
35if TYPE_CHECKING:
36 from . import block, inline
38# Variables ********************************************************************
40# Classes **********************************************************************
42class Singleton(type):
43 # lobster-trace: SwRequirements.sw_req_docx_render_md
44 """Singleton metaclass to ensure only one instance of a class exists."""
46 _instances = {}
48 def __call__(cls, *args, **kwargs):
49 """
50 Returns the singleton instance of the class.
52 Returns:
53 instance (cls): The singleton instance of the class.
54 """
56 if cls not in cls._instances:
57 cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
59 return cls._instances[cls]
61# pylint: disable-next=too-many-public-methods, too-many-instance-attributes
62class Md2DocxRenderer(Renderer, metaclass=Singleton):
63 # lobster-trace: SwRequirements.sw_req_docx_render_md
64 # lobster-trace: SwRequirements.sw_req_docx_render_plantuml
65 # lobster-trace: SwRequirements.sw_req_plantuml
66 """Renderer for docx output."""
68 # Docx block item container to add content to.
69 block_item_container: Optional[BlockItemContainer] = None
71 def __init__(self) -> None:
72 """Initialize the renderer."""
73 super().__init__()
74 self._list_indent_level = 0
75 self._is_italic = False
76 self._is_bold = False
77 self._is_underline = False
78 self._is_heading = False
79 self._heading_level = 0
80 self._is_list_item = False
81 self._list_style = []
82 self._is_quote = False
83 self._current_paragraph = None
84 self.reset()
86 def reset(self) -> None:
87 """Resets the renderer state before a new convert() call.
89 The Singleton pattern means __init__ runs only once. Without an explicit reset,
90 stale state from a previous convert() call (e.g. _current_paragraph) would persist
91 into the next call and cause spurious empty paragraphs in the output.
92 """
93 self.root_node = None
94 self._list_indent_level = 0
95 self._is_italic = False
96 self._is_bold = False
97 self._is_underline = False
98 self._is_heading = False
99 self._heading_level = 0
100 self._is_list_item = False
101 self._list_style = []
102 self._is_quote = False
103 self._current_paragraph = None
105 def render_children(self, element: Any) -> None:
106 """
107 Recursively renders child elements of a given element to
108 a docx document.
110 Args:
111 element (Element): The parent element whose children are to be rendered.
112 """
113 for child in element.children:
114 self.render(child)
116 def render_paragraph(self, element: block.Paragraph) -> None:
117 """
118 Renders a paragraph element.
120 Args:
121 element (block.Paragraph): The paragraph element to render.
122 """
123 assert self.block_item_container is not None
125 # The Singleton pattern means __init__ runs only once, so _current_paragraph persists
126 # across convert() calls. Each paragraph element must own exactly one docx paragraph for
127 # the duration of rendering its inline children — set it here and clear it after.
128 self._current_paragraph = self.block_item_container.add_paragraph()
130 # Apply the paragraph style based on the context set by the enclosing block element.
131 # render_paragraph is called for any Paragraph node in the AST — including those nested
132 # inside headings, list items, and block quotes. The outer block renderers set state flags
133 # but do not create the docx paragraph themselves, so the style must be applied here.
134 if self._is_heading is True:
135 self._current_paragraph.style = f"Heading {self._heading_level}"
136 elif self._is_list_item:
137 self._current_paragraph.style = self._list_style[-1]
138 elif self._is_quote:
139 self._current_paragraph.style = "Quote"
141 self.render_children(element)
142 self._current_paragraph = None
144 def render_list(self, element: block.List) -> None:
145 """
146 Renders a list (ordered or unordered) element.
148 Args:
149 element (block.List): The list element to render.
150 """
151 assert self.block_item_container is not None
153 self._is_list_item = True
154 self._list_indent_level += 1
156 style = "List Number" if element.ordered else "List Bullet"
158 if self._list_indent_level > 1:
159 style += f" {self._list_indent_level}"
161 self._list_style.append(style)
163 for child in element.children:
164 self.render(child)
166 self._list_style.pop()
168 self._list_indent_level -= 1
170 if self._list_indent_level == 0:
171 self._is_list_item = False
173 def render_quote(self, element: block.Quote) -> None:
174 """
175 Renders a blockquote element.
177 Args:
178 element (block.Quote): The blockquote element to render.
179 """
180 self._is_quote = True
181 self.render_children(element)
182 self._is_quote = False
184 def render_fenced_code(self, element: block.FencedCode) -> None:
185 """
186 Renders a fenced code block element.
188 If the language tag is 'plantuml', the diagram source is rendered as an embedded
189 PNG image. If PlantUML is not available, an error string is inserted instead.
190 For all other language tags the block is rendered as plain Consolas text.
192 Args:
193 element (block.FencedCode): The fenced code block element to render.
194 """
195 assert self.block_item_container is not None
197 if element.lang == "plantuml":
198 self._render_plantuml(element.children[0].children)
199 else:
200 paragraph = self.block_item_container.add_paragraph()
201 # Marko includes a trailing newline in the RawText content of code blocks - strip it
202 # to avoid an extra blank line appearing in the docx output after the code paragraph.
203 run = paragraph.add_run(element.children[0].children.rstrip("\n"))
204 run.font.name = "Consolas"
206 def _render_plantuml(self, diagram_source: str) -> None:
207 """Renders a PlantUML diagram as an embedded PNG in the docx document.
209 Generates PNG bytes via the PlantUML tool and embeds the image directly.
210 If PlantUML is not available, inserts an error string instead.
212 Args:
213 diagram_source (str): The PlantUML diagram source text.
214 """
215 assert self.block_item_container is not None
217 try:
218 plantuml = PlantUML()
219 with tempfile.TemporaryDirectory() as tmp_dir:
220 # Write the diagram source to a temp file so PlantUML can read it.
221 with tempfile.NamedTemporaryFile(
222 dir=tmp_dir, suffix=".puml", mode='w',
223 encoding='utf-8', delete=False
224 ) as src_file:
225 src_file.write(diagram_source)
226 src_name = src_file.name
227 # PNG is required: python-docx's add_picture() only accepts raster formats;
228 # SVG is not supported.
229 plantuml.generate("png", src_name, tmp_dir)
230 png_path = src_name.replace(".puml", ".png")
231 with open(png_path, 'rb') as png_file:
232 png_bytes = png_file.read()
234 paragraph = self.block_item_container.add_paragraph()
235 run = paragraph.add_run()
236 run.add_picture(io.BytesIO(png_bytes))
237 except (FileNotFoundError, OSError) as exc:
238 paragraph = self.block_item_container.add_paragraph()
239 paragraph.add_run(f"[PlantUML error: {exc}]")
241 def render_code_block(self, element: block.CodeBlock) -> None:
242 """
243 Renders a code block element.
245 Args:
246 element (block.CodeBlock): The code block element to render.
247 """
248 self.render_fenced_code(cast("block.FencedCode", element))
250 def render_html_block(self, element: block.HTMLBlock) -> None:
251 """
252 Renders a raw HTML block element.
254 Args:
255 element (block.HTMLBlock): The HTML block element to render.
256 """
257 self.render_fenced_code(cast("block.FencedCode", element))
259 # pylint: disable-next=unused-argument
260 def render_thematic_break(self, element: block.ThematicBreak) -> None:
261 """
262 Renders a thematic break (horizontal rule) element.
264 Args:
265 element (block.ThematicBreak): The thematic break element to render.
266 """
267 assert self.block_item_container is not None
269 # Remove the preceding blank paragraph if present — the BlankLine node before a
270 # thematic break is Markdown syntax spacing, not intended visual whitespace in docx.
271 paragraphs = self.block_item_container.paragraphs # type: ignore
272 if paragraphs and paragraphs[-1].text == "" and not paragraphs[-1].runs:
273 paragraphs[-1]._p.getparent().remove(paragraphs[-1]._p) # pylint: disable=protected-access
275 # Add a horizontal rule by inserting a paragraph with a bottom border
276 para = self.block_item_container.add_paragraph()
277 p = para._element # pylint: disable=protected-access
279 paragraph_properties = p.get_or_add_pPr()
280 p_bdr = OxmlElement('w:pBdr')
281 bottom = OxmlElement('w:bottom')
282 bottom.set(qn('w:val'), 'single')
283 bottom.set(qn('w:sz'), '6')
284 bottom.set(qn('w:space'), '1')
285 bottom.set(qn('w:color'), 'auto')
286 p_bdr.append(bottom)
287 paragraph_properties.append(p_bdr)
289 def render_heading(self, element: block.Heading) -> None:
290 """
291 Renders a heading element.
293 Args:
294 element (block.Heading): The heading element to render.
295 """
296 assert self.block_item_container is not None
298 self._is_heading = True
299 self._heading_level = min(max(element.level, 1), 9) # docx supports levels 1-9
300 # Heading inline children are direct children of the Heading node, not wrapped in a
301 # Paragraph node, so render_paragraph is never called — the docx paragraph must be
302 # created here directly.
303 self._current_paragraph = self.block_item_container.add_paragraph(
304 style=f"Heading {self._heading_level}"
305 )
307 self.render_children(element)
309 self._current_paragraph = None
310 self._is_heading = False
311 self._heading_level = 0
313 def render_setext_heading(self, element: block.SetextHeading) -> None:
314 """
315 Renders a setext heading element.
317 Args:
318 element (block.SetextHeading): The setext heading element to render.
319 """
320 self.render_heading(cast("block.Heading", element))
322 # pylint: disable-next=unused-argument
323 def render_blank_line(self, element: block.BlankLine) -> None:
324 """
325 Renders a blank line element.
327 Args:
328 element (block.BlankLine): The blank line element to render.
329 """
330 assert self.block_item_container is not None
332 self.block_item_container.add_paragraph()
334 # pylint: disable-next=unused-argument
335 def render_link_ref_def(self, element: block.LinkRefDef) -> None:
336 """
337 Renders a link reference definition element.
339 Args:
340 element (block.LinkRefDef): The link reference definition element to render.
341 """
342 # docx uses reference links differently than Markdown.
343 # It shall not be rendered in the document.
345 def render_emphasis(self, element: inline.Emphasis) -> None:
346 """
347 Renders an emphasis (italic) element.
349 Args:
350 element (inline.Emphasis): The emphasis element to render.
351 """
352 assert self.block_item_container is not None
354 self._is_italic = True
356 self.render_children(element)
358 self._is_italic = False
360 def render_strong_emphasis(self, element: inline.StrongEmphasis) -> None:
361 """
362 Renders a strong emphasis (bold) element.
364 Args:
365 element (inline.StrongEmphasis): The strong emphasis element to render.
366 """
367 assert self.block_item_container is not None
369 self._is_bold = True
371 self.render_children(element)
373 self._is_bold = False
375 def render_inline_html(self, element: inline.InlineHTML) -> None:
376 """
377 Renders an inline HTML element.
379 Args:
380 element (inline.InlineHTML): The inline HTML element to render.
381 """
382 assert self._current_paragraph is not None
384 run = self._current_paragraph.add_run(element.children)
385 run.font.name = "Consolas"
387 def render_plain_text(self, element: Any) -> None:
388 """
389 Renders plain text or any element with string children.
391 Args:
392 element (Any): The element to render.
393 """
394 if isinstance(element.children, str):
395 assert self._current_paragraph is not None
396 run = self._current_paragraph.add_run(element.children)
397 # Only set run properties to True when explicitly active. Setting them to False
398 # would override the paragraph style (e.g. Quote italic), breaking style inheritance.
399 # Leaving them as None lets the paragraph style apply instead.
400 if self._is_bold:
401 run.bold = True
402 if self._is_italic:
403 run.italic = True
404 if self._is_underline:
405 run.underline = True
406 else:
407 self.render_children(element)
409 def render_link(self, element: inline.Link) -> None:
410 """
411 Renders a link element as a clickable hyperlink.
413 Args:
414 element (inline.Link): The link element to render.
415 """
416 assert self._current_paragraph is not None
418 # python-docx has no high-level API for hyperlinks. The OOXML spec requires:
419 # 1. A relationship entry in the document part (rel_id) linking the URL.
420 # 2. A w:hyperlink element referencing that relationship by r:id.
421 # 3. A w:r run inside it with a w:rStyle "Hyperlink" for standard link styling.
422 # All three must be built via direct XML manipulation.
423 rel_id = self.block_item_container.part.relate_to(
424 element.dest,
425 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink',
426 is_external=True
427 )
429 hyperlink = OxmlElement('w:hyperlink')
430 hyperlink.set(qn('r:id'), rel_id)
432 r = OxmlElement('w:r')
433 r_pr = OxmlElement('w:rPr')
434 r_style = OxmlElement('w:rStyle')
435 r_style.set(qn('w:val'), 'Hyperlink')
436 r_pr.append(r_style)
437 r.append(r_pr)
439 t = OxmlElement('w:t')
440 t.text = self._collect_link_text(element)
441 r.append(t)
443 hyperlink.append(r)
444 self._current_paragraph._p.append(hyperlink) # pylint: disable=protected-access
446 @staticmethod
447 def _collect_link_text(element: Any) -> str:
448 """Recursively collects the plain text label from a link element's children.
450 Args:
451 element (Any): The link element.
453 Returns:
454 str: The plain text of the link label.
455 """
456 if isinstance(element.children, str):
457 result = element.children
458 else:
459 result = "".join(
460 Md2DocxRenderer._collect_link_text(child) for child in element.children
461 )
463 return result
465 def render_auto_link(self, element: inline.AutoLink) -> None:
466 """
467 Renders an auto link element.
469 Args:
470 element (inline.AutoLink): The auto link element to render.
471 """
472 self.render_link(cast("inline.Link", element))
474 def render_image(self, element: inline.Image) -> None:
475 """
476 Renders an image element.
478 Args:
479 element (inline.Image): The image element to render.
481 Returns:
482 DocxDocument: The rendered image as a docx document.
483 """
484 # Image handling in docx is non-trivial; for simplicity just render title and URL.
485 if element.title:
486 assert self.block_item_container is not None
487 self.block_item_container.add_paragraph(text=element.title)
488 self.block_item_container.add_paragraph(text=f" ({element.dest})")
490 def render_literal(self, element: inline.Literal) -> None:
491 """
492 Renders a literal (inline code) element.
494 Args:
495 element (inline.Literal): The literal element to render.
496 """
497 self.render_raw_text(cast("inline.RawText", element))
499 def render_raw_text(self, element: inline.RawText) -> None:
500 """
501 Renders a raw text element.
503 Args:
504 element (inline.RawText): The raw text element to render.
506 Returns:
507 DocxDocument: The rendered raw text as a docx document.
508 """
509 assert self._current_paragraph is not None
511 run = self._current_paragraph.add_run(element.children)
512 # Only set run properties to True when explicitly active — see render_plain_text.
513 if self._is_bold:
514 run.bold = True
515 if self._is_italic:
516 run.italic = True
517 if self._is_underline:
518 run.underline = True
520 # pylint: disable-next=unused-argument
521 def render_line_break(self, element: inline.LineBreak) -> None:
522 """
523 Renders a line break element.
525 Args:
526 element (inline.LineBreak): The line break element to render.
528 Returns:
529 DocxDocument: The rendered line break as a docx document.
530 """
531 assert self._current_paragraph is not None
533 self._current_paragraph.add_run().add_break()
535 def render_code_span(self, element: inline.CodeSpan) -> None:
536 """
537 Renders a code span (inline code) element.
539 Args:
540 element (inline.CodeSpan): The code span element to render.
542 Returns:
543 DocxDocument: The rendered code span as a docx document.
544 """
545 assert self._current_paragraph is not None
547 run = self._current_paragraph.add_run(cast(str, element.children))
548 run.font.name = "Consolas"
550# Functions ********************************************************************
552# Main *************************************************************************