diff --git a/docs/index.rst b/docs/index.rst index 8330cc4..b1a6a8f 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -343,6 +343,28 @@ With a plain ``{{ mysubdoc }}`` the paragraphs end up inside the text of the par and, if the paragraph also has other content such as a bookmark or formatted text, the generated document may be corrupted and refused by Word. The same goes for subdocs inserted in a loop: put the tag in its own ``{%p for ... %}`` block and use ``{{p item }}`` inside it. +.. rubric:: Multilevel numbered lists + +In Word, create one multilevel list in the template. For example, use decimal +numbers at level 1, lower-case letters at level 2, and lower-case Roman numerals +at level 3. Set the second level to restart after level 1 and the third level to +restart after level 2. Apply that list directly to the paragraph whose only +text is the tag ``{{p items }}``. + +Read the numbered paragraph's list ID (``numId``) and use it for every generated +paragraph. Set each paragraph's zero-based list level (``ilvl``) in the subdoc. +With separate numbering IDs for the levels, Word keeps separate counters and +the child numbering can continue under a new parent. + +``pip install "docform[subdoc]"`` installs the dependencies for this example. +Use the :download:`example template <../examples/multilevel_list/template.docx>` +and run the :download:`render script <../examples/multilevel_list/render.py>`. +Open the output in Word to see the numbering restart as +``1., a., b., i., ii., 2., a., i.``. + +.. literalinclude:: ../examples/multilevel_list/render.py + :language: python + .. _Escaping: Escaping diff --git a/examples/README.md b/examples/README.md index 5ef9b66..062342f 100644 --- a/examples/README.md +++ b/examples/README.md @@ -5,9 +5,11 @@ Each folder has a template, the data it's rendered with, and a `render.py` scrip | Example | Shows | |---|---| | [invoice](invoice) | Variables, a table row loop with `{%tr %}`, paragraph conditions with `{%p %}`, and formatting carried over from tags | +| [multilevel list](multilevel_list) | A numbered subdoc whose child levels restart under each new parent | Run one from the repo root: ```bash python examples/invoice/render.py +python examples/multilevel_list/render.py ``` diff --git a/examples/multilevel_list/render.py b/examples/multilevel_list/render.py new file mode 100644 index 0000000..33aee02 --- /dev/null +++ b/examples/multilevel_list/render.py @@ -0,0 +1,40 @@ +"""Render a numbered list with Word-managed restarts.""" + +from pathlib import Path + +from docform import DocxTemplate + +ITEMS = ( + (0, "Prepare the report"), + (1, "Collect the data"), + (1, "Review the figures"), + (2, "Check the axis labels"), + (2, "Check the units"), + (0, "Publish the report"), + (1, "Prepare the release"), + (2, "Check the metadata"), +) + + +def render(template_path, output_path, items): + tpl = DocxTemplate(template_path) + # Read the list instance from the numbered placeholder in the template. + placeholder = next(p for p in tpl.get_docx().paragraphs if p.text == "{{p items }}") + num_id = placeholder._p.pPr.numPr.numId.val + + subdoc = tpl.new_subdoc() + for level, text in items: + paragraph = subdoc.add_paragraph(text) + numbering = paragraph._p.get_or_add_pPr().get_or_add_numPr() + numbering.get_or_add_ilvl().val = level + numbering.get_or_add_numId().val = num_id + + tpl.render({"items": subdoc}) + tpl.save(output_path) + + +if __name__ == "__main__": + here = Path(__file__).resolve().parent + output = here / "multilevel_list.docx" + render(here / "template.docx", output, ITEMS) + print("Wrote", output) diff --git a/examples/multilevel_list/template.docx b/examples/multilevel_list/template.docx new file mode 100644 index 0000000..8807ea1 Binary files /dev/null and b/examples/multilevel_list/template.docx differ diff --git a/pyproject.toml b/pyproject.toml index e069e7e..4593f54 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -66,6 +66,9 @@ ignore_missing_imports = true [tool.pdm] version = {source="file", path="docform/__init__.py"} +[tool.pdm.build] +source-includes = ["tests/", "examples/multilevel_list/"] + [build-system] requires = ["pdm-backend"] build-backend = "pdm.backend" diff --git a/tests/unit/test_multilevel_list_example.py b/tests/unit/test_multilevel_list_example.py new file mode 100644 index 0000000..05d25e1 --- /dev/null +++ b/tests/unit/test_multilevel_list_example.py @@ -0,0 +1,29 @@ +import runpy +from pathlib import Path + +from docx import Document + + +def test_multilevel_list_example_keeps_one_list_with_explicit_levels(tmp_path): + example = Path(__file__).resolve().parents[2] / "examples" / "multilevel_list" + code = runpy.run_path(str(example / "render.py")) + template = example / "template.docx" + output = tmp_path / "multilevel_list.docx" + + code["render"](template, output, code["ITEMS"]) + + doc = Document(output) + assert [paragraph.text for paragraph in doc.paragraphs] == [ + text for _, text in code["ITEMS"] + ] + num_ids = {paragraph._p.pPr.numPr.numId.val for paragraph in doc.paragraphs} + template_num_id = Document(template).paragraphs[0]._p.pPr.numPr.numId.val + assert num_ids == {template_num_id} + numbering = doc.part.numbering_part.element + abstract_id = numbering.num_having_numId(template_num_id).abstractNumId.val + level_path = f'./w:abstractNum[@w:abstractNumId="{abstract_id}"]/w:lvl' + assert len(numbering.xpath(level_path)) == 3 + assert not numbering.xpath(level_path + "/w:lvlRestart") + assert [paragraph._p.pPr.numPr.ilvl.val for paragraph in doc.paragraphs] == [ + level for level, _ in code["ITEMS"] + ]