From bfadd8b8e9d3a4191929c3b1acd6b125b3857302 Mon Sep 17 00:00:00 2001 From: shen Date: Fri, 30 Oct 2026 14:53:22 +0800 Subject: [PATCH] fix: align legacy styles, nested paragraphs and Word export --- docs/architecture.md | 2 + docs/user_manual.md | 8 +- mdhelper/document_style.py | 10 +- mdhelper/docx_exporter.py | 33 ++++-- mdhelper/docx_inline.py | 2 + mdhelper/docx_semantic.py | 52 ++++++++-- mdhelper/resources/word_inline_styles.lua | 10 +- mdhelper/style_catalog.py | 14 ++- mdhelper/style_dialog.py | 16 ++- mdhelper/style_sync.py | 49 +++++++-- tests/test_style_revision_053.py | 121 ++++++++++++++++++++++ tests/word_styles_smoke.ps1 | 34 +++++- 12 files changed, 309 insertions(+), 42 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 658b548..9f191f3 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -53,6 +53,8 @@ CSS 同步按三个步骤处理:`_collect_cascade` 决定生效的声明,`_C 选择器先区分独立元素与旧版完整基准组;级联项同时记录声明归属,避免将基准值复制成子样式的显式覆盖。Word 组合字符样式也记录最终属性归属,初始值相等不会抹去内层覆盖。用于命名列表样式的编号定义复制后移除缩进,并分配独立 `nsid`,避免 Word 合并新旧定义而恢复旧缩进。 +跨类型的旧 `code`/`table` 文字基准由 `legacy_base` 统一判断,缺省保留兼容,显式空 `based_on` 表示解除。Markdown 列对齐通过派生段落样式保留;引用中的宽松列表由临时段落标记跨引擎传递,再转换为基于引用的组合样式。编号和层级保持独立,临时标记在最终导出中清除。边框样式作为独立字段同步,Word 的无边框使用 `none`,避免 `nil` 在实际 Word 中成为未定义状态。 + 明确无效的声明在级联选择前忽略;简写中任一无效组件使整条简写失效,有效但不支持的表达式仍遮盖前面的值。普通 `p` 同时映射引用段落及 `rules._list_paragraph` 上下文;各引擎通过临时段落标记区分宽松列表和紧凑列表。表格文字使用独立内容容器承载段间距,表格边框和单元格内边距保持原位置。 `render_css` 使用与图形写入相同的字体变量表达继承,并生成列表层级缩进及独立文字修饰的辅助规则。显式取消列表基准时会恢复该语义类型的默认格式,旧配置缺少元数据时仍保留兼容基准。 diff --git a/docs/user_manual.md b/docs/user_manual.md index 953b6fb..14293aa 100644 --- a/docs/user_manual.md +++ b/docs/user_manual.md @@ -154,7 +154,7 @@ Markdown 支持: - 正文、一级到六级标题、引用、无序/有序/任务列表、代码块、表头文字和单元格文字。 - 加粗、强调、删除线、超链接、行内代码采用字符样式;可设置下划线、删除线和背景色,未设置的字体与字号继承所在段落。 -- 表格基准可设置边框颜色、宽度和单元格内边距;列表可设置标记形式与嵌套层级缩进。 +- 表格基准可设置边框颜色、宽度、实线/虚线/无边框等样式和单元格内边距;列表可设置标记形式与嵌套层级缩进。 - 中文字体和英文字体分开设置。 - 字号支持磅(pt)、像素(px)和中文常用字号,例如五号 10.5 磅;可设置加粗、斜体、字体颜色和字符间距。 - 对齐支持左对齐、居中、右对齐和两端对齐。 @@ -165,6 +165,8 @@ Markdown 支持: “继承”沿用基准样式或文档默认值;数字 0 表示明确清零。复选框方块表示继承、勾选表示开启、空白表示关闭。设置窗口下方提供快速预览,“实际阅读效果”页使用阅读器显示完整示例;分页效果以 Word 为准。旧样式文件会自动兼容原有的像素字号、字符间距和缩进。 +行内代码、表头和单元格的“兼容:代码基准 / 表格基准”表示沿用旧配置。显式选择“文档默认 / 所在段落”会解除该兼容继承;也可以重新选择兼容基准。仅修改名称不会解除原有继承。 + ### 样式面板与 Word 导出 打开“样式 → 样式面板”,可查看全部样式或当前文档已用样式。编辑 Markdown 时,面板提示光标所在段落及其中包含的字符样式。双击条目修改样式名称、同类型基准及格式;改变样式不会改写 Markdown 内容。基于内置样式修改时自动创建自定义样式集,并保留原内置样式的字体、行距等基础信息,导出 Word 和迁移样式文件后继续生效。 @@ -179,6 +181,8 @@ Word 每段文字只能引用一个字符样式,因此加粗链接等组合会 内层明确设置与基准的初始值相同时,也会保留该覆盖关系;之后修改基准不会改变内层的明确设置。列表的缩进由命名段落样式控制,编号只负责标记和序号,因此在 Word 样式面板调整首行、悬挂和左右缩进可以继续生效。 +Markdown 表格明确指定的列对齐会保存为基于表头或单元格文字样式的派生样式,字体等格式继续继承。引用中的宽松列表保留引用格式,生成基于引用样式的“引用内段落”组合样式;其列表布局或其他独立覆盖可通过该组合样式统一调整。Word 一个段落样式只有一个基准,组合样式不会同时继承列表和引用两条基准链。 + Word 的字符样式会把加粗、斜体和删除线作为与段落格式叠加的开关。导出采用强调保护:明确字符样式中的这些字形设置会固定在对应文字上,避免修改正文或标题样式时反向关闭强调。字体、字号、颜色、下划线和段落仍由命名样式统一控制;受保护的加粗、斜体和删除线不能仅通过 Word 字符样式关闭,可在 MDHelper 调整后重新导出,或在 Word 中清除对应文字的直接字形格式再使用其原生样式规则。 纸张宽度是全局阅读设置,内置样式不再写死正文宽度,会跟随纸张宽度变化。 @@ -193,6 +197,8 @@ Word 的字符样式会把加粗、斜体和删除线作为与段落格式叠加 普通 `p` 选择器也作用于引用和宽松列表中的段落,Word 会保留这些上下文格式;紧凑列表没有独立段落元素,不受该选择器影响。表头和单元格的段前、段后及左右间距作用于内部文字区域,表格内边距仍独立设置。明显无效的 CSS 值(例如 `font-size:nope`)会被忽略并提示,前面的有效声明继续同步;有效但不能转换为 Word 的扩展表达式仍保留为 CSS。 +宽松列表中明确设置的 `p` 间距和缩进不会被列表辅助规则清零。图形设置修改引用等子对象时,会保留必要的 `!important` 优先级,使修改真正生效。无效的多值声明、错误单位和互斥文字修饰同样按浏览器的回退规则处理;`border-style:none` / `hidden` 会同步为 Word 无边框,改变宽度不会重新开启边框。 + 颜色选择“随所在文字颜色”(CSS `currentColor` / `inherit`)会继承段落或外层文字的颜色,不等同于“自动(随主题)”。如果它同时需要取消某个字符基准中的固定颜色,Word 无法只取消一个继承属性,因此导出会将该基准的其他已解析格式保留在当前命名字符样式内;导出后请修改此命名样式,其他普通样式的基准继承保持不变。 例如,将正文规则中的 `font-size: 12pt` 改成 `font-size: 14pt`,图形字号会变为 14 磅,导出 Word 也使用 14 磅。之后在图形界面调整字号,CSS 对应值会随之更新。删除某项属性后,如果没有其他常规规则提供该属性,图形设置显示“继承”。 diff --git a/mdhelper/document_style.py b/mdhelper/document_style.py index 3e94e70..89e15c7 100644 --- a/mdhelper/document_style.py +++ b/mdhelper/document_style.py @@ -68,6 +68,7 @@ def normalize_rule(value: object) -> dict[str, Any]: if key in rule and not re.fullmatch(r"auto|transparent|inherit|#[0-9a-fA-F]{6}", str(rule[key])): rule.pop(key) for key, allowed in {"alignment": {"left", "center", "right", "justify"}, + "border_style": {'none','hidden','solid','dotted','dashed','double','groove','ridge','inset','outset'}, "indent_mode": {"none", "first", "hanging"}, "line_spacing_mode": {"multiple", "exact", "at_least"}}.items(): if key in rule and rule[key] not in allowed: @@ -185,7 +186,10 @@ def css_declarations(value: dict) -> list[str]: if 'border_color' in r: out.append(f"border-color: {r['border_color']};") if 'border_width' in r: - out.extend((f"border-width: {fmt(r['border_width'])}pt;", 'border-style: solid;')) + out.append(f"border-width: {fmt(r['border_width'])}pt;") + if 'border_style' not in r: out.append('border-style: solid;') + if 'border_style' in r: + out.append(f"border-style: {r['border_style']};") if 'cell_padding' in r: out.append(f"padding: {fmt(r['cell_padding'])}pt;") if 'list_marker' in r: @@ -216,7 +220,7 @@ def css_declarations(value: dict) -> list[str]: return out -def build_document_style_css(rules: dict | None, extra_css: str = "") -> str: +def build_document_style_css(rules: dict | None, extra_css: str = "", *, reset_list_paragraphs=True) -> str: parts = [] rules = rules if isinstance(rules, dict) else {} p = normalize_rule(rules.get("paragraph")) @@ -227,7 +231,7 @@ def build_document_style_css(rules: dict | None, extra_css: str = "") -> str: declarations = css_declarations(rule) if declarations: parts.append(selector + " {\n " + "\n ".join(declarations) + "\n}") - if target in ("list", 'list_bullet', 'list_ordered', 'list_task'): + if reset_list_paragraphs and target in ("list", 'list_bullet', 'list_ordered', 'list_task'): # Loose Markdown lists contain p elements; spacing belongs to li. parts.append(".reader li > p { margin: 0; text-indent: inherit; }") if 'level_indent' in rule: diff --git a/mdhelper/docx_exporter.py b/mdhelper/docx_exporter.py index a0afe05..5c56829 100644 --- a/mdhelper/docx_exporter.py +++ b/mdhelper/docx_exporter.py @@ -7,7 +7,7 @@ import sys import tempfile import time import zipfile -from dataclasses import dataclass +from dataclasses import dataclass, field from pathlib import Path from xml.sax.saxutils import escape, quoteattr @@ -15,7 +15,7 @@ from markdown_it import MarkdownIt from markdown_it.token import Token from .markdown_compat import cjk_strong_plugin -from .docx_inline import source_style_name, LIST_PARAGRAPH_STYLE +from .docx_inline import source_style_name, LIST_PARAGRAPH_STYLE, QUOTED_LIST_PARAGRAPH_STYLE, SOURCE_PARAGRAPH_STYLES WP_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main" @@ -118,7 +118,7 @@ def export_markdown_to_docx_builtin(source: str, output_path: Path) -> Path: package.writestr("_rels/.rels", PACKAGE_RELS_XML) package.writestr("word/document.xml", document_xml) markers = ''.join(f'' for name in sorted(source_styles)) - markers += f'' + markers += ''.join(f'' for name in SOURCE_PARAGRAPH_STYLES) package.writestr("word/styles.xml", STYLES_XML.replace('', markers + '')) package.writestr("word/settings.xml", SETTINGS_XML) relations = ''.join(f'' for href, identifier in links.items()) @@ -248,10 +248,11 @@ def _add_python_docx_paragraph(document: object, block: ParagraphBlock) -> None: if block.list_kind and block.loose: from docx.enum.style import WD_STYLE_TYPE - if LIST_PARAGRAPH_STYLE not in document.styles: - marker = document.styles.add_style(LIST_PARAGRAPH_STYLE, WD_STYLE_TYPE.PARAGRAPH) + name = QUOTED_LIST_PARAGRAPH_STYLE if block.quote_depth else LIST_PARAGRAPH_STYLE + if name not in document.styles: + marker = document.styles.add_style(name, WD_STYLE_TYPE.PARAGRAPH) marker.base_style = document.styles[style] - style = LIST_PARAGRAPH_STYLE + style = name paragraph = document.add_paragraph(style=style) if block.list_kind: from docx.oxml import parse_xml @@ -301,6 +302,9 @@ def _add_python_docx_table(document: object, block: TableBlock) -> None: cell = table.cell(row_index, col_index) runs = row[col_index] if col_index < len(row) else [("", {})] paragraph = cell.paragraphs[0] + if col_index < len(block.alignments) and block.alignments[col_index]: + from docx.enum.text import WD_ALIGN_PARAGRAPH + paragraph.alignment = {'left':WD_ALIGN_PARAGRAPH.LEFT,'center':WD_ALIGN_PARAGRAPH.CENTER,'right':WD_ALIGN_PARAGRAPH.RIGHT}[block.alignments[col_index]] for text, run_style in runs: _add_python_docx_run(paragraph, text, run_style) @@ -327,11 +331,13 @@ class ParagraphBlock: list_id: int = 0 list_start: int = 1 loose: bool = False + alignment: str = '' @dataclass class TableBlock: rows: list[list[list[tuple[str, dict[str, bool]]]]] + alignments: list[str] = field(default_factory=list) class _DocxBuilder: @@ -390,6 +396,7 @@ class _DocxBuilder: def _collect_table(self) -> TableBlock: rows: list[list[list[tuple[str, dict[str, bool]]]]] = [] + alignments = [] current_row: list[list[tuple[str, dict[str, bool]]]] | None = None while self.index < len(self.tokens): token = self.tokens[self.index] @@ -399,6 +406,9 @@ class _DocxBuilder: rows.append(current_row) current_row = None elif token.type in {"th_open", "td_open"} and current_row is not None: + if token.type == 'th_open': + value = (token.attrGet('style') or '').removeprefix('text-align:').strip() + alignments.append(value if value in ('left','center','right') else '') inline = self.tokens[self.index + 1] if self.index + 1 < len(self.tokens) else None cell_runs = _inline_runs(inline.children if inline is not None else None) current_row.append(cell_runs) @@ -406,7 +416,7 @@ class _DocxBuilder: self.index += 1 break self.index += 1 - return TableBlock(rows) + return TableBlock(rows, alignments) def _inline_runs(children: list[Token] | None) -> list[tuple[str, dict[str, object]]]: @@ -479,10 +489,12 @@ def _block_xml(block: ParagraphBlock | TableBlock) -> str: def _paragraph_xml(block: ParagraphBlock) -> str: props = [f''] if block.style != "Normal" else [] if block.list_kind: - props = [f''] + name = (QUOTED_LIST_PARAGRAPH_STYLE if block.quote_depth else LIST_PARAGRAPH_STYLE) if block.loose else 'ListParagraph' + props = [f''] props.append(f'') if block.quote_depth: props.append('') + if block.alignment: props.append(f'') ppr = f"{''.join(props)}" if props else "" return f"{ppr}{''.join(_run_xml(text, style) for text, style in block.runs)}" @@ -526,8 +538,9 @@ def _table_xml(block: TableBlock) -> str: rows = [] for row in block.rows: cells = [] - for cell in row: - cells.append(f"{_paragraph_xml(ParagraphBlock(cell))}") + for index, cell in enumerate(row): + alignment = block.alignments[index] if index < len(block.alignments) else '' + cells.append(f"{_paragraph_xml(ParagraphBlock(cell, alignment=alignment))}") rows.append(f"{''.join(cells)}") return ( '' diff --git a/mdhelper/docx_inline.py b/mdhelper/docx_inline.py index f4f9f05..61834bc 100644 --- a/mdhelper/docx_inline.py +++ b/mdhelper/docx_inline.py @@ -1,6 +1,8 @@ """Private, temporary style markers shared by the three DOCX converters.""" PREFIX = 'MDHelperSource_' LIST_PARAGRAPH_STYLE = 'MDHelperSourceListParagraph' +QUOTED_LIST_PARAGRAPH_STYLE = 'MDHelperSourceQuotedListParagraph' +SOURCE_PARAGRAPH_STYLES = (LIST_PARAGRAPH_STYLE, QUOTED_LIST_PARAGRAPH_STYLE) CODES = {'strong': 'B', 'emphasis': 'I', 'strike': 'S', 'link': 'L', 'inline_code': 'C'} diff --git a/mdhelper/docx_semantic.py b/mdhelper/docx_semantic.py index 4d9ca0e..bf98cea 100644 --- a/mdhelper/docx_semantic.py +++ b/mdhelper/docx_semantic.py @@ -11,9 +11,9 @@ import zipfile from lxml import etree as ET from .document_style import resolved_rules, normalize_rule, font_points, length_points, number -from .style_catalog import CATALOG, CHARACTER_DEFAULTS, explicit_rules, parent_style, style_name +from .style_catalog import CATALOG, CHARACTER_DEFAULTS, explicit_rules, parent_style, style_name, legacy_base from .docx_style import W, NS, child, val, properties, _run_properties, _paragraph_properties, _order_properties -from .docx_inline import source_style_order, ordered_styles, LIST_PARAGRAPH_STYLE +from .docx_inline import source_style_order, ordered_styles, LIST_PARAGRAPH_STYLE, QUOTED_LIST_PARAGRAPH_STYLE, SOURCE_PARAGRAPH_STYLES RUN_FIELDS = 'rFonts sz szCs b bCs i iCs color spacing u strike shd'.split() PARAGRAPH_FIELDS = 'jc spacing ind shd snapToGrid contextualSpacing keepNext keepLines pageBreakBefore widowControl rPr outlineLvl'.split() @@ -113,7 +113,7 @@ class WordStyles: base_id = self.paragraph(base) if base else '' # Table styles cannot be a paragraph's basedOn. A shared paragraph base # carries the legacy table text settings and remains editable in Word. - if key in ('table_head', 'table_cell') and not base: + if key in ('table_head', 'table_cell') and not base and legacy_base(key, self.rules): base_id = 'MDHelperTableText' if base_id not in self.created: table_text = self.new(base_id, 'paragraph', 'MDHelper 表格文字基准') @@ -303,6 +303,38 @@ class WordStyles: _delta(props, old, own) return identifier + def quoted_list(self, target, base_id, level): + """A real p inside a quoted list receives the quote's explicit format.""" + identifier = base_id + 'Quote' + if identifier not in self.created: + quote_id = self.paragraph('blockquote') + style = self.new(identifier, 'paragraph', 'MDHelper ' + style_name(target, self.rules) + '(引用内段落)' + (str(level + 1) if level else ''), quote_id) + own = self.explicit['blockquote'] + rule = {**self.effective[target], **normalize_rule(self.rules.get('_list_paragraph')), **own} + # Keep the list's marker layout as context-specific paragraph + # properties; quote typography remains inherited from its style. + if level: + points = font_points(rule) + offset = level * number(rule.get('level_indent', 36)) + if rule['left_indent_unit'] == 'em': rule['left_indent_value'] += offset / points + else: + rule['left_indent_value'] = length_points(rule['left_indent_value'], rule['left_indent_unit'], points) + offset + rule['left_indent_unit'] = 'pt' + for tag, writer in (('pPr', _paragraph_properties), ('rPr', _run_properties)): + props, old = child(style, tag), ET.Element(W + tag) + writer(props, rule); writer(old, self.effective['blockquote']) + if tag == 'rPr': remove_fields(props, ('shd',)); remove_fields(old, ('shd',)) + _delta(props, old) + return identifier + + def table_column(self, target, alignment): + identifier = style_id(target) + alignment.capitalize() + if identifier not in self.created: + label = {'left':'左对齐','center':'居中','right':'右对齐','both':'两端对齐'}[alignment] + style = self.new(identifier, 'paragraph', 'MDHelper ' + style_name(target, self.rules) + f'({label}列)', self.paragraph(target)) + val(child(style, 'pPr'), 'jc', alignment) + return identifier + def apply_list_marker(self, numpr, target, marker): level, original_level = self.list_level(numpr) if original_level is None: return @@ -341,7 +373,8 @@ class WordStyles: element = child(borders, edge) width = number(rule.get('border_width', .5)) color = str(rule.get('border_color', '#d0d7de')) - element.attrib.update({W + 'val': 'single' if width and color != 'transparent' else 'nil', W + 'sz': str(max(2, round(width * 8))), W + 'color': color.lstrip('#') if color != 'transparent' else 'auto'}) + border = {'none':'none','hidden':'none','solid':'single','dotted':'dotted','dashed':'dashed','double':'double','groove':'threeDEngrave','ridge':'threeDEmboss','inset':'inset','outset':'outset'}.get(rule.get('border_style'), 'single') + element.attrib.update({W + 'val': border if width and color != 'transparent' else 'none', W + 'sz': str(max(2, round(width * 8))), W + 'color': color.lstrip('#') if color != 'transparent' else 'auto'}) if 'cell_padding' in rule: margins = child(props, 'tblCellMar') for side in ('top', 'left', 'bottom', 'right'): @@ -388,7 +421,8 @@ class WordStyles: for paragraph in document.iter(W + 'p'): ppr = properties(paragraph, 'pPr') original_id = reference(ppr, 'pStyle') or 'Normal' - loose = any(reference(style, 'name') == LIST_PARAGRAPH_STYLE for style in self.chain(original_id)) + names = {reference(style, 'name') for style in self.chain(original_id)} + loose = bool(names & set(SOURCE_PARAGRAPH_STYLES)) target = self.classify(paragraph, original_id) identifier = self.paragraph(target) if target.startswith('list_'): @@ -399,6 +433,10 @@ class WordStyles: marker = self.effective[target].get('list_marker') if marker: self.apply_list_marker(numpr, target, marker) if loose: identifier = self.list_paragraph(target, identifier) + if QUOTED_LIST_PARAGRAPH_STYLE in names: identifier = self.quoted_list(target, identifier, level) + alignment = reference(ppr, 'jc') + if target in ('table_head','table_cell') and alignment in ('left','center','right','both'): + identifier = self.table_column(target, alignment) remove_fields(ppr, PARAGRAPH_FIELDS) val(ppr, 'pStyle', identifier) for run in paragraph.iter(W + 'r'): self.apply_run(run, target) @@ -424,14 +462,14 @@ def apply_semantic_styles(path, rules, **defaults): if name in parts: for paragraph in parts[name].iter(W + 'p'): identifier = reference(paragraph.find(W + 'pPr'), 'pStyle') - if any(reference(s, 'name') == LIST_PARAGRAPH_STYLE for s in adapter.chain(identifier)): + if any(reference(s, 'name') in SOURCE_PARAGRAPH_STYLES for s in adapter.chain(identifier)): adapter.apply(paragraph) for run in parts[name].iter(W + 'r'): identifier = reference(run.find(W + 'rPr'), 'rStyle') if any(source_style_order(reference(s, 'name')) for s in adapter.chain(identifier)): adapter.apply_run(run, 'paragraph') for style in list(parts['word/styles.xml']): - if source_style_order(reference(style, 'name')) or reference(style, 'name') == LIST_PARAGRAPH_STYLE: + if source_style_order(reference(style, 'name')) or reference(style, 'name') in SOURCE_PARAGRAPH_STYLES: parts['word/styles.xml'].remove(style) for filename, root in parts.items(): _order_properties(root) diff --git a/mdhelper/resources/word_inline_styles.lua b/mdhelper/resources/word_inline_styles.lua index 635a0dc..f13cd6b 100644 --- a/mdhelper/resources/word_inline_styles.lua +++ b/mdhelper/resources/word_inline_styles.lua @@ -56,5 +56,13 @@ local function list_paragraphs(list) end return list end +local function quoted_paragraphs(quote) + return quote:walk({Div=function(block) + if block.attributes['custom-style'] == 'MDHelperSourceListParagraph' then + block.attributes['custom-style'] = 'MDHelperSourceQuotedListParagraph' + end + return block + end}) +end return {{Inlines=function(items) return mark(items, {}) end}, - {BulletList=list_paragraphs, OrderedList=list_paragraphs}} + {BulletList=list_paragraphs, OrderedList=list_paragraphs, BlockQuote=quoted_paragraphs}} diff --git a/mdhelper/style_catalog.py b/mdhelper/style_catalog.py index ad0e95d..916ab19 100644 --- a/mdhelper/style_catalog.py +++ b/mdhelper/style_catalog.py @@ -72,6 +72,13 @@ def parent_style(key, rules): return normalize_metadata(rules.get('_metadata')).get(key, {}).get('based_on', CATALOG[key].base) +def legacy_base(key, rules): + """Absent metadata keeps old cross-type bases; explicit detachment does not.""" + metadata = normalize_metadata(rules.get('_metadata')).get(key, {}) + if 'based_on' in metadata: return '' + return {'inline_code': 'code', 'table_head': 'table', 'table_cell': 'table'}.get(key, '') + + def explicit_rules(rules): """Resolve authored declarations only; absent character fields inherit their paragraph.""" rules = rules if isinstance(rules, dict) else {} @@ -85,10 +92,10 @@ def explicit_rules(rules): inherited = dict(resolve(base)) if base else {} if base and CATALOG[key].kind == 'character': inherited = {**CHARACTER_DEFAULTS.get(base, {}), **inherited} - if key in ('table_head', 'table_cell') and not base: + if key in ('table_head', 'table_cell') and not base and legacy_base(key, rules): legacy = rules.get('table') if isinstance(rules.get('table'), dict) else {} - inherited.update({k: v for k, v in legacy.items() if k not in {'border_color', 'border_width', 'cell_padding'}}) - if key == 'inline_code' and not base: + inherited.update({k: v for k, v in legacy.items() if k not in {'border_color', 'border_width', 'border_style', 'cell_padding'}}) + if key == 'inline_code' and not base and legacy_base(key, rules): legacy = rules.get('code') if isinstance(rules.get('code'), dict) else {} inherited.update({k: v for k, v in legacy.items() if k in CHARACTER_FIELDS}) inherited.update(own) @@ -116,6 +123,7 @@ def token_regions(tokens): if stack: stack.pop() continue contexts = [kind for kind, _ in stack] + if token.type == 'blockquote_open': used.add('blockquote') target = None if token.type == 'heading_open': target = token.tag elif token.type in ('fence', 'code_block'): target = 'code_block' diff --git a/mdhelper/style_dialog.py b/mdhelper/style_dialog.py index 4e56635..7fcb0b1 100644 --- a/mdhelper/style_dialog.py +++ b/mdhelper/style_dialog.py @@ -36,7 +36,7 @@ from .document_style import (STYLE_TARGETS, normalize_rule, resolved_rules, from .document_style import build_document_style_css from .style_sync import analyze_css, source_from_payload, patch_core, GROUPS -from .style_catalog import CATALOG, CHARACTER_FIELDS, KINDS, normalize_metadata, parent_style, style_name +from .style_catalog import CATALOG, CHARACTER_FIELDS, KINDS, normalize_metadata, parent_style, style_name, legacy_base class DocumentStyleEditorDialog(QDialog): @@ -214,10 +214,11 @@ class DocumentStyleEditorDialog(QDialog): self.border_color_edit.setPlaceholderText('继承 / #RRGGBB') self.border_width_spin = self._spin(20) self.border_width_spin.setSuffix(' 磅') + self.border_style_combo = self._combo([('继承',None),('无边框','none'),('隐藏','hidden'),('实线','solid'),('点线','dotted'),('虚线','dashed'),('双线','double'),('凹槽','groove'),('凸脊','ridge'),('内嵌','inset'),('外凸','outset')]) self.cell_padding_spin = self._spin(100) self.cell_padding_spin.setSuffix(' 磅') self.border_row = form.rowCount() - form.addRow('边框颜色 / 宽度', self._row(self.border_color_edit, self.border_width_spin)) + form.addRow('边框颜色 / 宽度 / 样式', self._row(self.border_color_edit, self.border_width_spin, self.border_style_combo)) self.padding_row = form.rowCount() form.addRow('内边距', self.cell_padding_spin) self.list_marker_box = self._combo([('继承', None), ('圆点', 'disc'), ('空心圆', 'circle'), ('方块', 'square'), @@ -363,14 +364,15 @@ class DocumentStyleEditorDialog(QDialog): def _store_metadata(self, *_): if self._loading: return key, base = self._current_target, self.based_on_box.currentData() or '' - ancestor, seen = base, set() + ancestor, seen = '' if base == '__legacy__' else base, set() while ancestor and ancestor not in seen: if ancestor == key: QMessageBox.warning(self, '无法继承', '样式基准不能形成循环。') self._load_rule_to_widgets(self.rules.get(key, {})); return seen.add(ancestor); ancestor = parent_style(ancestor, self.rules) metadata = deepcopy(self.rules.get('_metadata', {})) - metadata[key] = {'name': self.style_name_edit.text().strip() or CATALOG[key].name, 'based_on': base} + metadata[key] = {'name': self.style_name_edit.text().strip() or CATALOG[key].name} + if base != '__legacy__': metadata[key]['based_on'] = base self.rules['_metadata'] = normalize_metadata(metadata) self.target_list.currentItem().setText(style_name(key, self.rules)) self._refresh_preview() @@ -445,10 +447,12 @@ class DocumentStyleEditorDialog(QDialog): self.style_name_edit.setText(style_name(key, self.rules)) self.style_kind_label.setText(f'{KINDS[CATALOG[key].kind]} · {CATALOG[key].syntax}') self.based_on_box.clear(); self.based_on_box.addItem('文档默认 / 所在段落', '') + compatibility = {'inline_code':'code','table_head':'table','table_cell':'table'}.get(key) + if compatibility: self.based_on_box.addItem('兼容:' + style_name(compatibility, self.rules), '__legacy__') for candidate, definition in CATALOG.items(): if candidate != key and definition.kind == CATALOG[key].kind: self.based_on_box.addItem(style_name(candidate, self.rules), candidate) - self._select(self.based_on_box, parent_style(key, self.rules)) + self._select(self.based_on_box, '__legacy__' if legacy_base(key, self.rules) else parent_style(key, self.rules)) character = CATALOG[self._current_target].kind == 'character' for row in range(self.paragraph_row_start, self.paragraph_row_end): self.form.setRowVisible(row, not character) self.form.setRowVisible(self.border_row, self._current_target == 'table') @@ -458,6 +462,7 @@ class DocumentStyleEditorDialog(QDialog): self.background_edit.setText(rule.get('background_color', '')) self.border_color_edit.setText(rule.get('border_color', '')) self.border_width_spin.setValue(number(rule.get('border_width'), -1)) + self._select(self.border_style_combo, rule.get('border_style')) self.cell_padding_spin.setValue(number(rule.get('cell_padding'), -1)) self.level_indent_spin.setValue(number(rule.get('level_indent'), -1)) self._select(self.list_marker_box, rule.get('list_marker')) @@ -514,6 +519,7 @@ class DocumentStyleEditorDialog(QDialog): for key, widget in (('border_width', self.border_width_spin), ('cell_padding', self.cell_padding_spin), ('level_indent', self.level_indent_spin)): put(key, widget.value() if widget.value() >= 0 else None) put('list_marker', self.list_marker_box.currentData()) + put('border_style', self.border_style_combo.currentData()) color = self.color_combo.currentData() put("font_color", self.color_button.text() if color == "custom" else color) direction = self.character_spacing_combo.currentData() diff --git a/mdhelper/style_sync.py b/mdhelper/style_sync.py index ca1444f..f0f14f3 100644 --- a/mdhelper/style_sync.py +++ b/mdhelper/style_sync.py @@ -22,7 +22,7 @@ GROUPS = { "size": ("font_size", "font_size_unit"), "bold": ("bold",), "italic": ("italic",), "color": ("font_color",), "tracking": ("letter_spacing",), "align": ("alignment",), 'decoration': ('underline', 'strike'), 'background': ('background_color',), - 'border_color': ('border_color',), 'border_width': ('border_width',), 'padding': ('cell_padding',), + 'border_color': ('border_color',), 'border_width': ('border_width',), 'border_style': ('border_style',), 'padding': ('cell_padding',), 'marker': ('list_marker',), 'level_indent': ('level_indent',), "line": ("line_spacing_mode", "line_height_value"), "indent": ("indent_mode", "indent_value", "indent_unit"), **{side: (f"{side}_indent_value", f"{side}_indent_unit") for side in ("left", "right")}, @@ -34,7 +34,7 @@ PROPERTIES = { "size": {"font-size"}, "bold": {"font-weight"}, "italic": {"font-style"}, "color": {"color"}, "tracking": {"letter-spacing"}, "align": {"text-align"}, 'decoration': {'text-decoration', 'text-decoration-line', '--mdhelper-underline', '--mdhelper-strike'}, 'background': {'background-color'}, - 'border_color': {'border-color'}, 'border_width': {'border-width', 'border-style'}, 'padding': {'padding'}, + 'border_color': {'border-color'}, 'border_width': {'border-width'}, 'border_style': {'border-style'}, 'padding': {'padding'}, 'marker': {'list-style-type'}, 'level_indent': {'--mdhelper-list-level-indent'}, "line": {"line-height", "--mdhelper-line-spacing-mode"}, "indent": {"text-indent"}, **{side: {f"margin-{side}"} for side in ("left", "right")}, @@ -243,6 +243,19 @@ def _invalid_core_value(prop, tokens): """Reject definite invalid values; retain valid unsupported expressions.""" tokens = [t for t in tokens if t.type not in ('whitespace', 'comment')] if not tokens or any(t.type == 'error' for t in tokens): return True + if len(tokens)==1 and tokens[0].type=='ident' and tokens[0].lower_value in ('inherit','initial','unset','revert','revert-layer'): return False + # Variables may expand to otherwise valid token sequences, including empty + # fragments. Do not misclassify them as invalid syntax before substitution. + if any(t.type == 'function' and t.lower_name in ('var','env') for t in tokens): return False + scalar = {'font-size','line-height','letter-spacing','text-indent','font-weight','color','background-color','text-align', + 'margin-top','margin-bottom','margin-left','margin-right'} + if len(tokens) != 1 and prop in scalar: return True + lines = {'none','underline','overline','line-through','blink'} + if prop in ('text-decoration','text-decoration-line'): + names = [t.lower_value for t in tokens if t.type == 'ident'] + selected = [name for name in names if name in lines] + if 'none' in selected and len(selected)>1 or len(selected)!=len(set(selected)): return True + if prop == 'text-decoration-line': return any(t.type!='ident' or t.lower_value not in lines for t in tokens) if len(tokens) != 1: return False token = tokens[0] wide = {'inherit', 'initial', 'unset', 'revert', 'revert-layer'} @@ -253,6 +266,8 @@ def _invalid_core_value(prop, tokens): 'font-size': {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', 'xxx-large', 'larger', 'smaller', 'math'}, 'line-height': {'normal'}, 'letter-spacing': {'normal'}, 'border-width': {'thin', 'medium', 'thick'}, 'font-weight': {'normal', 'bold', 'bolder', 'lighter'}, 'font-style': {'normal', 'italic', 'oblique'}, + 'text-align': {'left','right','center','justify','start','end','match-parent','justify-all'}, + 'border-style': {'none','hidden','solid','dotted','dashed','double','groove','ridge','inset','outset'}, **{f'margin-{side}': {'auto'} for side in ('top', 'bottom', 'left', 'right')}, } if token.type == 'ident': @@ -267,6 +282,8 @@ def _invalid_core_value(prop, tokens): units.update(prefix + unit for prefix in ('s', 'l', 'd') for unit in ('vw', 'vh', 'vi', 'vb', 'vmin', 'vmax')) return token.lower_unit not in units if prop == 'font-weight' and token.type == 'number': return not 1 <= token.value <= 1000 + if prop == 'font-weight' and token.type in ('dimension','percentage'): return True + if prop in ('font-style','text-align','border-style') and token.type in ('dimension','percentage','number'): return True return False @@ -329,7 +346,7 @@ def _collect_cascade(source: str, result: Analysis): for selector, origin in aliases.items(): child = {'th': 'table_head', 'td': 'table_cell', 'code': 'code_block', 'pre': 'code_block'}.get(selector.removeprefix('.reader ')) if child and origin in ('table', 'code'): - if origin == 'table' and prop in PROPERTIES['border_color'] | PROPERTIES['border_width'] | PROPERTIES['padding']: continue + if origin == 'table' and prop in PROPERTIES['border_color'] | PROPERTIES['border_width'] | PROPERTIES['border_style'] | PROPERTIES['padding']: continue bindings.append((child, origin, 1, _specificity(selector))) character_props = set().union(*(PROPERTIES[g] for g in ('fonts','size','bold','italic','color','tracking','decoration'))) for target, origin, direct, specificity in bindings: @@ -365,6 +382,7 @@ class _CoreRuleReader: self.read(prop, lambda value, field=field: self.effect_color(value, field)) for prop, field in (('border-width', 'border_width'), ('padding', 'cell_padding'), ('--mdhelper-list-level-indent', 'level_indent')): self.read(prop, lambda value, field=field: self.effect_length(value, field)) + self.choice('border-style','border_style',{name:name for name in ('none','hidden','solid','dotted','dashed','double','groove','ridge','inset','outset')}) self.choice('list-style-type', 'list_marker', {x: x for x in ('none', 'disc', 'circle', 'square', 'decimal', 'lower-alpha', 'upper-alpha', 'lower-roman', 'upper-roman')}) self.read('line-height', self.line) for side, prefix in (('left', 'left_indent'), ('right', 'right_indent'), ('top', 'space_before'), ('bottom', 'space_after')): @@ -374,7 +392,7 @@ class _CoreRuleReader: self.choice('--mdhelper-contextual-spacing', 'contextual_spacing', {'true': True, 'false': False}) from .style_catalog import CATALOG, CHARACTER_FIELDS unsupported = set() - if self.target != 'table': unsupported.update(('border_color', 'border_width', 'cell_padding')) + if self.target != 'table': unsupported.update(('border_color', 'border_width', 'border_style', 'cell_padding')) if not self.target.startswith('list'): unsupported.update(('list_marker', 'level_indent')) if CATALOG[self.target].kind == 'character': unsupported.update(set(self.rule) - CHARACTER_FIELDS) for field in sorted(unsupported & self.rule.keys()): @@ -552,7 +570,9 @@ def patch_core(source: str, target: str, before: dict, after: dict, *, reset=Fal if not changed: return source affected = set().union(*(PROPERTIES[group] for group in changed)) - important = set() + winners = _collect_cascade(source, Analysis()).get(target, {}) + important = {group for group in changed for prop in PROPERTIES[group] + if prop in winners and winners[prop][0][1]} output = [] for node in css.parse_stylesheet(source, skip_whitespace=False, skip_comments=False): if node.type != "qualified-rule": @@ -599,6 +619,8 @@ def patch_core(source: str, target: str, before: dict, after: dict, *, reset=Fal node.content = css.parse_component_value_list(css.serialize(kept)) output.append(node) fragment = {key: value for group in changed for key in GROUPS[group] if (value := after.get(key)) is not None} + if 'border_width' in fragment and 'border_style' in after: + fragment['border_style'] = after['border_style'] declarations = _core_declarations(fragment) marked = [] for text in declarations: @@ -631,8 +653,11 @@ def render_css(source: str, rules: dict, font_family: str = '', font_size_px: fl from .document_style import resolved_rules effective = resolved_rules(rules, font_family, font_size_px, preset) for key, metadata in normalize_metadata(rules.get('_metadata')).items(): - if 'based_on' in metadata and CATALOG[key].kind != 'character': + detached_legacy = key in ('inline_code','table_head','table_cell') and metadata.get('based_on') == '' + if 'based_on' in metadata and (CATALOG[key].kind != 'character' or detached_legacy): inherited[key] = dict(effective[key]) + if detached_legacy: + inherited[key].update(underline=False, strike=False, background_color='transparent') if not metadata['based_on'] and CATALOG[key].base: legacy = rules.get(CATALOG[key].base, {}) defaults = {'underline': False, 'strike': False, 'background_color': 'transparent', @@ -641,7 +666,7 @@ def render_css(source: str, rules: dict, font_family: str = '', font_size_px: fl inherited[key].update({field: value for field, value in defaults.items() if field in legacy and field not in rules.get(key, {})}) inherited = {key: {field: value for field, value in rule.items() if field not in rules.get(key, {})} for key, rule in inherited.items()} contextual = {key: {"contextual_spacing": True} for key, rule in rules.items() if isinstance(rule, dict) and rule.get("contextual_spacing")} - helpers = build_document_style_css(contextual) + helpers = build_document_style_css(contextual, reset_list_paragraphs=False) # Emit the same font variables as the authored rules; a child's Chinese # font declaration must not shadow an inherited English font declaration. for key, rule in inherited.items(): @@ -671,7 +696,7 @@ def render_css(source: str, rules: dict, font_family: str = '', font_size_px: fl for key, rule in explicit_rules(rules).items(): materialized = {**inherited.get(key, {}), **rule} layout_helpers[key] = {field: materialized[field] for field in ('level_indent', 'contextual_spacing') if field in materialized} - helpers += '\n' + build_document_style_css(layout_helpers) + helpers += '\n' + build_document_style_css(layout_helpers, reset_list_paragraphs=False) # Independent flags retain their inherited counterpart. Literal CSS such as # text-decoration-line:none still wins over this opt-in variable expression. for key, rule in effective.items(): @@ -681,8 +706,12 @@ def render_css(source: str, rules: dict, font_family: str = '', font_size_px: fl paragraph = rules.get("paragraph", {}) if paragraph.get("font_size"): helpers += f"\n.reader {{ --reader-math-font-size: {fmt(paragraph['font_size'])}{paragraph.get('font_size_unit', 'px')}; }}" - if rules.get("list"): - helpers += "\n.reader li > p { margin: 0; text-indent: inherit; }" + paragraph_overrides = rules.get(LIST_PARAGRAPH, {}) + resets = [f'margin-{side}: 0;' for side, field in (('top','space_before_value'),('bottom','space_after_value'),('left','left_indent_value'),('right','right_indent_value')) if field not in paragraph_overrides] + if 'indent_mode' not in paragraph_overrides: resets.append('text-indent: inherit;') + for target in ('list','list_bullet','list_ordered','list_task'): + if rules.get(target) and resets: + helpers += '\n' + SELECTORS[target] + ' > p { ' + ' '.join(resets) + ' }' return (helpers.strip() + "\n\n" + source).strip() diff --git a/tests/test_style_revision_053.py b/tests/test_style_revision_053.py index 3b54595..addfe6f 100644 --- a/tests/test_style_revision_053.py +++ b/tests/test_style_revision_053.py @@ -3,6 +3,7 @@ import zipfile from lxml import etree as ET import pytest from mdhelper.style_sync import normalize_payload, analyze_css +from mdhelper.style_catalog import document_styles, explicit_rules from mdhelper.style_dialog import DocumentStyleEditorDialog from mdhelper.docx_exporter import export_markdown_to_docx from mdhelper.docx_style import W, NS @@ -15,6 +16,11 @@ TABLE_SOURCE = '| Header |\n|---|\n| Cell |' MIX_SOURCE = '**[LinkInner](https://example.com)** and [**BoldInner**](https://example.com)' MIX_RULES = {'strong': {'font_color': '#ff0000'}, 'link': {'font_color': '#ff0000'}} LIST_RULES = {'list_bullet': {'indent_mode': 'first', 'indent_value': 18, 'indent_unit': 'pt'}} +ALIGN_SOURCE = '| Left | Center | Right |\n|:---|:---:|---:|\n| A | B | C |' +QUOTE_SOURCE = '> - QuoteItem\n>\n> - QuoteSecond\n\n- Outside' +QUOTE_RULES = {'blockquote': {'font_color':'#ff0000','font_size':24,'font_size_unit':'pt'}} +LOOSE_CSS = 'li {font-size:12pt;} p {margin-top:24pt; text-indent:18pt;}' +BORDER_CSS = 'table,th,td {border-width:5pt;border-color:red;border-style:none;}' def test_legacy_css_keeps_separate_element_scopes_and_gui_edits(qt_application, tmp_path): @@ -81,3 +87,118 @@ def test_numbering_does_not_override_named_list_indents(tmp_path, engine, source assert num.find('.//w:pPr/w:ind',NS) is None identity=abstract.find(W+'nsid').get(W+'val') assert sum(n.find(W+'nsid') is not None and n.find(W+'nsid').get(W+'val')==identity for n in numbering.findall(W+'abstractNum'))==1 + + +@pytest.mark.parametrize('engine', ENGINES) +def test_legacy_bases_can_be_restored_or_explicitly_detached(qt_application, tmp_path, engine): + payload=normalize_payload({'rules':{'code':{'font_color':'#ff0000','font_size':20,'font_size_unit':'pt'},'table':{'font_color':'#ff0000'}}}) + dialog=DocumentStyleEditorDialog(payload) + try: + for target in ('inline_code','table_head','table_cell'): + dialog.select_target(target) + assert dialog.based_on_box.currentData()=='__legacy__' + dialog.style_name_edit.setText('Named '+target); dialog.style_name_edit.editingFinished.emit() + assert 'based_on' not in dialog.rules['_metadata'][target] + dialog.based_on_box.setCurrentIndex(dialog.based_on_box.findData('')) + payload=dialog.style_payload() + finally: dialog.close() + for target in ('inline_code','table_head','table_cell'): + assert 'font_color' not in explicit_rules(payload['rules'])[target] + source='`Inline`\n\n'+TABLE_SOURCE + assert all(color!='rgb(255, 0, 0)' for color in browser(qt_application,tmp_path,payload,source, + "[...document.querySelectorAll('code,th,td')].map(e=>getComputedStyle(e).color)")) + doc,styles=parts(export_markdown_to_docx(source,tmp_path/'detached.docx',engine=engine,style_rules=payload['rules'])) + for identifier in ('MDHelperInlineCode','MDHelperTableHead','MDHelperTableCell'): + assert styles.find(f"w:style[@w:styleId='{identifier}']/w:basedOn",NS) is None + + +@pytest.mark.parametrize('engine', ENGINES) +def test_table_column_alignment_is_a_shared_derived_style(tmp_path, engine): + doc,styles=parts(export_markdown_to_docx(ALIGN_SOURCE,tmp_path/'columns.docx',engine=engine)) + rendered=effective_document(doc,styles) + assert [p.find('w:pPr/w:jc',NS).get(W+'val') for p in rendered.iter(W+'p')]==['left','center','right']*2 + assert not doc.findall('.//w:pPr/w:jc',NS) + props=styles.find("w:style[@w:styleId='MDHelperTableCell']/w:rPr",NS) + color=props.find(W+'color') + if color is None: color=ET.SubElement(props,W+'color') + color.set(W+'val','ff0000') + for p in effective_document(doc,styles).iter(W+'p'): + if ''.join(p.itertext()) in ('A','B','C'): + assert p.find('.//w:rPr/w:color',NS).get(W+'val')=='ff0000' + + +@pytest.mark.parametrize('engine', ENGINES) +def test_quoted_loose_list_retains_quote_typography_and_style_inheritance(qt_application,tmp_path,engine): + payload=normalize_payload({'rules':QUOTE_RULES}) + assert {'blockquote','list_bullet'} <= document_styles(QUOTE_SOURCE)[1] + colors=browser(qt_application,tmp_path,payload,QUOTE_SOURCE,"[...document.querySelectorAll('blockquote p')].map(e=>getComputedStyle(e).color)") + assert colors==['rgb(255, 0, 0)']*2 + doc,styles=parts(export_markdown_to_docx(QUOTE_SOURCE,tmp_path/'quote.docx',engine=engine,style_rules=payload['rules'])) + for p in effective_document(doc,styles).iter(W+'p'): + if ''.join(p.itertext()).startswith('Quote'): + assert p.find('.//w:rPr/w:color',NS).get(W+'val')=='ff0000' + assert p.find('.//w:rPr/w:sz',NS).get(W+'val')=='48' + styles.find("w:style[@w:styleId='MDHelperBlockquote']/w:rPr/w:color",NS).set(W+'val','0000ff') + for p in effective_document(doc,styles).iter(W+'p'): + if ''.join(p.itertext()).startswith('Quote'): + assert p.find('.//w:rPr/w:color',NS).get(W+'val')=='0000ff' + assert not any('MDHelperSource' in s.get(W+'styleId','') for s in styles) + + +@pytest.mark.parametrize('engine', ENGINES) +def test_nested_quoted_lists_keep_depth_numbering_and_emphasis(tmp_path,engine): + source='> 3. **OuterQuote**\n>\n> - **NestedQuote**\n>\n> - NestedSecond\n>\n> 4. OuterSecond' + doc,styles=parts(export_markdown_to_docx(source,tmp_path/'nested-quote.docx',engine=engine,style_rules=QUOTE_RULES)) + values={} + for p in effective_document(doc,styles).iter(W+'p'): + text=''.join(p.itertext()); props=p.find(W+'pPr') + values[text]=props.find(W+'ind').get(W+'leftChars') + assert props.find(W+'numPr') is not None + if text in ('OuterQuote','NestedQuote'): + run=next(r for r in p.iter(W+'r') if ''.join(r.itertext())==text) + assert run.find('w:rPr/w:b',NS).get(W+'val')=='1' + assert run.find('w:rPr/w:color',NS).get(W+'val')=='ff0000' + assert int(values['NestedQuote'])>int(values['OuterQuote']) + + +def test_graphical_quote_edit_overrides_important_broad_p(qt_application,tmp_path): + dialog=DocumentStyleEditorDialog({'css':'p {color:red !important;}'}) + try: + dialog.select_target('blockquote'); dialog.color_button.setText('#008800'); dialog._store_and_refresh() + payload=dialog.style_payload() + assert payload['rules']['blockquote']['font_color']=='#008800' + assert payload['rules']['paragraph']['font_color']=='#ff0000' + assert browser(qt_application,tmp_path,payload,'> Quote',"getComputedStyle(document.querySelector('blockquote p')).color")=='rgb(0, 136, 0)' + finally:dialog.close() + + +def test_list_helpers_do_not_erase_explicit_p_spacing(qt_application,tmp_path): + payload=normalize_payload({'css':LOOSE_CSS}) + assert browser(qt_application,tmp_path,payload,'- First\n\n- Second', + "[...document.querySelectorAll('li > p')].map(e=>[parseFloat(getComputedStyle(e).marginTop),parseFloat(getComputedStyle(e).textIndent)])")==[[32,24],[32,24]] + + +@pytest.mark.parametrize('invalid',['font-size:10pt 20pt','color:red blue','font-weight:12pt','text-align:nope','text-decoration-line:none underline']) +def test_invalid_extended_values_preserve_previous_valid_declaration(qt_application,tmp_path,invalid): + css='p {font-size:20pt;color:green;font-weight:bold;text-align:center;text-decoration-line:line-through;'+invalid+';}' + payload=normalize_payload({'css':css}); rule=payload['rules']['paragraph'] + assert rule['font_size']==20 and rule['font_color']=='#008000' and rule['bold'] and rule['alignment']=='center' + assert rule['strike'] and not rule['underline'] + assert analyze_css(css).notes + assert browser(qt_application,tmp_path,payload,'Valid',"getComputedStyle(document.querySelector('p')).textDecorationLine")=='line-through' + + +@pytest.mark.parametrize('engine', ENGINES) +def test_border_style_sync_and_word_export(qt_application,tmp_path,engine): + dialog=DocumentStyleEditorDialog({'css':BORDER_CSS}) + try: + dialog.select_target('table'); assert dialog.border_style_combo.currentData()=='none' + dialog.border_width_spin.setValue(3) + payload=dialog.style_payload() + assert payload['rules']['table']['border_style']=='none' + assert browser(qt_application,tmp_path,payload,TABLE_SOURCE,"getComputedStyle(document.querySelector('td')).borderTopStyle")=='none' + _,styles=parts(export_markdown_to_docx(TABLE_SOURCE,tmp_path/'border.docx',engine=engine,style_rules=payload['rules'])) + assert all(b.get(W+'val')=='none' for b in styles.findall("w:style[@w:styleId='MDHelperTable']/w:tblPr/w:tblBorders/*",NS)) + dialog.border_style_combo.setCurrentIndex(dialog.border_style_combo.findData('dashed')) + assert dialog.style_payload()['rules']['table']['border_style']=='dashed' + finally:dialog.close() diff --git a/tests/word_styles_smoke.ps1 b/tests/word_styles_smoke.ps1 index 6b464bd..dc51b6c 100644 --- a/tests/word_styles_smoke.ps1 +++ b/tests/word_styles_smoke.ps1 @@ -13,13 +13,17 @@ from mdhelper.docx_exporter import export_markdown_to_docx from mdhelper.style_catalog import style_name from test_style_regressions import PARTIAL_RULES, UNIT_RULES, NESTED_SOURCE, NESTED_RULES from test_style_revision_052 import REPEATED_SOURCE, REPEATED_RULES, ABSOLUTE_PAYLOAD, SCOPED_SOURCE, SCOPED_CSS -from test_style_revision_053 import MIX_SOURCE, MIX_RULES, LIST_RULES +from test_style_revision_053 import MIX_SOURCE, MIX_RULES, LIST_RULES, ALIGN_SOURCE, QUOTE_SOURCE, QUOTE_RULES, LOOSE_CSS, BORDER_CSS, TABLE_SOURCE from mdhelper.style_sync import normalize_payload folder = Path(tempfile.mkdtemp(prefix='MDHelper-Word-Styles-')) rules = {'h2': {'bold': False}, '_metadata': {'h2': {'based_on': 'h1'}}} for engine in ('builtin', 'python-docx', 'pandoc'): export_markdown_to_docx(MIX_SOURCE, folder / (engine + '-equal-mix.docx'), engine=engine, style_rules=MIX_RULES) export_markdown_to_docx('- FirstItem\n\n- SecondItem', folder / (engine + '-list-first.docx'), engine=engine, style_rules=LIST_RULES) + export_markdown_to_docx(ALIGN_SOURCE, folder / (engine + '-columns.docx'), engine=engine) + export_markdown_to_docx(QUOTE_SOURCE, folder / (engine + '-quoted-list.docx'), engine=engine, style_rules=QUOTE_RULES) + export_markdown_to_docx('- SpacedItem\n\n- SecondItem', folder / (engine + '-loose-spacing.docx'), engine=engine, style_rules=normalize_payload({'css':LOOSE_CSS})['rules']) + export_markdown_to_docx(TABLE_SOURCE, folder / (engine + '-no-border.docx'), engine=engine, style_rules=normalize_payload({'css':BORDER_CSS})['rules']) export_markdown_to_docx(SOURCE + '\n\n## Child title', folder / (engine + '.docx'), engine=engine, style_rules=rules) export_markdown_to_docx('# Parent\n\n## Child', folder / (engine + '-partial.docx'), engine=engine, style_rules=PARTIAL_RULES) export_markdown_to_docx('# Parent\n\n## ChildUnits', folder / (engine + '-units.docx'), engine=engine, style_rules=UNIT_RULES) @@ -33,7 +37,7 @@ for engine in ('builtin', 'python-docx', 'pandoc'): style_rules=normalize_payload({'css': 'p {color:red;} strong,a {color:currentColor;}'})['rules']) export_markdown_to_docx('ValidValue', folder / (engine + '-fallback.docx'), engine=engine, style_rules=normalize_payload({'css': 'p {font-size:20pt;font-size:nope;color:red;color:invalid;}'})['rules']) -(folder / 'names.json').write_text(json.dumps({key: 'MDHelper ' + style_name(key) for key in ('paragraph', 'strong', 'link', 'h1')}), encoding='utf-8') +(folder / 'names.json').write_text(json.dumps({key: 'MDHelper ' + style_name(key) for key in ('paragraph', 'strong', 'link', 'h1', 'blockquote', 'table_cell')}), encoding='utf-8') print(folder) '@ | & $Python -B -).Trim() if ($LASTEXITCODE -ne 0) { throw 'Fixture generation failed.' } @@ -59,6 +63,32 @@ print(folder) if ($range.ParagraphFormat.FirstLineIndent -ne 24) { throw "$engine numbering blocks Word style edits." } } finally { $doc.Close(0); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc) } Write-Output "$engine passed: explicit equal-value overrides and list indentation style edits." + foreach ($case in @('columns','quoted-list','loose-spacing','no-border')) { + $doc = $word.Documents.Open((Join-Path $testDirectory "$engine-$case.docx"), $false, $true) + try { + if ($case -eq 'columns') { + foreach ($text in @('Center','Right')) { + $range=$doc.Content.Duplicate; [void]$range.Find.Execute($text) + $expected=if($text -eq 'Center'){1}else{2} + if($range.ParagraphFormat.Alignment -ne $expected){throw "$engine lost Markdown column alignment."} + } + $range=$doc.Tables.Item(1).Cell(2,3).Range + $doc.Styles.Item($names.table_cell).Font.Color=255 + if($range.Font.Color -ne 255){throw "$engine column style blocks cell-font inheritance."} + } elseif ($case -eq 'quoted-list') { + $range=$doc.Content.Duplicate; [void]$range.Find.Execute('QuoteItem') + if($range.Font.Color -ne 255 -or $range.Font.Size -ne 24){throw "$engine lost quote formatting inside list."} + $base=$doc.Styles.Item($names.blockquote); $base.Font.Color=16711680; $base.Font.Size=32 + if($range.Font.Color -ne 16711680 -or $range.Font.Size -ne 32){throw "$engine quoted list blocks quote-style inheritance."} + } elseif ($case -eq 'loose-spacing') { + $range=$doc.Content.Duplicate; [void]$range.Find.Execute('SpacedItem') + if($range.ParagraphFormat.SpaceBefore -ne 24 -or $range.ParagraphFormat.FirstLineIndent -ne 18){throw "$engine lost loose-list paragraph spacing."} + } else { + if($doc.Tables.Item(1).Borders.Item(-1).LineStyle -ne 0){throw "$engine ignores border-style:none."} + } + } finally { $doc.Close(0); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc) } + } + Write-Output "$engine passed: table alignment inheritance, quoted lists, loose spacing and disabled borders." $doc = $word.Documents.Open((Join-Path $testDirectory "$engine.docx"), $false, $true) try { $range = $doc.Content.Duplicate