diff --git a/docs/user_manual.md b/docs/user_manual.md index 90878da..3e4fdce 100644 --- a/docs/user_manual.md +++ b/docs/user_manual.md @@ -167,7 +167,9 @@ Markdown 支持: ### 样式面板与 Word 导出 -打开“样式 → 样式面板”,可查看全部样式或当前文档已用样式。编辑 Markdown 时,面板提示光标所在段落及其中包含的字符样式。双击条目修改样式名称、同类型基准及格式;改变样式不会改写 Markdown 内容。基于内置样式修改时自动创建自定义样式集。 +打开“样式 → 样式面板”,可查看全部样式或当前文档已用样式。编辑 Markdown 时,面板提示光标所在段落及其中包含的字符样式。双击条目修改样式名称、同类型基准及格式;改变样式不会改写 Markdown 内容。基于内置样式修改时自动创建自定义样式集,并保留原内置样式的字体、行距等基础信息,导出 Word 和迁移样式文件后继续生效。 + +首行和悬挂缩进可选择字符、磅或像素;高级 CSS 中的绝对缩进保留原单位,不会因继承字号而改变。图形设置只写回实际改动的字段,未改动的高级 CSS 数值即使超出控件范围也会保留。 样式集是一整套格式方案,正文、标题和链接等是其中的单个样式。启用项目默认后,修改作用于当前项目;否则修改全局默认。原有样式文件、配置导入导出和项目模板继续可用。面板和实际阅读预览按需创建,不增加启动阶段的窗口或浏览器切换。 diff --git a/mdhelper/document_style.py b/mdhelper/document_style.py index 8841a40..76f3bfa 100644 --- a/mdhelper/document_style.py +++ b/mdhelper/document_style.py @@ -96,6 +96,7 @@ def resolved_rules(rules: dict | None, font_family: str = "", font_size_px: floa """Reader defaults, not Word's theme-dependent defaults.""" from .style_catalog import explicit_rules, parent_style, CATALOG authored = rules if isinstance(rules, dict) else {} + preset = authored.get('_preset', preset) rules = explicit_rules(authored) base = dict(chinese_font_family=font_family or "Microsoft YaHei UI", english_font_family=font_family or "Microsoft YaHei UI", font_size=font_size_px, font_size_unit="px", bold=False, italic=False, @@ -202,7 +203,7 @@ def css_declarations(value: dict) -> list[str]: out.append(f"margin-{side}: {css_length(r[side + '_indent_value'], r.get(side + '_indent_unit', 'em'))};") mode, indent = r.get("indent_mode"), number(r.get("indent_value")) if mode in {"none", "first", "hanging"}: - out.append(f"text-indent: {fmt(-indent if mode == 'hanging' else indent if mode == 'first' else 0)}em;") + out.append(f"text-indent: {css_length(-indent if mode == 'hanging' else indent if mode == 'first' else 0, r.get('indent_unit', 'em'))};") out.append("padding-left: 0em;") for field, side in (("space_before", "top"), ("space_after", "bottom")): if field + "_value" in r: diff --git a/mdhelper/docx_exporter.py b/mdhelper/docx_exporter.py index cfff1c8..26b76e0 100644 --- a/mdhelper/docx_exporter.py +++ b/mdhelper/docx_exporter.py @@ -430,7 +430,7 @@ def _inline_runs(children: list[Token] | None) -> list[tuple[str, dict[str, obje style = {key: True for key in style_stack} if child.type == 'code_inline': style['code'] = True keys = {'bold': 'strong', 'italic': 'emphasis', 'strike': 'strike', 'link': 'link'} - style['semantic_order'] = tuple(dict.fromkeys([keys[key] for key in style_stack] + (['inline_code'] if style.get('code') else []))) + style['semantic_order'] = tuple([keys[key] for key in style_stack] + (['inline_code'] if style.get('code') else [])) if links: style['href'] = links[-1] runs.append((text, style)) elif child.type in {"softbreak", "hardbreak"}: diff --git a/mdhelper/docx_inline.py b/mdhelper/docx_inline.py index 0118a66..86a47a0 100644 --- a/mdhelper/docx_inline.py +++ b/mdhelper/docx_inline.py @@ -3,8 +3,13 @@ PREFIX = 'MDHelperSource_' CODES = {'strong': 'B', 'emphasis': 'I', 'strike': 'S', 'link': 'L', 'inline_code': 'C'} +def ordered_styles(order): + """Each semantic type takes precedence at its innermost occurrence.""" + return tuple(reversed(dict.fromkeys(reversed(tuple(order))))) + + def source_style_name(order): - keys = tuple(dict.fromkeys(key for key in order if key in CODES)) + keys = ordered_styles(key for key in order if key in CODES) return PREFIX + '_'.join(CODES[key] for key in keys) if keys else '' diff --git a/mdhelper/docx_semantic.py b/mdhelper/docx_semantic.py index 7862568..f112405 100644 --- a/mdhelper/docx_semantic.py +++ b/mdhelper/docx_semantic.py @@ -13,7 +13,7 @@ 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 .docx_style import W, NS, child, val, properties, _run_properties, _paragraph_properties, _order_properties -from .docx_inline import source_style_order +from .docx_inline import source_style_order, ordered_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() @@ -40,7 +40,7 @@ def _delta(current, base, authored=None): fields = {'rFonts': ('english_font_family', 'chinese_font_family'), 'sz': ('font_size',), 'szCs': ('font_size',), 'b': ('bold',), 'bCs': ('bold',), 'i': ('italic',), 'iCs': ('italic',), 'strike': ('strike',), 'u': ('underline',), 'shd': ('background_color',), 'color': ('font_color',), 'jc': ('alignment',), - 'ind': ('indent_mode', 'indent_value', 'left_indent_value', 'right_indent_value'), + 'ind': ('indent_mode', 'indent_value', 'indent_unit', 'left_indent_value', 'right_indent_value'), 'spacing': ('letter_spacing', 'space_before_value', 'space_after_value', 'line_height_value'), 'keepNext': ('keep_with_next',), 'keepLines': ('keep_lines_together',), 'pageBreakBefore': ('page_break_before',), 'widowControl': ('widow_control',), 'contextualSpacing': ('contextual_spacing',)} @@ -54,7 +54,7 @@ def _delta(current, base, authored=None): 'line': ('line_height_value', 'line_spacing_mode'), 'lineRule': ('line_height_value', 'line_spacing_mode')}, 'ind': {**{attr: (f'{side}_indent_value', f'{side}_indent_unit') for side in ('left', 'right') for attr in (side, side + 'Chars')}, - **{attr: ('indent_mode', 'indent_value') for attr in ('firstLine', 'firstLineChars', 'hanging', 'hangingChars')}}, + **{attr: ('indent_mode', 'indent_value', 'indent_unit') for attr in ('firstLine', 'firstLineChars', 'hanging', 'hangingChars')}}, }.get(ET.QName(node).localname) if old is not None and compound and not (node.tag == W + 'spacing' and current.tag == W + 'rPr'): # These properties merge attribute by attribute in Word. @@ -159,7 +159,7 @@ class WordStyles: return identifier def combined_character(self, keys, paragraph_target): - keys = tuple(dict.fromkeys(keys)) + keys = ordered_styles(keys) if not keys: return '' merged = dict(self.character_rule(keys[0])) for key in keys[1:]: merged.update(self.character_rule(key)) @@ -242,7 +242,10 @@ class WordStyles: rule['left_indent_unit'] = 'pt' temp = ET.Element(W + 'pPr') _paragraph_properties(temp, rule) - child(style, 'pPr').append(temp.find(W + 'ind')) + ind = temp.find(W + 'ind') + for attr in list(ind.attrib): + if attr not in (W + 'left', W + 'leftChars'): del ind.attrib[attr] + child(style, 'pPr').append(ind) return identifier def apply_list_marker(self, numpr, target, marker): diff --git a/mdhelper/docx_style.py b/mdhelper/docx_style.py index f6b3baa..efbc14d 100644 --- a/mdhelper/docx_style.py +++ b/mdhelper/docx_style.py @@ -105,8 +105,9 @@ def _paragraph_properties(ppr, rule): ind.set(W + side + 'Chars', '0') kind = "hanging" if rule["indent_mode"] == "hanging" else "firstLine" amount = number(rule["indent_value"]) if rule["indent_mode"] != "none" else 0 - ind.set(W + kind, str(round(amount * points * 20))) - ind.set(W + kind + "Chars", str(round(amount * 100))) + unit = rule.get('indent_unit', 'em') + ind.set(W + kind, str(round(length_points(amount, unit, points) * 20))) + ind.set(W + kind + "Chars", str(round(amount * 100)) if unit == 'em' else '0') # Override paragraph style inheritance, including Word's default grid snapping. val(ppr, "snapToGrid", 0) if 'background_color' in rule: diff --git a/mdhelper/main_window.py b/mdhelper/main_window.py index 951c5b6..7d0a49a 100644 --- a/mdhelper/main_window.py +++ b/mdhelper/main_window.py @@ -3263,6 +3263,9 @@ class MainWindow(QMainWindow): payload["css"] = str(style.get("css") or "") if "extra_css" in style: payload["extra_css"] = str(style.get("extra_css") or "") + if style_id in DOCUMENT_STYLE_PRESETS: + payload['rules'] = {'_preset': style_id} + payload['css_sync_version'] = 1 return payload def _write_document_style_file(self, output_path: Path, style_id: str) -> None: diff --git a/mdhelper/resources/reader.css b/mdhelper/resources/reader.css index ffdf9e7..f03fcd6 100644 --- a/mdhelper/resources/reader.css +++ b/mdhelper/resources/reader.css @@ -16,7 +16,7 @@ body { line-height: 1.72; } -html[data-theme="dark"] body { +:where(html[data-theme="dark"]) body { --reader-text-color: #e4e8ef; background: #17191f; color: #e4e8ef; @@ -31,7 +31,7 @@ html[data-theme="dark"] body { background: #ffffff; } -html[data-theme="dark"] .reader { +:where(html[data-theme="dark"]) .reader { background: #20242c; } .reader-shell { @@ -49,10 +49,10 @@ h4 { margin: 1.35em 0 0.55em; } -html[data-theme="dark"] h1, -html[data-theme="dark"] h2, -html[data-theme="dark"] h3, -html[data-theme="dark"] h4 { +:where(html[data-theme="dark"]) h1, +:where(html[data-theme="dark"]) h2, +:where(html[data-theme="dark"]) h3, +:where(html[data-theme="dark"]) h4 { color: #f4f7fb; } @@ -84,7 +84,7 @@ a:hover { text-decoration: underline; } -html[data-theme="dark"] a { +:where(html[data-theme="dark"]) a { color: #79b8ff; } @@ -96,7 +96,7 @@ blockquote { color: #344258; } -html[data-theme="dark"] blockquote { +:where(html[data-theme="dark"]) blockquote { background: #26313f; color: #d6deeb; } @@ -148,37 +148,37 @@ html[data-theme="dark"] blockquote { background: #f8f4ff; } -html[data-theme="dark"] .admonition { +:where(html[data-theme="dark"]) .admonition { border-color: #344e68; border-left-color: #5aa5e8; background: #1e2b38; color: #dce8f4; } -html[data-theme="dark"] .admonition-title { +:where(html[data-theme="dark"]) .admonition-title { color: #f0f7ff; } -html[data-theme="dark"] .admonition-tip { +:where(html[data-theme="dark"]) .admonition-tip { border-color: #294f39; border-left-color: #54c07d; background: #1d3026; } -html[data-theme="dark"] .admonition-note { +:where(html[data-theme="dark"]) .admonition-note { border-color: #344e68; border-left-color: #5aa5e8; background: #1e2b38; } -html[data-theme="dark"] .admonition-warning, -html[data-theme="dark"] .admonition-caution { +:where(html[data-theme="dark"]) .admonition-warning, +:where(html[data-theme="dark"]) .admonition-caution { border-color: #584725; border-left-color: #f0b849; background: #332b1b; } -html[data-theme="dark"] .admonition-important { +:where(html[data-theme="dark"]) .admonition-important { border-color: #4a3b66; border-left-color: #ad8cff; background: #2c253b; @@ -267,23 +267,23 @@ table { background: #f0f4f8; } -html[data-theme="dark"] .table-wrapper { +:where(html[data-theme="dark"]) .table-wrapper { border-color: #3a4352; background: #20242c; } -html[data-theme="dark"] .table-tools { +:where(html[data-theme="dark"]) .table-tools { border-bottom-color: #3a4352; background: #242b36; } -html[data-theme="dark"] .copy-table-button { +:where(html[data-theme="dark"]) .copy-table-button { border-color: #445063; background: #2d3542; color: #edf2f7; } -html[data-theme="dark"] .copy-table-button:hover { +:where(html[data-theme="dark"]) .copy-table-button:hover { background: #364151; } @@ -300,12 +300,12 @@ th { text-align: left; } -html[data-theme="dark"] th, -html[data-theme="dark"] td { +:where(html[data-theme="dark"]) th, +:where(html[data-theme="dark"]) td { border-color: #3a4352; } -html[data-theme="dark"] th { +:where(html[data-theme="dark"]) th { background: #2b3340; } @@ -322,9 +322,9 @@ td code { color: #9b2c2c; } -html[data-theme="dark"] p code, -html[data-theme="dark"] li code, -html[data-theme="dark"] td code { +:where(html[data-theme="dark"]) p code, +:where(html[data-theme="dark"]) li code, +:where(html[data-theme="dark"]) td code { background: #303745; color: #f2b8b5; } @@ -340,7 +340,7 @@ html[data-theme="dark"] td code { background: #ffffff; } -html[data-theme="dark"] .code-block { +:where(html[data-theme="dark"]) .code-block { border-color: #3c3c3c; background: #1e1e1e; } @@ -354,7 +354,7 @@ html[data-theme="dark"] .code-block { font-weight: 650; } -html[data-theme="dark"] .code-title { +:where(html[data-theme="dark"]) .code-title { border-bottom-color: #3c3c3c; background: #252526; color: #cccccc; @@ -368,7 +368,7 @@ pre.highlight { color: #000000; } -html[data-theme="dark"] pre.highlight { +:where(html[data-theme="dark"]) pre.highlight { background: #1e1e1e; color: #d4d4d4; } @@ -462,84 +462,84 @@ pre.highlight code { color: #a31515; } -html[data-theme="dark"] .highlight .c, -html[data-theme="dark"] .highlight .cm, -html[data-theme="dark"] .highlight .c1, -html[data-theme="dark"] .highlight .cs { +:where(html[data-theme="dark"]) .highlight .c, +:where(html[data-theme="dark"]) .highlight .cm, +:where(html[data-theme="dark"]) .highlight .c1, +:where(html[data-theme="dark"]) .highlight .cs { color: #6a9955; } -html[data-theme="dark"] .highlight .k, -html[data-theme="dark"] .highlight .kc, -html[data-theme="dark"] .highlight .kd, -html[data-theme="dark"] .highlight .kn, -html[data-theme="dark"] .highlight .kp, -html[data-theme="dark"] .highlight .kr, -html[data-theme="dark"] .highlight .ow { +:where(html[data-theme="dark"]) .highlight .k, +:where(html[data-theme="dark"]) .highlight .kc, +:where(html[data-theme="dark"]) .highlight .kd, +:where(html[data-theme="dark"]) .highlight .kn, +:where(html[data-theme="dark"]) .highlight .kp, +:where(html[data-theme="dark"]) .highlight .kr, +:where(html[data-theme="dark"]) .highlight .ow { color: #569cd6; } -html[data-theme="dark"] .highlight .kt, -html[data-theme="dark"] .highlight .nc, -html[data-theme="dark"] .highlight .nn { +:where(html[data-theme="dark"]) .highlight .kt, +:where(html[data-theme="dark"]) .highlight .nc, +:where(html[data-theme="dark"]) .highlight .nn { color: #4ec9b0; } -html[data-theme="dark"] .highlight .s, -html[data-theme="dark"] .highlight .sa, -html[data-theme="dark"] .highlight .sb, -html[data-theme="dark"] .highlight .sc, -html[data-theme="dark"] .highlight .dl, -html[data-theme="dark"] .highlight .sd, -html[data-theme="dark"] .highlight .s1, -html[data-theme="dark"] .highlight .s2, -html[data-theme="dark"] .highlight .se, -html[data-theme="dark"] .highlight .sh, -html[data-theme="dark"] .highlight .si, -html[data-theme="dark"] .highlight .sx, -html[data-theme="dark"] .highlight .sr, -html[data-theme="dark"] .highlight .ss { +:where(html[data-theme="dark"]) .highlight .s, +:where(html[data-theme="dark"]) .highlight .sa, +:where(html[data-theme="dark"]) .highlight .sb, +:where(html[data-theme="dark"]) .highlight .sc, +:where(html[data-theme="dark"]) .highlight .dl, +:where(html[data-theme="dark"]) .highlight .sd, +:where(html[data-theme="dark"]) .highlight .s1, +:where(html[data-theme="dark"]) .highlight .s2, +:where(html[data-theme="dark"]) .highlight .se, +:where(html[data-theme="dark"]) .highlight .sh, +:where(html[data-theme="dark"]) .highlight .si, +:where(html[data-theme="dark"]) .highlight .sx, +:where(html[data-theme="dark"]) .highlight .sr, +:where(html[data-theme="dark"]) .highlight .ss { color: #ce9178; } -html[data-theme="dark"] .highlight .m, -html[data-theme="dark"] .highlight .mb, -html[data-theme="dark"] .highlight .mf, -html[data-theme="dark"] .highlight .mh, -html[data-theme="dark"] .highlight .mi, -html[data-theme="dark"] .highlight .mo, -html[data-theme="dark"] .highlight .il { +:where(html[data-theme="dark"]) .highlight .m, +:where(html[data-theme="dark"]) .highlight .mb, +:where(html[data-theme="dark"]) .highlight .mf, +:where(html[data-theme="dark"]) .highlight .mh, +:where(html[data-theme="dark"]) .highlight .mi, +:where(html[data-theme="dark"]) .highlight .mo, +:where(html[data-theme="dark"]) .highlight .il { color: #b5cea8; } -html[data-theme="dark"] .highlight .nf, -html[data-theme="dark"] .highlight .fm, -html[data-theme="dark"] .highlight .nb, -html[data-theme="dark"] .highlight .bp { +:where(html[data-theme="dark"]) .highlight .nf, +:where(html[data-theme="dark"]) .highlight .fm, +:where(html[data-theme="dark"]) .highlight .nb, +:where(html[data-theme="dark"]) .highlight .bp { color: #dcdcaa; } -html[data-theme="dark"] .highlight .na, -html[data-theme="dark"] .highlight .nv, -html[data-theme="dark"] .highlight .vc, -html[data-theme="dark"] .highlight .vg, -html[data-theme="dark"] .highlight .vi, -html[data-theme="dark"] .highlight .vm { +:where(html[data-theme="dark"]) .highlight .na, +:where(html[data-theme="dark"]) .highlight .nv, +:where(html[data-theme="dark"]) .highlight .vc, +:where(html[data-theme="dark"]) .highlight .vg, +:where(html[data-theme="dark"]) .highlight .vi, +:where(html[data-theme="dark"]) .highlight .vm { color: #9cdcfe; } -html[data-theme="dark"] .highlight .nd, -html[data-theme="dark"] .highlight .ne, -html[data-theme="dark"] .highlight .nl { +:where(html[data-theme="dark"]) .highlight .nd, +:where(html[data-theme="dark"]) .highlight .ne, +:where(html[data-theme="dark"]) .highlight .nl { color: #c586c0; } -html[data-theme="dark"] .highlight .o, -html[data-theme="dark"] .highlight .p { +:where(html[data-theme="dark"]) .highlight .o, +:where(html[data-theme="dark"]) .highlight .p { color: #d4d4d4; } -html[data-theme="dark"] .highlight .err { +:where(html[data-theme="dark"]) .highlight .err { color: #f48771; } @@ -564,7 +564,7 @@ html[data-theme="dark"] .highlight .err { user-select: none; } -html[data-theme="dark"] .code-line::before { +:where(html[data-theme="dark"]) .code-line::before { color: #858585; } @@ -584,7 +584,7 @@ html[data-theme="dark"] .code-line::before { background: linear-gradient(rgb(255 255 255 / 0), #ffffff); } -html[data-theme="dark"] .code-block.is-collapsible.is-collapsed::after { +:where(html[data-theme="dark"]) .code-block.is-collapsible.is-collapsed::after { background: linear-gradient(rgb(30 30 30 / 0), #1e1e1e); } @@ -598,7 +598,7 @@ html[data-theme="dark"] .code-block.is-collapsible.is-collapsed::after { white-space: pre-wrap; } -html[data-theme="dark"] .plain-file-view { +:where(html[data-theme="dark"]) .plain-file-view { border-color: #384252; background: #171b22; } @@ -614,8 +614,8 @@ html[data-theme="dark"] .plain-file-view { background: #f7f9fc; } -html[data-theme="dark"] .diagram-block, -html[data-theme="dark"] .math-block { +:where(html[data-theme="dark"]) .diagram-block, +:where(html[data-theme="dark"]) .math-block { border-color: #384252; background: #171b22; } @@ -629,7 +629,7 @@ html[data-theme="dark"] .math-block { font-weight: 650; } -html[data-theme="dark"] .diagram-title { +:where(html[data-theme="dark"]) .diagram-title { border-bottom-color: #384252; background: #242b36; color: #b7c0cc; @@ -670,8 +670,8 @@ html[data-theme="dark"] .diagram-title { font-weight: 650; } -html[data-theme="dark"] .diagram-missing-runtime::before, -html[data-theme="dark"] .diagram-render-error::before { +:where(html[data-theme="dark"]) .diagram-missing-runtime::before, +:where(html[data-theme="dark"]) .diagram-render-error::before { color: #f2b8b5; } @@ -706,13 +706,13 @@ html[data-theme="dark"] .diagram-render-error::before { background: #f0f4f8; } -html[data-theme="dark"] .toggle-code-button { +:where(html[data-theme="dark"]) .toggle-code-button { border-color: #445063; background: #2d3542; color: #edf2f7; } -html[data-theme="dark"] .toggle-code-button:hover { +:where(html[data-theme="dark"]) .toggle-code-button:hover { background: #364151; } @@ -720,13 +720,13 @@ html[data-theme="dark"] .toggle-code-button:hover { background: #f0f4f8; } -html[data-theme="dark"] .copy-code-button { +:where(html[data-theme="dark"]) .copy-code-button { border-color: #445063; background: #2d3542; color: #edf2f7; } -html[data-theme="dark"] .copy-code-button:hover { +:where(html[data-theme="dark"]) .copy-code-button:hover { background: #364151; } @@ -735,7 +735,7 @@ html[data-theme="dark"] .copy-code-button:hover { font-weight: 700; } -html[data-theme="dark"] .pseudo-keyword { +:where(html[data-theme="dark"]) .pseudo-keyword { color: #569cd6; } @@ -816,21 +816,21 @@ img { background: #dbe4ef; } -html[data-theme="dark"] .media-player-link__box { +:where(html[data-theme="dark"]) .media-player-link__box { border-color: #384252; background: #242b36; } -html[data-theme="dark"] .media-player-link__title { +:where(html[data-theme="dark"]) .media-player-link__title { color: #dce3ec; } -html[data-theme="dark"] .media-player-link__button--secondary { +:where(html[data-theme="dark"]) .media-player-link__button--secondary { background: #303948; color: #edf2f7; } -html[data-theme="dark"] .media-player-link__button--secondary:hover { +:where(html[data-theme="dark"]) .media-player-link__button--secondary:hover { background: #3a4658; } @@ -852,7 +852,7 @@ html[data-theme="dark"] .media-player-link__button--secondary:hover { font-weight: 650; } -html[data-theme="dark"] .media-fallback { +:where(html[data-theme="dark"]) .media-fallback { border-color: #384252; background: #242b36; color: #dce3ec; @@ -864,7 +864,7 @@ figcaption { font-size: 0.9em; } -html[data-theme="dark"] figcaption { +:where(html[data-theme="dark"]) figcaption { color: #a9b4c4; } @@ -874,7 +874,7 @@ hr { margin: 2em 0; } -html[data-theme="dark"] hr { +:where(html[data-theme="dark"]) hr { border-top-color: #384252; } diff --git a/mdhelper/resources/word_inline_styles.lua b/mdhelper/resources/word_inline_styles.lua index 42ebfba..d4ef9d7 100644 --- a/mdhelper/resources/word_inline_styles.lua +++ b/mdhelper/resources/word_inline_styles.lua @@ -3,12 +3,11 @@ local prefix = 'MDHelperSource_' local codes = {Strong='B', Emph='I', Strikeout='S', Link='L', Code='C'} local function push(stack, code) - local copy, found = {}, false + local copy = {} for _, value in ipairs(stack) do - copy[#copy + 1] = value - if value == code then found = true end + if value ~= code then copy[#copy + 1] = value end end - if not found then copy[#copy + 1] = code end + copy[#copy + 1] = code return copy end local function mark(items, stack) diff --git a/mdhelper/style_dialog.py b/mdhelper/style_dialog.py index b2adfec..89a074d 100644 --- a/mdhelper/style_dialog.py +++ b/mdhelper/style_dialog.py @@ -35,7 +35,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 +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 @@ -248,8 +248,8 @@ class DocumentStyleEditorDialog(QDialog): form.addRow(label, self._row(spin, unit)) self.indent_mode_combo = self._combo([("继承", None), ("无", "none"), ("首行缩进", "first"), ("悬挂缩进", "hanging")]) self.indent_spin = self._spin(100, False) - self.indent_spin.setSuffix(" 字符") - form.addRow("特殊缩进", self._row(self.indent_mode_combo, self.indent_spin)) + self.indent_unit_combo = self._combo([('字符', 'em'), ('磅', 'pt'), ('像素', 'px')]) + form.addRow("特殊缩进", self._row(self.indent_mode_combo, self.indent_spin, self.indent_unit_combo)) self.line_height_mode_combo = self._combo([("继承", None), ("单倍", "single"), ("1.5 倍", "one_half"), ("双倍", "double"), ("多倍", "multiple"), ("固定值(磅)", "exact"), ("最小值(磅)", "at_least")]) self.line_height_spin = self._spin(500, False) @@ -334,10 +334,9 @@ class DocumentStyleEditorDialog(QDialog): self.css_status_label.setText("尚未同步:" + ";".join(result.errors[:3])) return False self._css_dirty = False - metadata = self.rules.get('_metadata') + metadata = {key: deepcopy(self.rules[key]) for key in ('_metadata', '_preset') if key in self.rules} self.rules = result.rules - if metadata: - self.rules['_metadata'] = deepcopy(metadata) + self.rules.update(metadata) if update_widgets: self._load_rule_to_widgets(self.rules.get(self._current_target, {})) else: @@ -482,6 +481,7 @@ class DocumentStyleEditorDialog(QDialog): self._select(getattr(self, f"{side}_indent_unit_combo"), rule.get(f"{side}_indent_unit", "em")) self._select(self.indent_mode_combo, rule.get("indent_mode")) self.indent_spin.setValue(number(rule.get("indent_value"))) + self._select(self.indent_unit_combo, rule.get('indent_unit', 'em')) mode, value = rule.get("line_spacing_mode"), number(rule.get("line_height_value"), 1) if mode == "multiple": mode = {1: "single", 1.5: "one_half", 2: "double"}.get(value, "multiple") @@ -490,13 +490,12 @@ class DocumentStyleEditorDialog(QDialog): for side in ("before", "after"): getattr(self, f"space_{side}_spin").setValue(number(rule.get(f"space_{side}_value"), -1)) self._select(getattr(self, f"space_{side}_unit_combo"), rule.get(f"space_{side}_unit", "pt")) + self._loaded_widget_rule = self._read_widget_rule() self._loading = False self._refresh_preview() - def _store_current_rule(self) -> None: - if self._loading: - return - rule = normalize_rule(self.rules.get(self._current_target, {})) + def _read_widget_rule(self) -> dict: + rule = {} def put(key: str, value: object) -> None: if value is None: rule.pop(key, None) @@ -528,6 +527,7 @@ class DocumentStyleEditorDialog(QDialog): mode = self.indent_mode_combo.currentData() put("indent_mode", mode) put("indent_value", None if mode is None else 0 if mode == "none" else self.indent_spin.value()) + put('indent_unit', self.indent_unit_combo.currentData() if mode in ('first', 'hanging') and self.indent_unit_combo.currentData() != 'em' else None) mode = self.line_height_mode_combo.currentData() preset = {"single": 1, "one_half": 1.5, "double": 2} put("line_spacing_mode", "multiple" if mode in preset else mode) @@ -535,6 +535,22 @@ class DocumentStyleEditorDialog(QDialog): rule.pop("line_height_unit", None) if CATALOG[self._current_target].kind == 'character': rule = {key: value for key, value in rule.items() if key in CHARACTER_FIELDS} + return rule + + def _store_current_rule(self) -> None: + if self._loading: + return + rule = normalize_rule(self.rules.get(self._current_target, {})) + current = self._read_widget_rule() + previous = self._loaded_widget_rule + # A spin box can round or clamp imported CSS. Only changed controls + # may write back; changing italic must not rewrite an untouched length. + for keys in GROUPS.values(): + if any(current.get(key) != previous.get(key) for key in keys): + for key in keys: + if key in current: rule[key] = current[key] + else: rule.pop(key, None) + self._loaded_widget_rule = current if rule: self.rules[self._current_target] = rule else: @@ -579,7 +595,7 @@ class DocumentStyleEditorDialog(QDialog): scale = 96 / 72 for side, setter in (("left", block.setLeftMargin), ("right", block.setRightMargin)): setter(length_points(rule[f"{side}_indent_value"], rule[f"{side}_indent_unit"], points) * scale) - indent = number(rule["indent_value"]) * points * scale + indent = length_points(rule['indent_value'], rule.get('indent_unit', 'em'), points) * scale block.setTextIndent(indent if rule["indent_mode"] == "first" else -indent if rule["indent_mode"] == "hanging" else 0) mode = rule["line_spacing_mode"] block.setLineHeight(number(rule["line_height_value"]) * (100 if mode == "multiple" else scale), diff --git a/mdhelper/style_sync.py b/mdhelper/style_sync.py index 3eb9796..54e008d 100644 --- a/mdhelper/style_sync.py +++ b/mdhelper/style_sync.py @@ -24,7 +24,7 @@ GROUPS = { 'decoration': ('underline', 'strike'), 'background': ('background_color',), 'border_color': ('border_color',), 'border_width': ('border_width',), 'padding': ('cell_padding',), 'marker': ('list_marker',), 'level_indent': ('level_indent',), - "line": ("line_spacing_mode", "line_height_value"), "indent": ("indent_mode", "indent_value"), + "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")}, **{side: (f"space_{side}_value", f"space_{side}_unit") for side in ("before", "after")}, **{name: (name,) for name in ("contextual_spacing", "keep_with_next", "keep_lines_together", "page_break_before", "widow_control")}, @@ -398,12 +398,8 @@ class _CoreRuleReader: def indent(self, value): amount, unit = _length(value, ('em', 'pt', 'px'), negative=True) - if unit != 'em': - points = font_points({**resolved_rules({}, font_size_px=self.font_size_px)[self.target], **self.rule}) - amount = amount * (0.75 if unit == 'px' else 1) / points - if abs(amount) > 100: - raise ValueError self.rule.update(indent_mode='none' if not amount else 'first' if amount > 0 else 'hanging', indent_value=abs(amount)) + if amount and unit != 'em': self.rule['indent_unit'] = unit def margin(self, value, prefix): amount, unit = _length(value, ('em', 'pt', 'px', 'cm') if 'indent' in prefix else ('em', 'pt', 'px', 'lh', 'cm')) @@ -560,6 +556,20 @@ def render_css(source: str, rules: dict, font_family: str = '', font_size_px: fl for key, rule in inherited.items(): declarations = _core_declarations(rule) if declarations: helpers += '\n' + SELECTORS[key] + ' { ' + ' '.join(declarations) + ' }' + # The legacy code rule also selects the inner . Let the semantic + # block own its typography instead of leaving that old child rule in charge. + block = {**inherited.get('code_block', {}), **rules.get('code_block', {})} + block_properties = { + 'font-family': ('chinese_font_family', 'english_font_family'), 'font-size': ('font_size',), + 'font-weight': ('bold',), 'font-style': ('italic',), 'color': ('font_color',), + 'letter-spacing': ('letter_spacing',), 'text-decoration-line': ('underline', 'strike'), + } + propagated = [prop + ': inherit;' for prop, fields in block_properties.items() if any(field in block for field in fields)] + if 'background_color' in block: propagated.append('background-color: transparent;') + block_selector = SELECTORS['code_block'] + ' > code' + if propagated: helpers += '\n' + block_selector + ' { ' + ' '.join(propagated) + ' }' + token_properties = [prop + ': inherit;' for prop, field in (('color', 'font_color'), ('font-weight', 'bold'), ('font-style', 'italic')) if field in block] + if token_properties: helpers += '\n' + block_selector + ' span { ' + ' '.join(token_properties) + ' }' layout_helpers = {} for key, rule in explicit_rules(rules).items(): materialized = {**inherited.get(key, {}), **rule} @@ -587,6 +597,9 @@ def normalize_payload(payload: dict, fallback_name="自定义样式", font_size_ metadata = normalize_metadata(supplied_rules.get('_metadata')) if metadata: result.rules['_metadata'] = metadata + from .style_presets import DOCUMENT_STYLE_PRESETS + if supplied_rules.get('_preset') in DOCUMENT_STYLE_PRESETS: + result.rules['_preset'] = supplied_rules['_preset'] return {"name": str(payload.get("name") or fallback_name).strip() or fallback_name, "css_sync_version": 1, "css": source, "rules": result.rules if not result.errors else deepcopy(payload.get("rules") or {})} diff --git a/tests/test_style_revision_052.py b/tests/test_style_revision_052.py new file mode 100644 index 0000000..b33dd34 --- /dev/null +++ b/tests/test_style_revision_052.py @@ -0,0 +1,130 @@ +"""Cross-surface regressions found in the 0.5.1 style audit.""" +import json +from PySide6.QtCore import Qt, QSettings +import pytest +from mdhelper import main_window +from mdhelper.style_dialog import DocumentStyleEditorDialog +from mdhelper.style_sync import normalize_payload, analyze_css +from mdhelper.document_style import resolved_rules +from mdhelper.docx_exporter import export_markdown_to_docx +from mdhelper.docx_style import W, NS, child +from docx_assertions import effective_document +from test_style_regressions import browser, parts + +ENGINES = ['builtin', 'python-docx', 'pandoc'] +REPEATED_SOURCE = '**Outer *middle **Deep** middle* outer**' +REPEATED_RULES = {'strong': {'font_color': '#ff0000'}, 'emphasis': {'font_color': '#0000ff'}} +ABSOLUTE_PAYLOAD = {'css_sync_version': 1, + 'css': '.reader h1 {font-size:20pt;} .reader h2 {text-indent:24pt;}', + 'rules': {'_metadata': {'h2': {'based_on': 'h1'}}}} + + +def text_run(document, word): + return next(r for r in document.iter(W + 'r') if word in ''.join(r.itertext())) + + +def test_unrelated_controls_preserve_css_values_outside_ui_range(qt_application): + source = '.reader table, .reader th, .reader td {padding:150pt; border-width:30pt; letter-spacing:1.2345pt;}' + dialog = DocumentStyleEditorDialog({'css': source}) + try: + dialog.select_target('table') + dialog.bool_boxes['italic'].setCheckState(Qt.CheckState.Checked) + payload = dialog.style_payload() + assert payload['rules']['table'] == dict(italic=True, cell_padding=150, border_width=30, letter_spacing=1.2345) + assert 'padding:150pt' in payload['css'] and 'letter-spacing:1.2345pt' in payload['css'] + dialog.cell_padding_spin.setValue(80) + rule = dialog.style_payload()['rules']['table'] + assert rule['cell_padding'] == 80 and rule['border_width'] == 30 + finally: dialog.close() + + +@pytest.mark.parametrize('engine', ENGINES) +def test_preset_copy_roundtrip_keeps_word_defaults(qt_application, tmp_path, monkeypatch, engine): + monkeypatch.setattr(main_window, 'QSettings', lambda *_: QSettings(str(tmp_path / 'settings.ini'), QSettings.Format.IniFormat)) + window = main_window.MainWindow(None, app_root=tmp_path) + dialog = DocumentStyleEditorDialog(window._style_payload_for_id('serif'), parent=window) + try: + dialog.select_target('link') + dialog.bool_boxes['strike'].setCheckState(Qt.CheckState.Checked) + payload = normalize_payload(json.loads(json.dumps(dialog.style_payload()))) + assert payload['rules']['_preset'] == 'serif' + before = resolved_rules({}, preset='serif')['paragraph'] + after = resolved_rules(payload['rules'], preset='custom:copy')['paragraph'] + assert after == before + path = export_markdown_to_docx('BookText', tmp_path / 'book.docx', engine=engine, + style_rules=payload['rules'], preset='custom:copy') + doc, styles = parts(path) + run = text_run(effective_document(doc, styles), 'BookText') + assert run.find('w:rPr/w:rFonts', NS).get(W + 'ascii') == 'Georgia' + assert run.find('w:rPr/w:rFonts', NS).get(W + 'eastAsia') == 'SimSun' + assert styles.find("w:style[@w:styleId='MDHelperParagraph']/w:pPr/w:spacing", NS).get(W + 'line') == '437' + finally: dialog.close(); window.close() + + +@pytest.mark.parametrize('detached', [False, True]) +def test_code_block_overrides_legacy_inner_code_rules(qt_application, tmp_path, detached): + rules = {'code': {'font_color': '#ff0000', 'font_size': 20, 'font_size_unit': 'pt', 'english_font_family': 'Arial'}} + if detached: rules['_metadata'] = {'code_block': {'based_on': ''}} + else: rules['code_block'] = {'font_color': '#0000ff', 'font_size': 10, 'font_size_unit': 'pt', 'english_font_family': 'Consolas'} + payload = normalize_payload({'rules': rules}) + values = browser(qt_application, tmp_path, payload, '```python\nprint("CodeText")\n```', + "[...document.querySelectorAll('pre,pre code,pre code span')].map(e=>{const s=getComputedStyle(e);return [s.color,s.fontSize,s.fontFamily]})") + assert all(item == values[0] for item in values) + assert values[0][0] == ('rgb(35, 39, 47)' if detached else 'rgb(0, 0, 255)') + # A legacy style without a semantic override keeps its former appearance. + legacy = normalize_payload({'rules': {'code': rules['code']}}) + assert browser(qt_application, tmp_path, legacy, '```text\nOld\n```', + "getComputedStyle(document.querySelector('pre code')).color") == 'rgb(255, 0, 0)' + + +def test_dark_theme_defaults_do_not_override_explicit_style_colors(qt_application, tmp_path): + payload = normalize_payload({'rules': {'h1': {'font_color': '#ff0000'}, 'link': {'font_color': '#ff0000'}, + 'code_block': {'background_color': '#ffff00'}}}) + values = browser(qt_application, tmp_path, payload, '# Header\n\n[Link](https://example.com)\n\n```text\nCode\n```', + "(()=>{document.documentElement.dataset.theme='dark';return [getComputedStyle(document.querySelector('h1')).color,getComputedStyle(document.querySelector('a')).color,getComputedStyle(document.querySelector('pre')).backgroundColor,getComputedStyle(document.documentElement).colorScheme]})()") + assert values == ['rgb(255, 0, 0)', 'rgb(255, 0, 0)', 'rgb(255, 255, 0)', 'dark'] + defaults = browser(qt_application, tmp_path, normalize_payload({}), '# Header\n\n[Link](#header)', + "(()=>{document.documentElement.dataset.theme='dark';return [getComputedStyle(document.querySelector('h1')).color,getComputedStyle(document.querySelector('a')).color]})()") + assert defaults == ['rgb(244, 247, 251)', 'rgb(121, 184, 255)'] + + +@pytest.mark.parametrize('engine', ENGINES) +def test_repeated_nested_character_style_keeps_innermost_precedence(tmp_path, engine): + path = export_markdown_to_docx(REPEATED_SOURCE, tmp_path / 'repeated.docx', engine=engine, style_rules=REPEATED_RULES) + doc, styles = parts(path) + run = text_run(effective_document(doc, styles), 'Deep') + assert run.find('w:rPr/w:color', NS).get(W + 'val') == 'ff0000' + assert run.find('w:rPr/w:b', NS).get(W + 'val') == '1' + assert run.find('w:rPr/w:i', NS).get(W + 'val') == '1' + + +@pytest.mark.parametrize('engine', ENGINES) +def test_nested_list_inherits_right_and_hanging_indent_edits(tmp_path, engine): + path = export_markdown_to_docx('- OuterList\n - InnerList', tmp_path / 'list.docx', engine=engine) + doc, styles = parts(path) + nested = styles.find("w:style[@w:styleId='MDHelperListBulletLevel2']/w:pPr/w:ind", NS) + assert set(nested.attrib) == {W + 'left', W + 'leftChars'} + base = child(styles.find("w:style[@w:styleId='MDHelperListBullet']/w:pPr", NS), 'ind') + base.set(W + 'right', '400'); base.set(W + 'rightChars', '0') + base.set(W + 'hangingChars', '200') + rendered = effective_document(doc, styles) + inner = next(p for p in rendered.iter(W + 'p') if 'InnerList' in ''.join(p.itertext())) + assert inner.find('w:pPr/w:ind', NS).get(W + 'right') == '400' + assert inner.find('w:pPr/w:ind', NS).get(W + 'hangingChars') == '200' + + +@pytest.mark.parametrize('engine', ENGINES) +def test_absolute_first_indent_survives_inherited_font_and_gui_roundtrip(qt_application, tmp_path, engine): + payload = normalize_payload(ABSOLUTE_PAYLOAD) + dialog = DocumentStyleEditorDialog(payload) + try: + dialog.select_target('h2') + assert dialog.indent_unit_combo.currentData() == 'pt' and dialog.indent_spin.value() == 24 + dialog.bool_boxes['italic'].setCheckState(Qt.CheckState.Checked) + payload = normalize_payload(dialog.style_payload()) + assert payload['rules']['h2']['indent_value'] == 24 and payload['rules']['h2']['indent_unit'] == 'pt' + path = export_markdown_to_docx('## Indented', tmp_path / 'indent.docx', engine=engine, style_rules=payload['rules']) + doc, styles = parts(path) + ind = effective_document(doc, styles).find('.//w:pPr/w:ind', NS) + assert ind.get(W + 'firstLine') == '480' and ind.get(W + 'firstLineChars') == '0' + finally: dialog.close() diff --git a/tests/word_styles_smoke.ps1 b/tests/word_styles_smoke.ps1 index 29be388..426a447 100644 --- a/tests/word_styles_smoke.ps1 +++ b/tests/word_styles_smoke.ps1 @@ -12,6 +12,8 @@ from test_word_named_styles import SOURCE 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 +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'): @@ -19,6 +21,10 @@ for engine in ('builtin', 'python-docx', 'pandoc'): 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) export_markdown_to_docx(NESTED_SOURCE, folder / (engine + '-nested.docx'), engine=engine, style_rules=NESTED_RULES) + export_markdown_to_docx(REPEATED_SOURCE, folder / (engine + '-repeated.docx'), engine=engine, style_rules=REPEATED_RULES) + export_markdown_to_docx('- OuterList\n - InnerList', folder / (engine + '-list.docx'), engine=engine) + export_markdown_to_docx('## Indented', folder / (engine + '-absolute.docx'), engine=engine, style_rules=normalize_payload(ABSOLUTE_PAYLOAD)['rules']) + export_markdown_to_docx('BookText', folder / (engine + '-preset.docx'), engine=engine, style_rules={'_preset': 'serif'}, preset='custom:copy') (folder / 'names.json').write_text(json.dumps({key: 'MDHelper ' + style_name(key) for key in ('paragraph', 'strong', 'link', 'h1')}), encoding='utf-8') print(folder) '@ | & $Python -B -).Trim() @@ -81,6 +87,28 @@ print(folder) if ($link.Font.Color -ne 65280 -or $bold.Font.Color -ne 255) { throw "$engine lost shared link style or inner override." } Write-Output "$engine passed: child units, nested colors and shared style updates." } finally { $doc.Close(0); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc) } + foreach ($case in @('repeated', 'list', 'absolute', 'preset')) { + $doc = $word.Documents.Open((Join-Path $testDirectory "$engine-$case.docx"), $false, $true) + try { + $text = switch ($case) { 'repeated' { 'Deep' }; 'list' { 'OuterList' }; 'absolute' { 'Indented' }; 'preset' { 'BookText' } } + $range = $doc.Content.Duplicate + if (-not $range.Find.Execute($text)) { throw "Missing $case text" } + switch ($case) { + 'repeated' { if ($range.Font.Color -ne 255) { throw "$engine lost innermost repeated style." } } + 'absolute' { if ($range.ParagraphFormat.FirstLineIndent -ne 24) { throw "$engine changed absolute indentation." } } + 'preset' { if ($range.Font.NameAscii -ne 'Georgia') { throw "$engine lost copied preset." } } + 'list' { + $base = $doc.Styles.Item($range.Style.NameLocal) + $base.ParagraphFormat.CharacterUnitRightIndent = 0 + $base.ParagraphFormat.RightIndent = 20 + $base.ParagraphFormat.CharacterUnitFirstLineIndent = -2 + $range = $doc.Content.Duplicate; [void]$range.Find.Execute('InnerList') + if ($range.ParagraphFormat.RightIndent -ne 20 -or $range.ParagraphFormat.CharacterUnitFirstLineIndent -ne -2) { throw "$engine froze nested list inheritance." } + } + } + } finally { $doc.Close(0); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc) } + } + Write-Output "$engine passed: repeated inline styles, nested list edits, absolute indents and copied presets." } } finally { if ($word) { $word.Quit(); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($word) }