From 51b4ee6eba4acaef482a3f869d73ddfdfa9ad4f4 Mon Sep 17 00:00:00 2001 From: Srinivas Chippagiri Date: Wed, 25 Nov 2026 00:57:55 -0800 Subject: [PATCH] Keep section breaks that sit on a {%p %} tag paragraph A paragraph that ends a section holds the section's page size, margins and orientation in w:pPr/w:sectPr. When that paragraph carries a {%p %} tag it was removed along with its section break, so the section merged into the next one and lost its layout. Keep an empty paragraph with the same properties, before opening tags and after closing ones so an if or for never drops or repeats it. Fixes #111 --- docform/docx/template.py | 27 ++++++++++++++++++++++++++- tests/unit/test_render.py | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/docform/docx/template.py b/docform/docx/template.py index edf0dfd..03baf53 100644 --- a/docform/docx/template.py +++ b/docform/docx/template.py @@ -267,6 +267,28 @@ def write_xml(self, filename): with open(filename, "w", encoding="utf-8") as fh: fh.write(self.get_xml()) + @staticmethod + def _keep_section_break(m): + """Replace a {%p %} paragraph by its tag, keeping a section break. + + A paragraph that ends a section holds the section's settings (page + size, margins, orientation) in w:pPr/w:sectPr. Dropping it with the + tag would merge the section into the next one. Keep an empty + paragraph with those properties outside the block: before an + opening tag and after a closing one, so it's never skipped or + repeated by the tag. + """ + tag = m.group(1) + " " + m.group(2) + ppr = re.search( + r"(?:(?!).)*/].*?", m.group(0), flags=re.DOTALL + ) + if ppr is None: + return tag + section_break = "" + ppr.group(0) + "" + if re.match(r"-?\s*end", m.group(2)): + return tag + section_break + return section_break + tag + def patch_xml(self, src_xml): """Make a lots of cleaning to have a raw xml understandable by jinja2 : strip all unnecessary xml tags, manage table cell background color and colspan, @@ -404,7 +426,10 @@ def cellbg(m): r"](?:(?!]).)*({%%|{{)%(y)s ((?:(?!%%}|}}).)*(?:%%}|}})).*?" % {"y": y} ) - src_xml = re.sub(pat, r"\1 \2", src_xml, flags=re.DOTALL) + if y == "p": + src_xml = re.sub(pat, self._keep_section_break, src_xml, flags=re.DOTALL) + else: + src_xml = re.sub(pat, r"\1 \2", src_xml, flags=re.DOTALL) for y in ["tr", "tc", "p"]: # same thing, but for {#y xxx #} (but not where y == 'r', since that diff --git a/tests/unit/test_render.py b/tests/unit/test_render.py index 746c025..139740a 100644 --- a/tests/unit/test_render.py +++ b/tests/unit/test_render.py @@ -265,6 +265,42 @@ def test_hm_keeps_tcpr_in_schema_order(tmp_path): assert names == sorted(names, key=TC_PR_ORDER.index) +@pytest.mark.parametrize( + "paragraphs, break_at, context", + [ + (["{%p if show %}", "{{ text }}", "{%p endif %}"], 0, {"show": True}), + (["{%p if show %}", "{{ text }}", "{%p endif %}"], 0, {"show": False}), + (["{%p if show %}", "{{ text }}", "{%p endif %}"], 2, {"show": True}), + (["{%p if show %}", "{{ text }}", "{%p endif %}"], 2, {"show": False}), + (["{%p for x in xs %}", "{{ x }}", "{%p endfor %}"], 0, {"xs": [1, 2, 3]}), + (["{%p for x in xs %}", "{{ x }}", "{%p endfor %}"], 2, {"xs": [1, 2, 3]}), + ], + ids=["if-shown", "if-hidden", "endif-shown", "endif-hidden", "for", "endfor"], +) +def test_section_break_on_paragraph_tag_is_kept(tmp_path, paragraphs, break_at, context): + from docx.shared import Inches + + doc = Document() + for index, text in enumerate(paragraphs): + if index == break_at: + # python-docx puts the section break in a new last paragraph + doc.add_section() + doc.paragraphs[-1].text = text + else: + doc.add_paragraph(text) + doc.sections[0].left_margin = Inches(2) + path = tmp_path / "sections.docx" + doc.save(str(path)) + + tpl = DocxTemplate(str(path)) + tpl.render(dict(context, text="body")) + out = saved(tpl) + assert len(out.sections) == 2 + assert out.sections[0].left_margin == Inches(2) + assert out.sections[1].left_margin != Inches(2) + assert not any("{%" in text for text in body_text(out)) + + def test_header_footer_and_properties(make_docx): path = make_docx(["body {{ x }}"], header="head {{ x }}", footer="foot {{ x }}", title="Report {{ x }}") tpl = DocxTemplate(path)