From 7f81c2015ea8fb5eec4a03ddbf7ee63c4b8a3d7d Mon Sep 17 00:00:00 2001 From: shen Date: Thu, 5 Nov 2026 21:54:52 +0800 Subject: [PATCH] fix: preserve nested Word structures and synchronize valid font families --- mdhelper/app.py | 8 ++- mdhelper/docx_exporter.py | 21 ++++-- mdhelper/docx_semantic.py | 48 +++++++++---- mdhelper/resources/word_inline_styles.lua | 7 +- mdhelper/style_sync.py | 2 +- tests/test_css_revision_058.py | 39 ++++++++++ tests/test_document_style.py | 6 +- tests/test_startup_revision_058.py | 29 ++++++++ tests/test_style_revision_055.py | 3 +- tests/test_style_revision_058.py | 68 ++++++++++++++++++ tests/word_revision_055_smoke.ps1 | 2 +- tests/word_revision_058_smoke.ps1 | 87 +++++++++++++++++++++++ 12 files changed, 292 insertions(+), 28 deletions(-) create mode 100644 tests/test_css_revision_058.py create mode 100644 tests/test_startup_revision_058.py create mode 100644 tests/test_style_revision_058.py create mode 100644 tests/word_revision_058_smoke.ps1 diff --git a/mdhelper/app.py b/mdhelper/app.py index 485eeda..0c73011 100644 --- a/mdhelper/app.py +++ b/mdhelper/app.py @@ -113,9 +113,11 @@ def main(argv: list[str] | None = None) -> int: app.setOrganizationName("MDHelper") settings = QSettings("MDHelper", "MDHelper") if project_root is None: - last_project_root = Path(str(settings.value("project/last_root", ""))).expanduser() - if str(last_project_root) and last_project_root.exists(): - project_root = last_project_root.resolve() + last_root = settings.value("project/last_root", "") + if isinstance(last_root, str) and last_root.strip(): + last_project_root = Path(last_root).expanduser() + if last_project_root.is_dir(): + project_root = last_project_root.resolve() logging.getLogger(__name__).info( "Starting MDHelper %s with project_root=%s content_root=%s log_root=%s", diff --git a/mdhelper/docx_exporter.py b/mdhelper/docx_exporter.py index afabcc9..d5c5b2c 100644 --- a/mdhelper/docx_exporter.py +++ b/mdhelper/docx_exporter.py @@ -248,7 +248,10 @@ def _pandoc_list_tables(source: str) -> str: if match: prefix, marker, spacing = match.groups() indent = prefix + ' ' * (len(marker) + len(spacing)) - lines[row] = match.group() + '\n' + prefix + '\n' + indent + lines[row][match.end():] + # A bare '-' after parent text is a Setext heading underline. + # '+' is the same bullet without changing the parent's tightness. + marker = '+' if marker == '-' else marker + lines[row] = prefix + marker + spacing + '\n' + prefix + '\n' + indent + lines[row][match.end():] return ''.join(lines) @@ -324,6 +327,7 @@ def _add_python_docx_table(document: object, block: TableBlock) -> None: if block.list_target: table._tbl.set(LIST_TARGET, block.list_target) table._tbl.set(LIST_LEVEL, str(block.list_level)) + if block.quote_depth: table._tbl.set(QUOTE_DEPTH, str(block.quote_depth)) table.style = "Table Grid" for row_index, row in enumerate(block.rows): for col_index in range(column_count): @@ -371,6 +375,7 @@ class TableBlock: alignments: list[str] = field(default_factory=list) list_target: str = '' list_level: int = 0 + quote_depth: int = 0 class _DocxBuilder: @@ -415,6 +420,8 @@ class _DocxBuilder: elif token.type == "blockquote_close": self.quote_depth = max(0, self.quote_depth - 1) elif token.type in ('bullet_list_open', 'ordered_list_open'): + if self.item_pending and self.item_pending[-1]: + self._append_list_marker() self.list_stack.append('bullet' if token.type == 'bullet_list_open' else 'number') self.list_sequence += 1 self.list_ids.append(self.list_sequence) @@ -427,7 +434,7 @@ class _DocxBuilder: self.list_quote_depths.pop() elif token.type == "table_open": if self.item_pending and self.item_pending[-1]: - self._append_paragraph([], 'Normal', self.list_stack[-1]) + self._append_list_marker() self.blocks.append(self._collect_table()) continue elif token.type == "hr": @@ -435,6 +442,12 @@ class _DocxBuilder: self.index += 1 return self.blocks + def _append_list_marker(self) -> None: + self._append_paragraph([], 'Normal', self.list_stack[-1]) + # The marker belongs to the list item, outside its leading quote/table. + self.blocks[-1].quote_depth = self.list_quote_depths[-1] + self.blocks[-1].inner_quote = False + def _add_next_inline(self, style: str, list_kind: str = "") -> None: inline = self.tokens[self.index + 1] if self.index + 1 < len(self.tokens) else None runs = _inline_runs(inline.children if inline is not None else None) @@ -474,7 +487,7 @@ class _DocxBuilder: self.index += 1 break self.index += 1 - return TableBlock(rows, alignments, self.item_targets[-1] if self.item_targets else '', max(0, len(self.list_stack)-1)) + return TableBlock(rows, alignments, self.item_targets[-1] if self.item_targets else '', max(0, len(self.list_stack)-1), self.quote_depth) def _inline_runs(children: list[Token] | None) -> list[tuple[str, dict[str, object]]]: @@ -599,7 +612,7 @@ def _numbering_xml(blocks): def _table_xml(block: TableBlock) -> str: - marker = f' xmlns:mdh="urn:mdhelper:source" mdh:list-target="{block.list_target}" mdh:list-level="{block.list_level}"' if block.list_target else '' + marker = f' xmlns:mdh="urn:mdhelper:source" mdh:list-target="{block.list_target}" mdh:list-level="{block.list_level}" mdh:quote-depth="{block.quote_depth}"' if block.list_target or block.quote_depth else '' rows = [] for row in block.rows: cells = [] diff --git a/mdhelper/docx_semantic.py b/mdhelper/docx_semantic.py index 931922f..7cb904a 100644 --- a/mdhelper/docx_semantic.py +++ b/mdhelper/docx_semantic.py @@ -142,7 +142,7 @@ class WordStyles: base = 'table' style = self.new(identifier, 'paragraph', 'MDHelper ' + style_name(key, self.rules), base_id) rule = dict(self.effective[key]) - if key == 'list' or key in LIST_TARGETS: rule = absolute_indents(rule) + if key in ('list', 'blockquote') or key in LIST_TARGETS: rule = absolute_indents(rule) if rule.get('font_color') == 'inherit': rule['font_color'] = 'auto' _paragraph_properties(child(style, 'pPr'), rule) if key in ('table_head', 'table_cell'): remove_fields(child(style, 'pPr'), ('shd',)) @@ -151,7 +151,7 @@ class WordStyles: if base: for tag, writer in (('pPr', _paragraph_properties), ('rPr', _run_properties)): base_props = ET.Element(W + tag) - base_rule = absolute_indents(self.effective[base]) if base == 'list' or base in LIST_TARGETS else self.effective[base] + base_rule = absolute_indents(self.effective[base]) if base in ('list', 'blockquote') or base in LIST_TARGETS else self.effective[base] writer(base_props, base_rule) if tag == 'rPr': remove_fields(base_props, ('shd',)) _delta(child(style, tag), base_props, normalize_rule(self.rules.get(key))) @@ -393,7 +393,7 @@ class WordStyles: child(child(style, 'pPr'), 'ind').attrib.update({W + key:'0' for key in ('firstLine','firstLineChars','hanging','hangingChars')}) return identifier - def quoted_block(self, base_id, target, depth): + def quoted_block(self, base_id, target, depth, *, offset_depth=None): identifier = base_id + 'Quote' + str(depth) if identifier not in self.created: style = self.new(identifier, 'paragraph', reference(self.created[base_id], 'name') + f'(引用第 {depth} 层)', base_id) @@ -408,12 +408,13 @@ class WordStyles: ind = base.find('w:pPr/w:ind', NS) if ind is not None: attributes.update(ind.attrib) points = font_points(self.effective['paragraph']) + offset_depth = depth if offset_depth is None else offset_depth props = child(child(style, 'pPr'), 'ind') for side, padding in (('left', points + 3), ('right', points)): value = number(attributes.get(W + side, 0)) / 20 chars = number(attributes.get(W + side + 'Chars', 0)) if chars: value = chars / 100 * font_points(self.effective[target]) - props.set(W + side, str(round((value + padding * depth) * 20))) + props.set(W + side, str(round((value + padding * offset_depth) * 20))) props.set(W + side + 'Chars', '0') return identifier @@ -486,6 +487,10 @@ class WordStyles: rpr = numbering_level.find(W + 'rPr') if rpr is not None: remove_fields(rpr, ('rFonts',)) + def table_padding(self, side): + rule = self.effective['table'] + return number(rule.get('cell_padding', font_points(rule) * (.76 if side in ('left', 'right') else .62))) + def table(self): identifier = style_id('table') style = self.new(identifier, 'table', 'MDHelper ' + style_name('table', self.rules)) @@ -504,7 +509,7 @@ class WordStyles: element.attrib.update({W + 'val': border if visible else 'none', W + 'sz': str(max(2, round(width * 8))), W + 'color': color.lstrip('#') if color != 'transparent' else 'auto'}) margins = child(props, 'tblCellMar') for side in ('top', 'left', 'bottom', 'right'): - padding = number(rule.get('cell_padding', font_points(rule) * (.76 if side in ('left', 'right') else .62))) + padding = self.table_padding(side) child(margins, side).attrib.update({W + 'w': str(round(padding * 20)), W + 'type': 'dxa'}) if 'background_color' in rule: child(child(style, 'tcPr'), 'shd').attrib.update({W + 'val': 'clear', W + 'fill': str(rule['background_color']).lstrip('#') if rule['background_color'] != 'transparent' else 'auto'}) @@ -558,7 +563,7 @@ class WordStyles: continuation = paragraph.attrib.pop(CONTINUATION, '') == '1' list_target = paragraph.attrib.pop(LIST_TARGET, '') quote_depth = int(paragraph.attrib.pop(QUOTE_DEPTH, '0')) - paragraph.attrib.pop(LIST_LEVEL, None) + context_level = int(paragraph.attrib.pop(LIST_LEVEL, '0')) ppr = properties(paragraph, 'pPr') original_id = reference(ppr, 'pStyle') or 'Normal' names = {reference(style, 'name') for style in self.chain(original_id)} @@ -571,7 +576,7 @@ class WordStyles: names.add(base) loose = bool(names & set(SOURCE_PARAGRAPH_STYLES)) target = self.classify(paragraph, original_id) - if target.startswith('list_') and list_target in LIST_TARGETS: target = list_target + if target.startswith('list_') and target != 'list_task' and list_target in LIST_TARGETS: target = list_target identifier = self.paragraph(target) numpr = ppr.find(W + 'numPr') if numpr is not None: @@ -599,11 +604,20 @@ class WordStyles: if marker and not continuation: self.apply_list_marker(numpr, target, marker) if loose: identifier = self.list_paragraph(target, identifier, level) if QUOTED_LIST_PARAGRAPH_STYLE in names: identifier = self.quoted_list(target, identifier, level) + elif target == 'blockquote' and list_target in LIST_TARGETS: + base = self.nested_list(list_target, context_level) if context_level else self.paragraph(list_target) + identifier = self.quoted_list(list_target, base, context_level) + marker = self.effective[list_target].get('list_marker') + if marker and not continuation: self.apply_list_marker(numpr, list_target, marker) if continuation: remove_fields(ppr, ('numPr',)) identifier = self.continuation_style(identifier) - if quote_depth and (target == 'code_block' or re.fullmatch('h[1-6]', target)): - identifier = self.quoted_block(identifier, target, quote_depth) + if quote_depth: + # The legacy quote paragraph style already represents its first + # quote. Keep that base editable and add only deeper containers. + standalone_quote = target == 'blockquote' and list_target not in LIST_TARGETS + offset = quote_depth - 1 if standalone_quote else quote_depth + if offset: identifier = self.quoted_block(identifier, target, quote_depth, offset_depth=offset) alignment = reference(ppr, 'jc') if target in ('table_head','table_cell') and alignment in ('left','center','right','both'): identifier = self.table_column(target, alignment) @@ -613,11 +627,19 @@ class WordStyles: for table in document.iter(W + 'tbl'): list_target = table.attrib.pop(LIST_TARGET, '') level = int(table.attrib.pop(LIST_LEVEL, '0')) - table.attrib.pop(QUOTE_DEPTH, None); table.attrib.pop(CONTINUATION, None) + depth = int(table.attrib.pop(QUOTE_DEPTH, '0')); table.attrib.pop(CONTINUATION, None) props = properties(table, 'tblPr') - if list_target in LIST_TARGETS: - rule = self.contextual_list_rule(list_target, {}, level) - child(props, 'tblInd').attrib.update({W+'type':'dxa', W+'w':str(round(rule['left_indent_value'] * 20))}) + if list_target in LIST_TARGETS or depth: + left = 0 + if list_target in LIST_TARGETS: + rule = self.contextual_list_rule(list_target, {}, level) + left = rule['left_indent_value'] + left += (font_points(self.effective['paragraph']) + 3) * depth + # With no tblInd, Word aligns the table edge at the margin. + # An explicit tblInd instead positions the first cell's text. + # Retain the cell inset so the whole table moves by the context. + left += self.table_padding('left') + child(props, 'tblInd').attrib.update({W+'type':'dxa', W+'w':str(round(left * 20))}) remove_fields(props, ('tblBorders', 'tblCellMar', 'shd')) val(props, 'tblStyle', style_id('table')) child(props, 'tblLayout').set(W + 'type', 'autofit') diff --git a/mdhelper/resources/word_inline_styles.lua b/mdhelper/resources/word_inline_styles.lua index 562b241..252569a 100644 --- a/mdhelper/resources/word_inline_styles.lua +++ b/mdhelper/resources/word_inline_styles.lua @@ -50,7 +50,9 @@ local function list_paragraphs(list) for _, item in ipairs(list.content) do -- Word numbers paragraphs, not tables. Give a table-first item its own -- empty numbered paragraph; its following text remains a continuation. - if item[1] and item[1].t == 'Table' then + local first = item[1] + while first and (first.t == 'BlockQuote' or first.t == 'Div') do first = first.content[1] end + if first and first.t == 'Table' then item:insert(1, pandoc.Div({pandoc.Para({pandoc.Str('\u{200b}')})}, pandoc.Attr('', {}, {['custom-style']='MDHelperSourceTableMarker'}))) end @@ -98,7 +100,8 @@ local function contexts(blocks, target, level, depth, item_state) elseif block.t == 'Div' then block.content = contexts(block.content, target, level, depth, item_state) else - if block.t == 'Header' or block.t == 'CodeBlock' or block.t == 'Table' then + if block.t == 'Header' or block.t == 'CodeBlock' or block.t == 'Table' or + (depth > 0 and (block.t == 'Para' or block.t == 'Plain')) then local continuation = item_state and not item_state.pending and '1' or '0' output:insert(pandoc.RawBlock('openxml', '{const s=getComputedStyle(document.querySelector('p'));return [parseFloat(s.fontSize),s.fontStyle]})()") + assert result[0] == pytest.approx(20*4/3, abs=.01) and result[1] == 'italic' + dialog = DocumentStyleEditorDialog(payload) + try: + assert dialog.font_size_spin.value() == 20 + dialog.font_size_spin.setValue(22) + rule = analyze_css(dialog.style_payload()['css']).rules['paragraph'] + assert rule['font_size'] == 22 and rule['english_font_family'] == family and rule['italic'] + dialog.extra_css_edit.setPlainText(css) + assert dialog.style_payload()['rules']['paragraph']['font_size'] == 20 + assert dialog.font_size_spin.value() == 20 + finally: dialog.close() + + +@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc']) +def test_valid_family_exports_editable_size_and_italic(tmp_path, engine): + rules = normalize_payload({'css':'p{font:italic 20pt Initial Font}'})['rules'] + doc, styles = parts(export_markdown_to_docx('Text', tmp_path/'font.docx', engine=engine, style_rules=rules)) + base = styles.find("w:style[@w:styleId='MDHelperParagraph']/w:rPr", NS) + assert base.find(W+'sz').get(W+'val') == '40' + assert base.find(W+'i').get(W+'val') == '1' + base.find(W+'sz').set(W+'val', '48') + assert effective_document(doc, styles).find('.//w:r/w:rPr/w:sz', NS).get(W+'val') == '48' diff --git a/tests/test_document_style.py b/tests/test_document_style.py index 2e76606..9785b8f 100644 --- a/tests/test_document_style.py +++ b/tests/test_document_style.py @@ -106,9 +106,9 @@ def test_word_preserves_all_settings_and_content(tmp_path: Path, engine): assert spacing.get(W + "before") == spacing.get(W + "after") == "0" assert spacing.get(W + "line") == "400" and spacing.get(W + "lineRule") == "exact" ind = ppr.find(W + "ind") - # List geometry uses absolute lengths so Word's document grid cannot - # shift code/heading continuations away from their list's text column. - assert ind.get(W + "firstLineChars") == ("0" if ppr.find(W + 'numPr') is not None else "200") + # List/quote geometry uses absolute lengths, independent of Word's grid. + absolute = ppr.find(W + 'numPr') is not None or ''.join(p.itertext()).startswith('Quote') + assert ind.get(W + "firstLineChars") == ("0" if absolute else "200") assert ind.get(W + "firstLine") == "420" and ind.get(W + "right") == "120" assert ind.get(W + "left") == "850" for name, value in (("keepNext", "1"), ("keepLines", "1"), ("contextualSpacing", "1"), ("pageBreakBefore", "0"), ("widowControl", "0")): diff --git a/tests/test_startup_revision_058.py b/tests/test_startup_revision_058.py new file mode 100644 index 0000000..22c5d53 --- /dev/null +++ b/tests/test_startup_revision_058.py @@ -0,0 +1,29 @@ +"""Empty and invalid directory history must not resolve to the working folder.""" +from unittest.mock import MagicMock +import pytest +from PySide6.QtCore import QSettings +from mdhelper import app + + +@pytest.mark.parametrize('history', [None, '', ' ', 'missing', 'file', 'directory']) +def test_startup_history_requires_a_nonempty_directory(tmp_path, monkeypatch, history): + settings = QSettings(str(tmp_path/'settings.ini'), QSettings.Format.IniFormat) + folder = tmp_path/'project'; folder.mkdir() + file = folder/'note.md'; file.write_text('Text') + value = {'missing': str(tmp_path/'missing'), 'file': str(file), 'directory': str(folder)}.get(history, history) + if value is not None: settings.setValue('project/last_root', value) + window = MagicMock() + monkeypatch.setattr(app, 'QSettings', lambda *_: settings) + monkeypatch.setattr(app, 'QApplication', MagicMock()) + monkeypatch.setattr(app, 'MainWindow', window) + monkeypatch.setattr(app, 'configure_process_runtime', lambda *_: None) + monkeypatch.setattr(app, 'setup_logging', lambda *_: None) + app.main([]) + args = window.call_args.kwargs + assert args['project_root'] == (folder if history == 'directory' else None) + assert args['prompt_for_project'] == (history != 'directory') + assert args['initial_path'] is None + # Explicit startup files still take precedence over all history values. + app.main([str(file)]) + assert window.call_args.kwargs['project_root'] == folder + assert window.call_args.kwargs['initial_path'] == file diff --git a/tests/test_style_revision_055.py b/tests/test_style_revision_055.py index 31fca5e..7e6234e 100644 --- a/tests/test_style_revision_055.py +++ b/tests/test_style_revision_055.py @@ -93,7 +93,8 @@ def test_quoted_list_keeps_additive_nested_indents(tmp_path, engine): text=''.join(p.itertext()) if text in ('Outer','Inner'): ind=p.find('w:pPr/w:ind',NS) - assert int(ind.get(W+'left'))/20 == (36 if text=='Outer' else 72) + # Include the quote container's 12 pt padding and 3 pt border. + assert int(ind.get(W+'left'))/20 == (51 if text=='Outer' else 87) assert ind.get(W+'hangingChars','0')=='0' diff --git a/tests/test_style_revision_058.py b/tests/test_style_revision_058.py new file mode 100644 index 0000000..36b865c --- /dev/null +++ b/tests/test_style_revision_058.py @@ -0,0 +1,68 @@ +"""Nested list markers and quote containers remain shared, editable Word styles.""" +import pytest +from mdhelper.docx_exporter import export_markdown_to_docx +from mdhelper.docx_style import W, NS +from test_style_regressions import parts +from docx_assertions import effective_document + +ENGINES = ['builtin', 'python-docx', 'pandoc'] +NESTED_TABLE = '1. Outer\n - | HeadOne | HeadTwo |\n |---|---|\n | CellOne | CellTwo |\n\n2. End' +QUOTE_TABLE = '1. > | HeadOne | HeadTwo |\n > |---|---|\n > | CellOne | CellTwo |\n\n2. End' +NESTED_FIRST = '1. - FirstChild\n - SecondChild\n\n2. End' +QUOTE_TEXT = '> OuterText\n>\n> > InnerText\n> >\n> > ### InnerHeading\n> >\n> > ```text\n> > InnerCode\n> > ```' +MIXED_QUOTE = '1. Outer\n\n > - Inner\n >\n > Continued\n >\n > ### Heading\n >\n > ```text\n > CodeLine\n > ```\n\n2. End' + + +@pytest.mark.parametrize('engine', ENGINES) +@pytest.mark.parametrize('source', [NESTED_TABLE, QUOTE_TABLE, NESTED_FIRST]) +def test_nested_blocks_keep_parent_marker_and_content(tmp_path, engine, source): + doc, styles = parts(export_markdown_to_docx(source, tmp_path/'nested.docx', engine=engine)) + paragraphs = doc.findall('w:body/w:p', NS) + first, last = paragraphs[0], paragraphs[-1] + assert first.find('w:pPr/w:numPr', NS) is not None + assert first.find('w:pPr/w:numPr/w:numId', NS).get(W+'val') == last.find('w:pPr/w:numPr/w:numId', NS).get(W+'val') + assert 'H2' not in first.find('w:pPr/w:pStyle', NS).get(W+'val') + if 'HeadOne' in source: + assert [''.join(c.itertext()) for c in doc.findall('.//w:tbl/w:tr/w:tc', NS)] == ['HeadOne','HeadTwo','CellOne','CellTwo'] + assert '\u200b' not in ''.join(doc.itertext()) + assert not any(a.startswith('{urn:mdhelper:source}') for el in doc.iter() for a in el.attrib) + + +@pytest.mark.parametrize('engine', ENGINES) +def test_parent_text_after_nested_list_is_a_continuation(tmp_path, engine): + source = NESTED_FIRST.replace('\n\n2. End', '\n\n Continued\n\n2. End') + doc, _ = parts(export_markdown_to_docx(source, tmp_path/'continued.docx', engine=engine)) + p = next(p for p in doc.iter(W+'p') if ''.join(p.itertext()) == 'Continued') + assert p.find('w:pPr/w:numPr', NS) is None + + +@pytest.mark.parametrize('engine', ENGINES) +def test_nested_quote_text_keeps_depth_and_base_font_inheritance(tmp_path, engine): + doc, styles = parts(export_markdown_to_docx(QUOTE_TEXT, tmp_path/'quote.docx', engine=engine)) + effective = effective_document(doc, styles) + def left(text): + p = next(p for p in effective.iter(W+'p') if ''.join(p.itertext()) == text) + return int(p.find('w:pPr/w:ind', NS).get(W+'left')) + assert left('InnerText') - left('OuterText') == 300 + styles.find("w:style[@w:styleId='MDHelperBlockquote']/w:rPr/w:color", NS).set(W+'val','008000') + for p in effective_document(doc,styles).iter(W+'p'): + if ''.join(p.itertext()) in ('OuterText', 'InnerText'): + assert p.find('.//w:rPr/w:color',NS).get(W+'val') == '008000' + + +@pytest.mark.parametrize('engine', ENGINES) +def test_mixed_quote_containers_align_text_headings_and_code(tmp_path, engine): + doc, styles = parts(export_markdown_to_docx(MIXED_QUOTE, tmp_path/'mixed.docx', engine=engine)) + positions = [] + for p in effective_document(doc,styles).iter(W+'p'): + if ''.join(p.itertext()) in ('Inner','Continued','Heading','CodeLine'): + positions.append(int(p.find('w:pPr/w:ind',NS).get(W+'left'))) + assert positions == [1500]*4 + + +@pytest.mark.parametrize('engine', ENGINES) +@pytest.mark.parametrize('depth', [1, 2]) +def test_quoted_tables_preserve_container_depth(tmp_path, engine, depth): + source = '\n'.join('> '*depth+line for line in ['| Head |','|---|','| Cell |']) + doc, _ = parts(export_markdown_to_docx(source, tmp_path/'table.docx', engine=engine)) + assert doc.find('.//w:tblPr/w:tblInd', NS).get(W+'w') == str(round(depth*300 + 12*.76*20)) diff --git a/tests/word_revision_055_smoke.ps1 b/tests/word_revision_055_smoke.ps1 index 09e693d..bf7f4df 100644 --- a/tests/word_revision_055_smoke.ps1 +++ b/tests/word_revision_055_smoke.ps1 @@ -45,7 +45,7 @@ print(folder) if($text -eq 'Continuation' -and $range.ListFormat.ListString.Trim() -ne ''){throw "$engine continuation consumed a marker"} } } elseif($case -eq 'quoted') { - foreach($pair in @(@('Outer',36),@('Inner',72))) { + foreach($pair in @(@('Outer',51),@('Inner',87))) { $range=$doc.Content.Duplicate;[void]$range.Find.Execute($pair[0]) if([Math]::Abs($range.ParagraphFormat.LeftIndent-$pair[1]) -gt 0.1){throw "$engine quoted $($pair[0]) indent: $($range.ParagraphFormat.LeftIndent)"} } diff --git a/tests/word_revision_058_smoke.ps1 b/tests/word_revision_058_smoke.ps1 new file mode 100644 index 0000000..01536f4 --- /dev/null +++ b/tests/word_revision_058_smoke.ps1 @@ -0,0 +1,87 @@ +param([string]$Python = (Join-Path $PSScriptRoot '..\mdhelper_env\mdhelper_env\Scripts\python.exe')) +$ErrorActionPreference='Stop' +Push-Location (Join-Path $PSScriptRoot '..') +$word=$null +try { + $folder = (@' +import sys,tempfile +from pathlib import Path +sys.path.insert(0,str(Path('tests').resolve())) +from test_style_revision_058 import * +from mdhelper.style_sync import normalize_payload +folder=Path(tempfile.mkdtemp(prefix='MDHelper-058-Word-')) +for engine in ENGINES: + for name,source in [('nested-table',NESTED_TABLE),('quote-table',QUOTE_TABLE),('nested-first',NESTED_FIRST),('quote-text',QUOTE_TEXT),('mixed',MIXED_QUOTE)]: + export_markdown_to_docx(source,folder/f'{engine}-{name}.docx',engine=engine) + for depth in range(3): + source='\n'.join('> '*depth+line for line in ['| Head |','|---|','| Cell |']) + export_markdown_to_docx(source,folder/f'{engine}-table-{depth}.docx',engine=engine) + rules=normalize_payload({'css':'p{font:italic 20pt Initial Font}'})['rules'] + export_markdown_to_docx('Text',folder/f'{engine}-font.docx',engine=engine,style_rules=rules) +print(folder) +'@ | & $Python -B -).Trim() + if($LASTEXITCODE -ne 0){throw 'Fixture generation failed'} + $word=New-Object -ComObject Word.Application + $word.Visible=$false;$word.DisplayAlerts=0 + foreach($engine in @('builtin','python-docx','pandoc')) { + foreach($case in @('nested-table','quote-table','nested-first','quote-text','mixed','table-0','table-1','table-2','font')) { + $doc=$word.Documents.Open((Join-Path $folder "$engine-$case.docx"),$false,$true,$false) + try { + if($case -in @('nested-table','quote-table','nested-first')) { + if($doc.Paragraphs.Item(1).Range.ListFormat.ListString.Trim() -ne '1.'){throw "$engine $case parent number missing"} + $r=$doc.Content.Duplicate;[void]$r.Find.Execute('End') + if($r.ListFormat.ListString.Trim() -ne '2.'){throw "$engine $case next number wrong"} + if($case -eq 'nested-table') { + $r=$doc.Content.Duplicate;[void]$r.Find.Execute('Outer') + if($r.Style.NameLocal -match '标题|Heading'){throw "$engine parent became a heading"} + } + } elseif($case -eq 'font') { + $r=$doc.Content.Duplicate;[void]$r.Find.Execute('Text') + if($r.Font.Size -ne 20 -or $r.Font.Italic -ne -1){throw "$engine font CSS lost"} + $doc.Styles.Item('MDHelper 正文').Font.Size=24 + if($r.Font.Size -ne 24){throw "$engine font no longer follows paragraph style"} + } else { + $doc.ExportAsFixedFormat((Join-Path $folder "$engine-$case.pdf"),17) + if($case -eq 'quote-text') { + $doc.Styles.Item('MDHelper 引用').Font.Color=255 + foreach($text in @('OuterText','InnerText')) { + $r=$doc.Content.Duplicate;[void]$r.Find.Execute($text) + if($r.Font.Color -ne 255){throw "$engine nested quote lost base inheritance"} + } + } elseif($case -eq 'mixed') { + $doc.Styles.Item('MDHelper 标题 3').Font.Size=20 + $r=$doc.Content.Duplicate;[void]$r.Find.Execute('Heading') + if($r.Font.Size -ne 20){throw "$engine nested heading lost base inheritance"} + } + } + Write-Output "$engine $case PASS" + } finally {$doc.Close(0)} + } + } + @' +import sys +from pathlib import Path +from pypdf import PdfReader +folder=Path(sys.argv[1]) +def positions(name): + result={} + def visit(text,cm,tm,font,size): + if text.strip():result[text.strip()]=tm[4]*cm[0]+tm[5]*cm[2]+cm[4] + for page in PdfReader(folder/name).pages:page.extract_text(visitor_text=visit) + return result +for engine in ('builtin','python-docx','pandoc'): + quote=positions(f'{engine}-quote-text.pdf') + assert abs(quote['InnerText']-quote['OuterText']-15)<.3,(engine,quote) + mixed=positions(f'{engine}-mixed.pdf') + values=[mixed[x] for x in ('Inner','Continued','Heading','CodeLine')] + assert max(values)-min(values)<.3,(engine,mixed) + tables=[positions(f'{engine}-table-{d}.pdf')['Head'] for d in range(3)] + assert all(abs(tables[d]-tables[d-1]-15)<.3 for d in (1,2)),(engine,tables) + print(engine,'actual Word quote/table layout PASS') +'@ | & $Python -B - $folder + if($LASTEXITCODE -ne 0){throw 'Word PDF layout failed'} + Write-Output "Fixtures: $folder" +} finally { + if($word){$word.Quit();[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($word)} + Pop-Location +}