fix: preserve per-property inheritance and semantic emphasis
This commit is contained in:
@@ -31,7 +31,7 @@
|
|||||||
|
|
||||||
`style_panel.py` 仅在用户打开时创建,按文档版本缓存语法分析,隐藏时停止刷新;`style_dialog.py` 的实际阅读预览也只在切换到该页时创建。启动路径不创建这些浏览器,不重建主窗口。
|
`style_panel.py` 仅在用户打开时创建,按文档版本缓存语法分析,隐藏时停止刷新;`style_dialog.py` 的实际阅读预览也只在切换到该页时创建。启动路径不创建这些浏览器,不重建主窗口。
|
||||||
|
|
||||||
`docx_style.py` 负责格式字段与 OOXML 属性的转换及属性顺序;`docx_semantic.py` 识别各引擎输出的语义、生成命名段落/字符/表格样式,并移除会遮盖样式的重复直接格式。保留编号、公式、关系和书签;组合字符与加粗段落上下文采用命名变体。`tests/word_styles_smoke.ps1` 使用本机 Word 的独立隐藏实例,验证打开文件、样式修改传播及继承,关闭时不保存测试修改。
|
`docx_style.py` 负责格式字段与 OOXML 属性的转换及属性顺序;`docx_semantic.py` 识别各引擎输出的语义、生成命名段落/字符/表格样式,并按属性保留继承。保留编号、公式、关系和书签;除用于防止 Word 反向切换的明确字符字形(加粗、斜体、删除线)外,不重复写入直接字体、字号、颜色和段落格式。组合字符采用命名样式。`tests/word_styles_smoke.ps1` 使用本机 Word 的独立隐藏实例,验证打开文件、样式修改传播及继承,关闭时不保存测试修改。
|
||||||
|
|
||||||
`preferences.py` 定义 `ReaderPreferences` 和 `ApplicationConfiguration`。本地设置与 JSON 导入共用字段、取值检查和旧版迁移规则;`ConfigurationStore` 负责持久化。页面设置保留旧版 PDF 页边距的读取方式。窗口几何状态和草稿仍由各自的界面、文档组件管理。内置文档样式集中在 `style_presets.py`。
|
`preferences.py` 定义 `ReaderPreferences` 和 `ApplicationConfiguration`。本地设置与 JSON 导入共用字段、取值检查和旧版迁移规则;`ConfigurationStore` 负责持久化。页面设置保留旧版 PDF 页边距的读取方式。窗口几何状态和草稿仍由各自的界面、文档组件管理。内置文档样式集中在 `style_presets.py`。
|
||||||
|
|
||||||
|
|||||||
+3
-1
@@ -173,7 +173,9 @@ Markdown 支持:
|
|||||||
|
|
||||||
三个 Word 导出引擎均创建 `MDHelper 正文`、`MDHelper 标题 1`、`MDHelper 加粗` 等命名样式。导出后,在 Word 的样式面板中修改相应样式,即可统一调整引用该样式的内容;正文的字体和字号也会传递到未单独设置字体的加粗、强调和链接文字。表格边框及内边距通过 Word 表格样式修改。
|
三个 Word 导出引擎均创建 `MDHelper 正文`、`MDHelper 标题 1`、`MDHelper 加粗` 等命名样式。导出后,在 Word 的样式面板中修改相应样式,即可统一调整引用该样式的内容;正文的字体和字号也会传递到未单独设置字体的加粗、强调和链接文字。表格边框及内边距通过 Word 表格样式修改。
|
||||||
|
|
||||||
Word 每段文字只能引用一个字符样式,因此加粗链接等组合会生成 `MDHelper 超链接+加粗` 等组合样式;组合优先以超链接为基准,其余效果保存在组合样式中。标题中加粗等情况会生成带段落名称的变体,以适配 Word 的加粗叠加规则。组合和变体都可以在 Word 样式面板统一修改,但不会同时继承多个字符样式。嵌套列表使用基于对应列表样式的层级样式,层级缩进可单独修改。
|
Word 每段文字只能引用一个字符样式,因此加粗链接等组合会生成 `MDHelper 超链接+加粗` 等组合样式;组合不会同时继承多个字符样式。嵌套列表使用基于对应列表样式的层级样式,层级缩进可单独修改。
|
||||||
|
|
||||||
|
Word 的字符样式会把加粗、斜体和删除线作为与段落格式叠加的开关。导出采用强调保护:明确字符样式中的这些字形设置会固定在对应文字上,避免修改正文或标题样式时反向关闭强调。字体、字号、颜色、下划线和段落仍由命名样式统一控制;受保护的加粗、斜体和删除线不能仅通过 Word 字符样式关闭,可在 MDHelper 调整后重新导出,或在 Word 中清除对应文字的直接字形格式再使用其原生样式规则。
|
||||||
|
|
||||||
纸张宽度是全局阅读设置,内置样式不再写死正文宽度,会跟随纸张宽度变化。
|
纸张宽度是全局阅读设置,内置样式不再写死正文宽度,会跟随纸张宽度变化。
|
||||||
|
|
||||||
|
|||||||
+25
-16
@@ -44,15 +44,26 @@ def _delta(current, base, authored=None):
|
|||||||
'keepNext': ('keep_with_next',), 'keepLines': ('keep_lines_together',), 'pageBreakBefore': ('page_break_before',),
|
'keepNext': ('keep_with_next',), 'keepLines': ('keep_lines_together',), 'pageBreakBefore': ('page_break_before',),
|
||||||
'widowControl': ('widow_control',), 'contextualSpacing': ('contextual_spacing',)}
|
'widowControl': ('widow_control',), 'contextualSpacing': ('contextual_spacing',)}
|
||||||
for node in list(current):
|
for node in list(current):
|
||||||
if any(field in authored for field in fields.get(ET.QName(node).localname, ())): continue
|
|
||||||
old = base.find(node.tag)
|
old = base.find(node.tag)
|
||||||
if old is not None and node.attrib == old.attrib and node.text == old.text and not len(node) and not len(old):
|
compound = {
|
||||||
current.remove(node)
|
'rFonts': {'ascii': ('english_font_family',), 'hAnsi': ('english_font_family',),
|
||||||
elif old is not None and node.tag in {W + 'rFonts', W + 'spacing', W + 'ind'}:
|
'cs': ('english_font_family',), 'eastAsia': ('chinese_font_family',)},
|
||||||
|
'spacing': {**{attr: (f'space_{side}_value', f'space_{side}_unit')
|
||||||
|
for side in ('before', 'after') for attr in (side, side + 'Lines', side + 'Autospacing')},
|
||||||
|
'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')}},
|
||||||
|
}.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.
|
# These properties merge attribute by attribute in Word.
|
||||||
for key in list(node.attrib):
|
for key in list(node.attrib):
|
||||||
if old.get(key) == node.get(key): del node.attrib[key]
|
explicit = any(field in authored for field in compound.get(ET.QName(key).localname, ()))
|
||||||
|
if not explicit and old.get(key) == node.get(key): del node.attrib[key]
|
||||||
if not node.attrib and not len(node): current.remove(node)
|
if not node.attrib and not len(node): current.remove(node)
|
||||||
|
elif not any(field in authored for field in fields.get(ET.QName(node).localname, ())):
|
||||||
|
if old is not None and node.attrib == old.attrib and node.text == old.text and not len(node) and not len(old):
|
||||||
|
current.remove(node)
|
||||||
|
|
||||||
|
|
||||||
class WordStyles:
|
class WordStyles:
|
||||||
@@ -158,17 +169,6 @@ class WordStyles:
|
|||||||
_run_properties(props, merged)
|
_run_properties(props, merged)
|
||||||
_run_properties(old, self.character_rule(keys[0]))
|
_run_properties(old, self.character_rule(keys[0]))
|
||||||
_delta(props, old)
|
_delta(props, old)
|
||||||
# Word XORs style-level emphasis with the paragraph's emphasis. A named
|
|
||||||
# context variant compensates for that (e.g. **text** in a bold heading),
|
|
||||||
# keeping all formatting editable in the Styles panel, not on each run.
|
|
||||||
compensate = [field for field in ('bold', 'italic', 'strike') if field in merged and self.effective[paragraph_target].get(field)]
|
|
||||||
if compensate:
|
|
||||||
context_id = identifier + 'In' + style_id(paragraph_target)[8:]
|
|
||||||
if context_id not in self.created:
|
|
||||||
style = self.new(context_id, 'character', 'MDHelper ' + '+'.join(style_name(k, self.rules) for k in keys) + '(' + style_name(paragraph_target, self.rules) + ')', identifier)
|
|
||||||
for field in compensate:
|
|
||||||
for tag in {'bold': ('b', 'bCs'), 'italic': ('i', 'iCs'), 'strike': ('strike',)}[field]: val(child(style, 'rPr'), tag, int(not merged[field]))
|
|
||||||
identifier = context_id
|
|
||||||
return identifier
|
return identifier
|
||||||
|
|
||||||
def syntax_style(self, run_id, target):
|
def syntax_style(self, run_id, target):
|
||||||
@@ -311,6 +311,15 @@ class WordStyles:
|
|||||||
remove_fields(rpr, RUN_FIELDS)
|
remove_fields(rpr, RUN_FIELDS)
|
||||||
if identifier: val(rpr, 'rStyle', identifier)
|
if identifier: val(rpr, 'rStyle', identifier)
|
||||||
else: remove_fields(rpr, ('rStyle',))
|
else: remove_fields(rpr, ('rStyle',))
|
||||||
|
# Word character-style emphasis XORs with paragraph emphasis. Protect
|
||||||
|
# only explicit semantic emphasis; fonts, sizes, colors and spacing stay
|
||||||
|
# style-driven. This is an intentional export contract, not a style copy.
|
||||||
|
merged = {}
|
||||||
|
for key in ('link', 'strong', 'emphasis', 'strike', 'inline_code'):
|
||||||
|
if key in keys: merged.update(self.character_rule(key))
|
||||||
|
for field, tags in (('bold', ('b', 'bCs')), ('italic', ('i', 'iCs')), ('strike', ('strike',))):
|
||||||
|
if field in merged:
|
||||||
|
for tag in tags: val(rpr, tag, int(merged[field]))
|
||||||
|
|
||||||
def apply(self, document):
|
def apply(self, document):
|
||||||
for paragraph in document.iter(W + 'p'):
|
for paragraph in document.iter(W + 'p'):
|
||||||
|
|||||||
+16
-2
@@ -33,7 +33,7 @@ PROPERTIES = {
|
|||||||
"fonts": {"font-family", "--mdhelper-font-chinese", "--mdhelper-font-english"},
|
"fonts": {"font-family", "--mdhelper-font-chinese", "--mdhelper-font-english"},
|
||||||
"size": {"font-size"}, "bold": {"font-weight"}, "italic": {"font-style"}, "color": {"color"},
|
"size": {"font-size"}, "bold": {"font-weight"}, "italic": {"font-style"}, "color": {"color"},
|
||||||
"tracking": {"letter-spacing"}, "align": {"text-align"},
|
"tracking": {"letter-spacing"}, "align": {"text-align"},
|
||||||
'decoration': {'text-decoration', 'text-decoration-line'}, 'background': {'background-color'},
|
'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'}, 'padding': {'padding'},
|
||||||
'marker': {'list-style-type'}, 'level_indent': {'--mdhelper-list-level-indent'},
|
'marker': {'list-style-type'}, 'level_indent': {'--mdhelper-list-level-indent'},
|
||||||
"line": {"line-height", "--mdhelper-line-spacing-mode"}, "indent": {"text-indent"},
|
"line": {"line-height", "--mdhelper-line-spacing-mode"}, "indent": {"text-indent"},
|
||||||
@@ -62,6 +62,7 @@ ALIASES.update({'strong': 'strong', 'em': 'emphasis', 's': 'strike', 'del': 'str
|
|||||||
ALIASES[_normalize_selector_text(SELECTORS["paragraph"])] = "paragraph"
|
ALIASES[_normalize_selector_text(SELECTORS["paragraph"])] = "paragraph"
|
||||||
FONT_VARIABLES = {"chinese_font_family": "--mdhelper-font-chinese", "english_font_family": "--mdhelper-font-english"}
|
FONT_VARIABLES = {"chinese_font_family": "--mdhelper-font-chinese", "english_font_family": "--mdhelper-font-english"}
|
||||||
FONT_EXPRESSION = "var(--mdhelper-font-english, var(--mdhelper-font-chinese, var(--reader-font-family))), var(--mdhelper-font-chinese, sans-serif)"
|
FONT_EXPRESSION = "var(--mdhelper-font-english, var(--mdhelper-font-chinese, var(--reader-font-family))), var(--mdhelper-font-chinese, sans-serif)"
|
||||||
|
DECORATION_EXPRESSION = 'var(--mdhelper-text-decoration, none)'
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -301,6 +302,10 @@ class _CoreRuleReader:
|
|||||||
return self.rule
|
return self.rule
|
||||||
|
|
||||||
def decoration(self, value):
|
def decoration(self, value):
|
||||||
|
if re.sub(r'\s+', '', value) == re.sub(r'\s+', '', DECORATION_EXPRESSION):
|
||||||
|
for key in ('underline', 'strike'):
|
||||||
|
self.choice('--mdhelper-' + key, key, {'true': True, 'false': False})
|
||||||
|
return
|
||||||
parts = value.split()
|
parts = value.split()
|
||||||
if not parts or not set(parts) <= {'none', 'underline', 'line-through'}: raise ValueError
|
if not parts or not set(parts) <= {'none', 'underline', 'line-through'}: raise ValueError
|
||||||
self.rule.update(underline='underline' in parts, strike='line-through' in parts)
|
self.rule.update(underline='underline' in parts, strike='line-through' in parts)
|
||||||
@@ -426,7 +431,10 @@ def analyze_css(source: str, font_size_px: float = 16) -> Analysis:
|
|||||||
|
|
||||||
|
|
||||||
def _core_declarations(rule):
|
def _core_declarations(rule):
|
||||||
declarations = [d for d in css_declarations(rule) if not d.startswith(("font-family:", "padding-left:"))]
|
declarations = [d for d in css_declarations(rule) if not d.startswith(("font-family:", "padding-left:", 'text-decoration-line:'))]
|
||||||
|
if 'underline' in rule or 'strike' in rule:
|
||||||
|
declarations.extend(f'--mdhelper-{key}: {str(rule[key]).lower()};' for key in ('underline', 'strike') if key in rule)
|
||||||
|
declarations.append(f'text-decoration-line: {DECORATION_EXPRESSION};')
|
||||||
if any(rule.get(key) for key in FONT_VARIABLES):
|
if any(rule.get(key) for key in FONT_VARIABLES):
|
||||||
for key, variable in FONT_VARIABLES.items():
|
for key, variable in FONT_VARIABLES.items():
|
||||||
if rule.get(key):
|
if rule.get(key):
|
||||||
@@ -541,6 +549,12 @@ def render_css(source: str, rules: dict, font_family: str = '', font_size_px: fl
|
|||||||
contextual = {key: {"contextual_spacing": True} for key, rule in rules.items() if isinstance(rule, dict) and rule.get("contextual_spacing")}
|
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)
|
||||||
helpers += '\n' + build_document_style_css(inherited)
|
helpers += '\n' + build_document_style_css(inherited)
|
||||||
|
# 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():
|
||||||
|
if any(field in rules.get(key, {}) or field in inherited.get(key, {}) for field in ('underline', 'strike')):
|
||||||
|
decoration = ' '.join(token for field, token in (('underline', 'underline'), ('strike', 'line-through')) if rule.get(field)) or 'none'
|
||||||
|
helpers += '\n' + SELECTORS[key] + ' { --mdhelper-text-decoration: ' + decoration + '; }'
|
||||||
paragraph = rules.get("paragraph", {})
|
paragraph = rules.get("paragraph", {})
|
||||||
if paragraph.get("font_size"):
|
if paragraph.get("font_size"):
|
||||||
helpers += f"\n.reader {{ --reader-math-font-size: {fmt(paragraph['font_size'])}{paragraph.get('font_size_unit', 'px')}; }}"
|
helpers += f"\n.reader {{ --reader-math-font-size: {fmt(paragraph['font_size'])}{paragraph.get('font_size_unit', 'px')}; }}"
|
||||||
|
|||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import json
|
||||||
|
import time
|
||||||
|
import zipfile
|
||||||
|
from lxml import etree as ET
|
||||||
|
import pytest
|
||||||
|
from PySide6.QtCore import Qt
|
||||||
|
from PySide6.QtWebEngineCore import QWebEnginePage
|
||||||
|
from mdhelper.docx_exporter import export_markdown_to_docx
|
||||||
|
from mdhelper.docx_style import W, NS, val
|
||||||
|
from mdhelper.style_dialog import DocumentStyleEditorDialog
|
||||||
|
from mdhelper.style_sync import normalize_payload, render_css
|
||||||
|
from mdhelper.markdown_renderer import MarkdownRenderer
|
||||||
|
from docx_assertions import effective_document
|
||||||
|
|
||||||
|
PARTIAL_RULES = {
|
||||||
|
'h1': {'chinese_font_family': 'SimSun', 'english_font_family': 'Arial', 'font_size': 12, 'font_size_unit': 'pt',
|
||||||
|
'space_after_value': 8, 'space_after_unit': 'pt', 'line_height_value': 1.5, 'line_spacing_mode': 'multiple',
|
||||||
|
'left_indent_value': 24, 'left_indent_unit': 'pt'},
|
||||||
|
'h2': {'english_font_family': 'Courier New', 'space_before_value': 12, 'space_before_unit': 'pt',
|
||||||
|
'right_indent_value': 8, 'right_indent_unit': 'pt'},
|
||||||
|
'_metadata': {'h2': {'based_on': 'h1'}},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def parts(path):
|
||||||
|
with zipfile.ZipFile(path) as z:
|
||||||
|
return ET.fromstring(z.read('word/document.xml')), ET.fromstring(z.read('word/styles.xml'))
|
||||||
|
|
||||||
|
|
||||||
|
def browser(qapp, tmp_path, payload, source, expression):
|
||||||
|
page = QWebEnginePage(); loaded = []; result = []
|
||||||
|
def wait(predicate):
|
||||||
|
end = time.monotonic() + 12
|
||||||
|
while not predicate() and time.monotonic() < end: qapp.processEvents(); time.sleep(.01)
|
||||||
|
assert predicate(), 'WebEngine timed out'
|
||||||
|
try:
|
||||||
|
page.loadFinished.connect(loaded.append)
|
||||||
|
page.setHtml(MarkdownRenderer(tmp_path).render_source(source, tmp_path / 'test.md',
|
||||||
|
document_style_css=render_css(payload['css'], payload['rules'])))
|
||||||
|
wait(lambda: loaded)
|
||||||
|
page.runJavaScript('JSON.stringify(' + expression + ')', result.append)
|
||||||
|
wait(lambda: result)
|
||||||
|
return json.loads(result[0])
|
||||||
|
finally: page.deleteLater(); qapp.processEvents()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc'])
|
||||||
|
def test_word_inherits_other_attributes_when_one_attribute_is_explicit(tmp_path, engine):
|
||||||
|
path = export_markdown_to_docx('# Parent\n\n## Child', tmp_path / 'partial.docx', engine=engine, style_rules=PARTIAL_RULES)
|
||||||
|
doc, styles = parts(path)
|
||||||
|
base = styles.find("w:style[@w:styleId='MDHelperH1']", NS)
|
||||||
|
child = styles.find("w:style[@w:styleId='MDHelperH2']", NS)
|
||||||
|
assert child.find('w:rPr/w:rFonts', NS).get(W + 'eastAsia') is None
|
||||||
|
assert child.find('w:rPr/w:rFonts', NS).get(W + 'ascii') == 'Courier New'
|
||||||
|
assert set(child.find('w:pPr/w:spacing', NS).attrib) == {W + 'before'}
|
||||||
|
assert set(child.find('w:pPr/w:ind', NS).attrib) == {W + 'right'}
|
||||||
|
base.find('w:rPr/w:rFonts', NS).set(W + 'eastAsia', 'KaiTi')
|
||||||
|
base.find('w:pPr/w:spacing', NS).set(W + 'after', '480')
|
||||||
|
rendered = effective_document(doc, styles)
|
||||||
|
paragraph = next(p for p in rendered.iter(W + 'p') if 'Child' in ''.join(p.itertext()))
|
||||||
|
assert paragraph.find('.//w:rFonts', NS).get(W + 'eastAsia') == 'KaiTi'
|
||||||
|
assert paragraph.find('w:pPr/w:spacing', NS).get(W + 'after') == '480'
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc'])
|
||||||
|
def test_word_semantic_emphasis_survives_paragraph_style_changes(tmp_path, engine):
|
||||||
|
path = export_markdown_to_docx('Plain **StrongText** *ItalicText* ~~Deleted~~\n\n# Title **HeadingStrong**', tmp_path / 'emphasis.docx', engine=engine)
|
||||||
|
doc, styles = parts(path)
|
||||||
|
base = styles.find("w:style[@w:styleId='MDHelperParagraph']/w:rPr", NS)
|
||||||
|
for tag in ('b', 'i', 'strike'): val(base, tag, 1)
|
||||||
|
val(styles.find("w:style[@w:styleId='MDHelperH1']/w:rPr", NS), 'b', 0)
|
||||||
|
rendered = effective_document(doc, styles)
|
||||||
|
for text, tag in (('StrongText', 'b'), ('HeadingStrong', 'b'), ('ItalicText', 'i'), ('Deleted', 'strike')):
|
||||||
|
run = next(r for r in rendered.iter(W + 'r') if text in ''.join(r.itertext()))
|
||||||
|
assert run.find('w:rPr/w:' + tag, NS).get(W + 'val') == '1'
|
||||||
|
for run in doc.iter(W + 'r'):
|
||||||
|
assert run.find('w:rPr/w:sz', NS) is None
|
||||||
|
assert run.find('w:rPr/w:rFonts', NS) is None
|
||||||
|
assert run.find('w:rPr/w:color', NS) is None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('key,changed,source,selector', [('strike', 'underline', '~~Text~~', 's'), ('link', 'strike', '[Text](#text)', 'p a')])
|
||||||
|
def test_graphical_decoration_preserves_inherited_counterpart(qt_application, tmp_path, key, changed, source, selector):
|
||||||
|
dialog = DocumentStyleEditorDialog({})
|
||||||
|
try:
|
||||||
|
dialog.select_target(key)
|
||||||
|
dialog.bool_boxes[changed].setCheckState(Qt.CheckState.Checked)
|
||||||
|
payload = dialog.style_payload()
|
||||||
|
assert payload['rules'][key] == {changed: True}
|
||||||
|
assert normalize_payload(payload)['rules'][key] == {changed: True}
|
||||||
|
actual = browser(qt_application, tmp_path, payload, source, f'getComputedStyle(document.querySelector("{selector}")).textDecorationLine')
|
||||||
|
assert set(actual.split()) == {'underline', 'line-through'}
|
||||||
|
# Explicitly switching the other property off is still respected.
|
||||||
|
other = 'strike' if changed == 'underline' else 'underline'
|
||||||
|
dialog.bool_boxes[other].setCheckState(Qt.CheckState.Unchecked)
|
||||||
|
assert dialog.style_payload()['rules'][key][other] is False
|
||||||
|
finally: dialog.close()
|
||||||
@@ -29,7 +29,8 @@ def test_shared_named_styles_without_direct_format_overrides(tmp_path, engine):
|
|||||||
assert ppr.find(W + 'pStyle').get(W + 'val') in by_id
|
assert ppr.find(W + 'pStyle').get(W + 'val') in by_id
|
||||||
for run in doc.iter(W + 'r'):
|
for run in doc.iter(W + 'r'):
|
||||||
rpr = run.find(W + 'rPr')
|
rpr = run.find(W + 'rPr')
|
||||||
assert all(rpr.find(W + field) is None for field in RUN_FIELDS)
|
protected = {'b', 'bCs', 'i', 'iCs', 'strike'}
|
||||||
|
assert all(rpr.find(W + field) is None for field in set(RUN_FIELDS) - protected)
|
||||||
ref = rpr.find(W + 'rStyle')
|
ref = rpr.find(W + 'rStyle')
|
||||||
if ref is not None: assert ref.get(W + 'val') in by_id
|
if ref is not None: assert ref.get(W + 'val') in by_id
|
||||||
paragraph_ids = {p.find('w:pPr/w:pStyle', NS).get(W + 'val') for p in doc.iter(W + 'p')}
|
paragraph_ids = {p.find('w:pPr/w:pStyle', NS).get(W + 'val') for p in doc.iter(W + 'p')}
|
||||||
|
|||||||
@@ -11,10 +11,12 @@ sys.path.insert(0, str(Path('tests').resolve()))
|
|||||||
from test_word_named_styles import SOURCE
|
from test_word_named_styles import SOURCE
|
||||||
from mdhelper.docx_exporter import export_markdown_to_docx
|
from mdhelper.docx_exporter import export_markdown_to_docx
|
||||||
from mdhelper.style_catalog import style_name
|
from mdhelper.style_catalog import style_name
|
||||||
|
from test_style_regressions import PARTIAL_RULES
|
||||||
folder = Path(tempfile.mkdtemp(prefix='MDHelper-Word-Styles-'))
|
folder = Path(tempfile.mkdtemp(prefix='MDHelper-Word-Styles-'))
|
||||||
rules = {'h2': {'bold': False}, '_metadata': {'h2': {'based_on': 'h1'}}}
|
rules = {'h2': {'bold': False}, '_metadata': {'h2': {'based_on': 'h1'}}}
|
||||||
for engine in ('builtin', 'python-docx', 'pandoc'):
|
for engine in ('builtin', 'python-docx', 'pandoc'):
|
||||||
export_markdown_to_docx(SOURCE + '\n\n## Child title', folder / (engine + '.docx'), engine=engine, style_rules=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)
|
||||||
(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')}), encoding='utf-8')
|
||||||
print(folder)
|
print(folder)
|
||||||
'@ | & $Python -B -).Trim()
|
'@ | & $Python -B -).Trim()
|
||||||
@@ -44,8 +46,25 @@ print(folder)
|
|||||||
if ($range.Font.Bold -ne 0) { throw "$engine explicit child-style bold=False did not override its base." }
|
if ($range.Font.Bold -ne 0) { throw "$engine explicit child-style bold=False did not override its base." }
|
||||||
$doc.Styles.Item($names.h1).Font.Size = 30
|
$doc.Styles.Item($names.h1).Font.Size = 30
|
||||||
if ($range.Font.Size -ne 30) { throw "$engine base-style change does not reach child heading." }
|
if ($range.Font.Size -ne 30) { throw "$engine base-style change does not reach child heading." }
|
||||||
|
$range = $doc.Content.Duplicate; [void]$range.Find.Execute('strong second')
|
||||||
|
$doc.Styles.Item($names.paragraph).Font.Bold = -1
|
||||||
|
if ($range.Font.Bold -ne -1) { throw "$engine paragraph bold inverted semantic emphasis." }
|
||||||
|
$range = $doc.Content.Duplicate; [void]$range.Find.Execute('bold title')
|
||||||
|
$doc.Styles.Item($names.h1).Font.Bold = 0
|
||||||
|
if ($range.Font.Bold -ne -1) { throw "$engine heading edit removed semantic emphasis." }
|
||||||
Write-Output "$engine passed: Word opened document, heading emphasis, body and character edits, mixed links, base-style inheritance."
|
Write-Output "$engine passed: Word opened document, heading emphasis, body and character edits, mixed links, base-style inheritance."
|
||||||
} finally { $doc.Close(0); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc) }
|
} finally { $doc.Close(0); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc) }
|
||||||
|
$doc = $word.Documents.Open((Join-Path $testDirectory "$engine-partial.docx"), $false, $true)
|
||||||
|
try {
|
||||||
|
$range = $doc.Content.Duplicate; [void]$range.Find.Execute('Child')
|
||||||
|
$base = $doc.Styles.Item($names.h1)
|
||||||
|
$base.Font.NameFarEast = 'KaiTi'; $base.ParagraphFormat.SpaceAfter = 24
|
||||||
|
$base.ParagraphFormat.LineSpacingRule = 0; $base.ParagraphFormat.LeftIndent = 40
|
||||||
|
if ($range.Font.NameFarEast -ne $base.Font.NameFarEast -or $range.ParagraphFormat.SpaceAfter -ne 24 -or $range.ParagraphFormat.LineSpacingRule -ne 0 -or $range.ParagraphFormat.LeftIndent -ne 40) {
|
||||||
|
throw "$engine partial overrides froze unrelated inherited properties."
|
||||||
|
}
|
||||||
|
Write-Output "$engine passed: partial overrides preserve inheritance of fonts, spacing and indents."
|
||||||
|
} finally { $doc.Close(0); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc) }
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if ($word) { $word.Quit(); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($word) }
|
if ($word) { $word.Quit(); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($word) }
|
||||||
|
|||||||
Reference in New Issue
Block a user