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)