diff --git a/docs/user_manual.md b/docs/user_manual.md index 1ecd62c..466048a 100644 --- a/docs/user_manual.md +++ b/docs/user_manual.md @@ -185,7 +185,7 @@ Word 每段文字只能引用一个字符样式,因此加粗链接等组合会 内层明确设置与基准的初始值相同时,也会保留该覆盖关系;之后修改基准不会改变内层的明确设置。列表的缩进由命名段落样式控制,编号只负责标记和序号,因此在 Word 样式面板调整首行、悬挂和左右缩进可以继续生效。 -Markdown 表格明确指定的列对齐会保存为基于表头或单元格文字样式的派生样式,字体等格式继续继承。引用中的宽松列表保留引用格式,生成基于引用样式的“引用内段落”组合样式;其列表布局或其他独立覆盖可通过该组合样式统一调整。Word 一个段落样式只有一个基准,组合样式不会同时继承列表和引用两条基准链。 +Markdown 表格明确指定的列对齐会保存为基于表头或单元格文字样式的派生样式,字体等格式继续继承。引用中的宽松列表按 CSS 的继承和直接声明顺序组合:列表自身设置可覆盖引用容器传入的格式,直接作用于引用段落的设置优先;其列表布局或其他独立覆盖可通过“引用内段落”组合样式统一调整。列表内部的引用保留引用样式。Word 一个段落样式只有一个基准,组合样式不会同时继承列表和引用两条基准链。 Word 的字符样式会把加粗、斜体和删除线作为与段落格式叠加的开关。导出采用强调保护:明确字符样式中的这些字形设置会固定在对应文字上,避免修改正文或标题样式时反向关闭强调。字体、字号、颜色、下划线和段落仍由命名样式统一控制;受保护的加粗、斜体和删除线不能仅通过 Word 字符样式关闭,可在 MDHelper 调整后重新导出,或在 Word 中清除对应文字的直接字形格式再使用其原生样式规则。 @@ -201,6 +201,10 @@ Word 的字符样式会把加粗、斜体和删除线作为与段落格式叠加 独立的 `th`、`td`、`pre` 设置分别对应表头、单元格和代码块,不会串用到其他对象。旧版生成的 `table, th, td` 和 `pre, code` 合并规则仍作为兼容基准,未单独设置的子样式继续继承。 +旧 CSS 含 `!important` 时,图形设置修改核心属性和解除兼容继承仍会同步到阅读效果;无效颜色、字号等声明不会覆盖前面的有效值。显式单元格底色优先于隔行底纹,解除表格文字继承不会关闭表头底色或隔行底纹。 + +嵌套字符样式可分别开启或关闭下划线与删除线。阅读器按最终文字样式绘制修饰,内层关闭下划线时可保留外层删除线,文字仍正常换行。高级 CSS 的修饰颜色、波浪线及条件规则继续用于阅读器和 HTML/PDF;Word 保留已支持的核心修饰和命名样式。 + 普通 `p` 选择器也作用于引用和宽松列表中的段落,Word 会保留这些上下文格式;紧凑列表没有独立段落元素,不受该选择器影响。表头和单元格的段前、段后及左右间距作用于内部文字区域,表格内边距仍独立设置。明显无效的 CSS 值(例如 `font-size:nope`)会被忽略并提示,前面的有效声明继续同步;有效但不能转换为 Word 的扩展表达式仍保留为 CSS。 宽松列表中明确设置的 `p` 间距和缩进不会被列表辅助规则清零。图形设置修改引用等子对象时,会保留必要的 `!important` 优先级,使修改真正生效。无效的多值声明、错误单位和互斥文字修饰同样按浏览器的回退规则处理;`border-style:none` / `hidden` 会同步为 Word 无边框,改变宽度不会重新开启边框。 diff --git a/mdhelper/docx_exporter.py b/mdhelper/docx_exporter.py index 3137ada..14e3add 100644 --- a/mdhelper/docx_exporter.py +++ b/mdhelper/docx_exporter.py @@ -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, QUOTED_LIST_PARAGRAPH_STYLE, SOURCE_PARAGRAPH_STYLES, CONTINUATION +from .docx_inline import source_style_name, LIST_PARAGRAPH_STYLE, QUOTED_LIST_PARAGRAPH_STYLE, SOURCE_PARAGRAPH_STYLES, CONTINUATION, INNER_QUOTE_STYLE WP_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main" @@ -249,6 +249,7 @@ 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 name = QUOTED_LIST_PARAGRAPH_STYLE if block.quote_depth else LIST_PARAGRAPH_STYLE + if block.inner_quote: name = INNER_QUOTE_STYLE if name not in document.styles: marker = document.styles.add_style(name, WD_STYLE_TYPE.PARAGRAPH) marker.base_style = document.styles[style] @@ -334,6 +335,7 @@ class ParagraphBlock: loose: bool = False alignment: str = '' continuation: bool = False + inner_quote: bool = False @dataclass @@ -352,6 +354,7 @@ class _DocxBuilder: self.list_starts: list[int] = [] self.list_sequence = 1000 self.item_pending: list[bool] = [] + self.list_quote_depths: list[int] = [] self.quote_depth = 0 def build(self) -> list[ParagraphBlock | TableBlock]: @@ -381,10 +384,12 @@ class _DocxBuilder: self.list_sequence += 1 self.list_ids.append(self.list_sequence) self.list_starts.append(int(token.attrGet('start') or 1)) + self.list_quote_depths.append(self.quote_depth) elif token.type in {"bullet_list_close", "ordered_list_close"} and self.list_stack: self.list_stack.pop() self.list_ids.pop() self.list_starts.pop() + self.list_quote_depths.pop() elif token.type == "table_open": self.blocks.append(self._collect_table()) continue @@ -399,7 +404,8 @@ class _DocxBuilder: self.blocks.append(ParagraphBlock(runs, style=style, list_kind=list_kind, quote_depth=self.quote_depth, list_level=min(8, max(0, len(self.list_stack) - 1)), list_id=self.list_ids[-1] if self.list_ids else 0, list_start=self.list_starts[-1] if self.list_starts else 1, loose=not self.tokens[self.index].hidden, - continuation=bool(list_kind and self.item_pending and not self.item_pending[-1]))) + continuation=bool(list_kind and self.item_pending and not self.item_pending[-1]), + inner_quote=bool(self.list_quote_depths and self.quote_depth > self.list_quote_depths[-1]))) if self.item_pending: self.item_pending[-1] = False self.index += 3 @@ -499,6 +505,7 @@ def _paragraph_xml(block: ParagraphBlock) -> str: props = [f''] if block.style != "Normal" else [] if block.list_kind: name = (QUOTED_LIST_PARAGRAPH_STYLE if block.quote_depth else LIST_PARAGRAPH_STYLE) if block.loose else 'ListParagraph' + if block.inner_quote: name = INNER_QUOTE_STYLE props = [f''] props.append(f'') if block.quote_depth: diff --git a/mdhelper/docx_inline.py b/mdhelper/docx_inline.py index e497629..30cc590 100644 --- a/mdhelper/docx_inline.py +++ b/mdhelper/docx_inline.py @@ -2,7 +2,8 @@ PREFIX = 'MDHelperSource_' LIST_PARAGRAPH_STYLE = 'MDHelperSourceListParagraph' QUOTED_LIST_PARAGRAPH_STYLE = 'MDHelperSourceQuotedListParagraph' -SOURCE_PARAGRAPH_STYLES = (LIST_PARAGRAPH_STYLE, QUOTED_LIST_PARAGRAPH_STYLE) +INNER_QUOTE_STYLE = 'MDHelperSourceInnerQuote' +SOURCE_PARAGRAPH_STYLES = (LIST_PARAGRAPH_STYLE, QUOTED_LIST_PARAGRAPH_STYLE, INNER_QUOTE_STYLE) CONTINUATION = '{urn:mdhelper:source}continuation' 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 4f6e3d9..7a2d5ab 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, 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, QUOTED_LIST_PARAGRAPH_STYLE, SOURCE_PARAGRAPH_STYLES, CONTINUATION +from .docx_inline import source_style_order, ordered_styles, LIST_PARAGRAPH_STYLE, QUOTED_LIST_PARAGRAPH_STYLE, SOURCE_PARAGRAPH_STYLES, CONTINUATION, INNER_QUOTE_STYLE from .table_style import HEADER_COLOR, STRIPE_COLOR, BORDER_COLOR, VERTICAL_BORDER_COLOR RUN_FIELDS = 'rFonts sz szCs b bCs i iCs color spacing u strike shd'.split() @@ -170,7 +170,8 @@ class WordStyles: _run_properties(child(shared, 'rPr'), self.explicit['code']) # Word cannot clear one inherited character-style property. Preserve # the resolved remaining properties and inherit color from the text. - if rule.get('font_color') == 'inherit' and base and self.character_rule(base).get('font_color') not in (None, 'inherit'): + base_rule = self.explicit['code'] if legacy else self.character_rule(base) if base else {} + if rule.get('font_color') == 'inherit' and base_rule.get('font_color') not in (None, 'inherit'): base_id = '' style = self.new(identifier, 'character', 'MDHelper ' + style_name(key, self.rules), base_id) _run_properties(child(style, 'rPr'), rule) @@ -258,6 +259,7 @@ class WordStyles: def classify(self, paragraph, original_id): names = self.names(original_id) + if INNER_QUOTE_STYLE.lower() in names: return 'blockquote' heading = re.search(r'heading\s*([1-6])', names) if heading: return 'h' + heading[1] if any(word in names for word in ('sourcecode', 'source code', 'code', 'verbatim')): return 'code_block' @@ -340,6 +342,12 @@ class WordStyles: 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} + # Container typography is inherited by li; a declaration on li + # wins over that inherited value. A direct blockquote p rule wins + # again. Preserve this distinction from the original CSS cascade. + overrides = {field: value for field, value in self.explicit[target].items() + if field in self.rules.get('_quote_container', {})} + rule.update(overrides) # Keep the list's marker layout as context-specific paragraph # properties; quote typography remains inherited from its style. if level: @@ -353,7 +361,7 @@ class WordStyles: 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) + _delta(props, old, overrides) return identifier def table_column(self, target, alignment): @@ -462,6 +470,7 @@ class WordStyles: loose = bool(names & set(SOURCE_PARAGRAPH_STYLES)) target = self.classify(paragraph, original_id) identifier = self.paragraph(target) + if continuation and target == 'blockquote': remove_fields(ppr, ('numPr',)) if target.startswith('list_'): numpr = ppr.find(W + 'numPr') self.inherit_list_indents(numpr) diff --git a/mdhelper/markdown_renderer.py b/mdhelper/markdown_renderer.py index 578c902..979207f 100644 --- a/mdhelper/markdown_renderer.py +++ b/mdhelper/markdown_renderer.py @@ -752,7 +752,11 @@ class MarkdownRenderer: font_size = max(12, min(int(document_font_size or fallback_font_size), 28)) font_family = self._css_font_family(document_font_family) escaped_font_family = html.escape(font_family, quote=False) + from .reader_decoration import MARKER, wrap_decoration_text + leaf_decorations = MARKER in document_style_css + if leaf_decorations: body = wrap_decoration_text(body) reader_shell = self._reader_shell_html(body) + if leaf_decorations: reader_shell = reader_shell.replace('
diff --git a/mdhelper/reader_decoration.py b/mdhelper/reader_decoration.py new file mode 100644 index 0000000..c3c63fb --- /dev/null +++ b/mdhelper/reader_decoration.py @@ -0,0 +1,113 @@ +"""Draw semantic decorations on text, where an inner style can turn them off. + +CSS decorations on an ancestor cannot be cancelled by a descendant. Inline +text spans keep normal wrapping while inherited custom properties carry each +independent decoration to the final text. Raw markup and entities are retained. +""" +from html.parser import HTMLParser + +MARKER = '/* mdhelper:leaf-decorations */' + + +def wrap_decoration_text(body): + class TextLeaves(HTMLParser): + def __init__(self): + super().__init__(convert_charrefs=False) + self.output, self.blocked = [], [] + self.depth = 0 + + def handle_starttag(self, tag, attrs): + self.output.append(self.get_starttag_text()) + if tag in ('area','base','br','col','embed','hr','img','input','link','meta','param','source','track','wbr'): return + self.depth += 1 + classes = dict(attrs).get('class','') or '' + if tag in ('script','style','textarea','svg','math','pre') or 'data-mdh-text' in dict(attrs) or set(classes.split()) & {'mermaid','math-inline','math-block','math-display'}: + self.blocked.append(self.depth) + + def handle_startendtag(self, tag, attrs): self.output.append(self.get_starttag_text()) + + def handle_endtag(self, tag): + self.output.append(f'') + if self.blocked and self.blocked[-1] == self.depth: self.blocked.pop() + self.depth = max(0,self.depth-1) + + def handle_data(self, text): + self.output.append(text if self.blocked or not text.strip() else ''+text+'') + + def handle_entityref(self, name): self.handle_data('&'+name+';') + def handle_charref(self, name): self.handle_data('&#'+name+';') + def handle_comment(self, data): self.output.append('') + def handle_decl(self, data): self.output.append('') + + parser=TextLeaves();parser.feed(body);parser.close() + return ''.join(parser.output) + + +def decoration_css(rules, inherited, selectors, source): + from .style_catalog import CHARACTER_DEFAULTS, CATALOG + if not any(CATALOG.get(key) and CATALOG[key].kind == 'character' and + any(rule.get(field) is False for field in ('underline','strike')) + for key,rule in rules.items() if isinstance(rule,dict)): + return source + root='.reader[data-mdh-leaf-decoration]' + parts=[MARKER, root+' { --mdh-line-underline: ; --mdh-line-strike: ; }'] + suppress=[] + for key,selector in selectors.items(): + if key == 'code_block': continue # Code blocks have no Markdown inline nesting. + if key == 'code': selector='.reader code:not(:where(pre code))' + own={**inherited.get(key,{}), **rules.get(key,{})} + defaults=CHARACTER_DEFAULTS.get(key,{}) + rule={**defaults, **own} + fields=[(field,token) for field,token in (('underline','underline'),('strike','line-through')) if field in rule] + if not fields: continue + # Reader-only companion rules; the original CSS remains editable. + suppress.append(selector.replace('.reader',root)) + for field,token in fields: + # Defaults have zero specificity; authored conditional selectors + # can continue to change decorations (including hover effects). + scope=selector if field in own else ':where('+selector+')' + parts.append(scope+' { --mdh-decoration-raw: initial; --mdh-line-'+field+': '+(token if rule[field] else '')+'; }') + parts.append(_decoration_variables(source)) + parts.append(', '.join(suppress)+' { text-decoration-line: none !important; }') + parts.append(':where('+root+' p, '+root+' strong, '+root+' em, '+root+' a, '+root+' s, '+root+' del, '+root+' code) { text-decoration-color: inherit; text-decoration-style: inherit; text-decoration-thickness: inherit; }') + parts.append(root+' [data-mdh-text] { text-decoration-line: var(--mdh-decoration-raw, var(--mdh-line-underline) var(--mdh-line-strike)); text-decoration-color: inherit; text-decoration-style: inherit; text-decoration-thickness: inherit; }') + return '\n'.join(parts) + + +def _decoration_variables(source): + """Keep authored selectors, conditions, priority and decoration appearance.""" + import tinycss2 as css + from .style_sync import DECORATION_EXPRESSION + def visit(nodes): + for node in nodes: + if node.type=='at-rule' and node.content is not None and node.lower_at_keyword in ('media','supports','layer','container'): + children=css.parse_stylesheet(node.content);visit(children) + node.content=css.parse_component_value_list(css.serialize(children)) + elif node.type=='qualified-rule': + declarations=css.parse_declaration_list(node.content,skip_whitespace=False,skip_comments=False) + output=[] + for declaration in declarations: + output.append(declaration) + if declaration.type!='declaration':continue + value=css.serialize(declaration.value).strip() + suffix=' !important' if declaration.important else '' + if declaration.name in ('--mdhelper-underline','--mdhelper-strike') and value in ('true','false'): + field=declaration.name.removeprefix('--mdhelper-') + token=('underline' if field=='underline' else 'line-through') if value=='true' else '' + output.extend(css.parse_declaration_list(f'--mdh-decoration-raw:initial{suffix};--mdh-line-{field}:{token}{suffix};')) + continue + if declaration.lower_name not in ('text-decoration','text-decoration-line'):continue + if value==DECORATION_EXPRESSION:continue + tokens=[t.lower_value for t in declaration.value if t.type=='ident'] + lines=set(tokens)&{'none','underline','line-through','overline'} + if lines and not ('none' in lines and len(lines)>1): + values={'--mdh-decoration-raw':'initial','--mdh-line-underline':'underline' if 'underline' in lines else '', + '--mdh-line-strike':'line-through' if 'line-through' in lines else ''} + if 'overline' in lines:values['--mdh-decoration-raw']=' '.join(x for x in ('underline','line-through','overline') if x in lines) + elif declaration.lower_name=='text-decoration-line' and any(t.type=='function' for t in declaration.value): + values={'--mdh-decoration-raw':value} + else:continue + output.extend(css.parse_declaration_list(''.join(f'{prop}:{val}{suffix};' for prop,val in values.items()))) + node.content=css.parse_component_value_list(css.serialize(output)) + nodes=css.parse_stylesheet(source);visit(nodes) + return css.serialize(nodes) diff --git a/mdhelper/resources/reader.css b/mdhelper/resources/reader.css index b1a1002..5ef421a 100644 --- a/mdhelper/resources/reader.css +++ b/mdhelper/resources/reader.css @@ -270,6 +270,7 @@ table { :where(html[data-theme="dark"]) .reader { --reader-table-stripe: #252c37; + --reader-table-header: #2b3340; } :where(html[data-theme="dark"]) .copy-table-button { diff --git a/mdhelper/resources/reader.js b/mdhelper/resources/reader.js index 6689e0e..963b249 100644 --- a/mdhelper/resources/reader.js +++ b/mdhelper/resources/reader.js @@ -120,21 +120,7 @@ document.addEventListener("DOMContentLoaded", () => { button.textContent = "复制"; button.addEventListener("click", async () => { - const text = rawText; - try { - await navigator.clipboard.writeText(text); - button.textContent = "已复制"; - } catch (error) { - const textarea = document.createElement("textarea"); - textarea.value = text; - textarea.style.position = "fixed"; - textarea.style.left = "-9999px"; - document.body.appendChild(textarea); - textarea.select(); - document.execCommand("copy"); - textarea.remove(); - button.textContent = "已复制"; - } + button.textContent = await copyText(rawText) ? "已复制" : "复制失败,请重试"; window.setTimeout(() => { button.textContent = "复制"; }, 1200); @@ -173,20 +159,26 @@ document.addEventListener("DOMContentLoaded", () => { }, 700); }); - const copyText = async (text) => { + async function copyText(text) { try { await navigator.clipboard.writeText(text); + return true; } catch (error) { + const focused = document.activeElement; const textarea = document.createElement("textarea"); textarea.value = text; textarea.style.position = "fixed"; textarea.style.left = "-9999px"; document.body.appendChild(textarea); textarea.select(); - document.execCommand("copy"); - textarea.remove(); + try { return document.execCommand("copy"); } + catch (fallbackError) { return false; } + finally { + textarea.remove(); + focused?.focus({ preventScroll: true }); + } } - }; + } document.querySelectorAll(".reader table").forEach((table) => { if (table.closest(".table-wrapper")) { @@ -213,13 +205,12 @@ document.addEventListener("DOMContentLoaded", () => { copyButton.title = "复制表格"; copyButton.addEventListener("click", async () => { - const rows = [...table.querySelectorAll("tr")].map((row) => - [...row.querySelectorAll("th, td")] + const rows = [...table.rows].map((row) => + [...row.cells] .map((cell) => (cell.innerText || cell.textContent || "").replace(/\s+/g, " ").trim()) .join("\t") ); - await copyText(rows.join("\n")); - copyButton.textContent = "已复制"; + copyButton.textContent = await copyText(rows.join("\n")) ? "已复制" : "复制失败,请重试"; window.setTimeout(() => { copyButton.textContent = "复制表格"; }, 1200); diff --git a/mdhelper/resources/word_inline_styles.lua b/mdhelper/resources/word_inline_styles.lua index f13cd6b..75694bf 100644 --- a/mdhelper/resources/word_inline_styles.lua +++ b/mdhelper/resources/word_inline_styles.lua @@ -57,6 +57,11 @@ local function list_paragraphs(list) return list end local function quoted_paragraphs(quote) + for index, block in ipairs(quote.content) do + if block.t == 'Para' or block.t == 'Plain' then + quote.content[index] = pandoc.Div({block}, pandoc.Attr('', {}, {['custom-style']='MDHelperSourceInnerQuote'})) + end + end return quote:walk({Div=function(block) if block.attributes['custom-style'] == 'MDHelperSourceListParagraph' then block.attributes['custom-style'] = 'MDHelperSourceQuotedListParagraph' diff --git a/mdhelper/style_panel.py b/mdhelper/style_panel.py index 4e3dcc8..8095654 100644 --- a/mdhelper/style_panel.py +++ b/mdhelper/style_panel.py @@ -51,7 +51,7 @@ class StylePanel(QDockWidget): active = next((region for region in reversed(self.regions) if region.start <= line < region.end), None) self.current.setText(('当前段落:' + style_name(active.style, rules) + ('\n包含:' + '、'.join(style_name(k, rules) for k in active.characters) if active.characters else '')) if active else '阅读模式:双击条目修改统一外观。') - listing_key = (key, repr(rules), window.document_font_size, window.document_font_family, self.filter.currentIndex()) + listing_key = (key, repr(rules), window.document_style_id, window.document_font_size, window.document_font_family, self.filter.currentIndex()) if force or listing_key != self.list_key: selected = self.listing.currentItem().data(Qt.ItemDataRole.UserRole) if self.listing.currentItem() else None self.listing.clear() diff --git a/mdhelper/style_sync.py b/mdhelper/style_sync.py index a99e19f..5d083dc 100644 --- a/mdhelper/style_sync.py +++ b/mdhelper/style_sync.py @@ -250,6 +250,17 @@ def _invalid_core_value(prop, tokens): # 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 + if prop in ('color','background-color','border-color') and len(tokens) == 1: + token=tokens[0] + if token.type != 'function': return parse_color(token) is None + if prop == 'font-style' and len(tokens) > 1: + return not (len(tokens)==2 and tokens[0].type=='ident' and tokens[0].lower_value=='oblique' + and tokens[1].type=='dimension' and tokens[1].lower_unit in ('deg','grad','rad','turn')) + if prop == 'font': + if len(tokens)==1: + return not (tokens[0].type=='ident' and tokens[0].lower_value in ('caption','icon','menu','message-box','small-caption','status-bar')) + # Valid but unsupported shorthands still reset the core font fields. + 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 @@ -261,6 +272,7 @@ def _invalid_core_value(prop, tokens): 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] + if token.type == 'string' and prop != 'font-family' and not prop.startswith('--'): return True wide = {'inherit', 'initial', 'unset', 'revert', 'revert-layer'} if token.type == 'ident' and token.lower_value in wide: return False lengths = {'font-size', 'line-height', 'letter-spacing', 'text-indent', 'padding', 'border-width', @@ -324,7 +336,7 @@ def _collect_cascade(source: str, result: Analysis): result.errors.append(f"第 {raw.source_line} 行:{raw.name} 缺少属性值。") continue expanded = _expand(raw) - if any(d.type == 'declaration' and _property(d) in CORE_PROPERTIES and + if any(d.type == 'declaration' and (_property(d) in CORE_PROPERTIES or _property(d)=='font') and _invalid_core_value(_property(d), d.value) for d in expanded): # One invalid component invalidates the entire shorthand. result.notes.append(f'已忽略无效的 {raw.lower_name}: {_text(raw.value)},沿用前面的有效声明') @@ -535,6 +547,10 @@ def analyze_css(source: str, font_size_px: float = 16) -> Analysis: rule = {field: value for field, value in rule.items() if field in owned} if rule: result.rules[target] = rule + if target == 'blockquote': + container = {prop: entry for prop, entry in entries.items() if not entry[0][0]} + inherited = _CoreRuleReader(target, container, result, font_size_px).parse() + if inherited: result.rules['_quote_container'] = inherited result.notes = list(dict.fromkeys(result.notes)) return result @@ -659,12 +675,20 @@ def render_css(source: str, rules: dict, font_family: str = '', font_size_px: fl inherited = explicit_rules(rules) from .document_style import resolved_rules effective = resolved_rules(rules, font_family, font_size_px, preset) + winners = _collect_cascade(source, Analysis()) + def priority(declarations, entries): + important_groups = {g for g, props in PROPERTIES.items() if any(p in entries and entries[p][0][1] for p in props)} + return [d.rstrip(';')+' !important;' if any(d.split(':',1)[0] in PROPERTIES[g] for g in important_groups) else d for d in declarations] for key, metadata in normalize_metadata(rules.get('_metadata')).items(): 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') + inherited[key].update(underline=False, strike=False) + if key == 'inline_code': inherited[key]['background_color'] = 'transparent' + elif 'background_color' in rules.get('table', {}): + inherited[key]['background_color'] = ('var(--reader-table-header, #f1f5f9)' if key == 'table_head' + else 'var(--mdhelper-cell-fill, transparent)') if not metadata['based_on'] and CATALOG[key].base: legacy = rules.get(CATALOG[key].base, {}) defaults = {'underline': False, 'strike': False, 'background_color': 'transparent', @@ -674,11 +698,17 @@ def render_css(source: str, rules: dict, font_family: str = '', font_size_px: fl 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, reset_list_paragraphs=False) - helpers += '\n' + table_helper_css(rules.get('table', {})) + helpers += '\n' + table_helper_css(rules.get('table', {}), any( + winners['table'].get(p, ((False,False),))[0][1] for p in PROPERTIES['border_style'])) # 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(): declarations = _core_declarations(rule) + if str(rule.get('background_color', '')).startswith('var('): + declarations.append('background-color: '+rule['background_color']+';') + entries = winners.get(key, {}) + if key == 'inline_code': entries = {**winners.get('code', {}), **entries} + declarations = priority(declarations, entries) if declarations: helpers += '\n' + SELECTORS[key] + ' { ' + ' '.join(declarations) + ' }' for key in ('table_head', 'table_cell'): rule = {**inherited.get(key, {}), **rules.get(key, {})} @@ -697,7 +727,7 @@ def render_css(source: str, rules: dict, font_family: str = '', font_size_px: fl 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) + ' }' + if propagated: helpers += '\n' + block_selector + ' { ' + ' '.join(priority(propagated, winners.get('code_block', {}))) + ' }' 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 = {} @@ -720,7 +750,8 @@ def render_css(source: str, rules: dict, font_family: str = '', font_size_px: fl 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() + from .reader_decoration import decoration_css + return decoration_css(rules, inherited, SELECTORS, (helpers.strip() + "\n\n" + source).strip()).strip() def normalize_payload(payload: dict, fallback_name="自定义样式", font_size_px=16) -> dict: diff --git a/mdhelper/table_style.py b/mdhelper/table_style.py index a16da91..e6b061b 100644 --- a/mdhelper/table_style.py +++ b/mdhelper/table_style.py @@ -15,18 +15,19 @@ BORDER_COLOR = '#d5dbe5' VERTICAL_BORDER_COLOR = '#e8ecf2' -def table_helper_css(rule): +def table_helper_css(rule, important=False): """Companion rules for options that affect descendants of the table.""" parts = [] selector = '.reader table[data-mdh-table]' mode = rule.get('table_border_mode') if mode in ('horizontal', 'none'): declarations = 'border-style: none;' if mode == 'none' else 'border-left-style: none; border-right-style: none;' + if important: declarations = declarations.replace(';', ' !important;') parts.append(f'{selector}, {selector} th, {selector} td {{ {declarations} }}') if rule.get('table_banded_rows'): color = rule.get('table_stripe_color', 'var(--reader-table-stripe, #f8fafc)') # Low specificity lets explicit cell backgrounds remain authoritative. - parts.append(f':where(.reader table) tbody tr:where(:nth-child(even)) td {{ background-color: {color}; }}') + parts.append(f':where(.reader table tbody tr:nth-child(even)) td {{ --mdhelper-cell-fill: {color}; background-color: {color}; }}') if 'table_repeat_header' in rule: display = 'table-header-group' if rule['table_repeat_header'] else 'table-row-group' parts.append(f'{selector} thead {{ display: {display}; }}') diff --git a/tests/test_style_regressions.py b/tests/test_style_regressions.py index b45385d..6d688bb 100644 --- a/tests/test_style_regressions.py +++ b/tests/test_style_regressions.py @@ -148,7 +148,7 @@ def test_reader_nested_list_indent_uses_own_core_setting(qt_application, tmp_pat def test_decoration_shorthand_obeys_cascade_in_browser_controls_and_word(qt_application, tmp_path, css, expected): payload = normalize_payload({'css': css}) assert payload['rules']['link']['underline'] is expected - actual = browser(qt_application, tmp_path, payload, '[Link](#link)', "getComputedStyle(document.querySelector('p a')).textDecorationLine") + actual = browser(qt_application, tmp_path, payload, '[Link](#link)', "getComputedStyle(document.querySelector('p a [data-mdh-text]') || document.querySelector('p a')).textDecorationLine") assert ('underline' in actual) is expected dialog = DocumentStyleEditorDialog(payload) try: diff --git a/tests/test_style_revision_054.py b/tests/test_style_revision_054.py index 26a0ec9..123f1b8 100644 --- a/tests/test_style_revision_054.py +++ b/tests/test_style_revision_054.py @@ -7,6 +7,7 @@ from mdhelper.docx_style import W, NS from mdhelper.style_sync import normalize_payload from test_style_regressions import browser, parts from docx_assertions import effective_document +from mdhelper.style_dialog import DocumentStyleEditorDialog ENGINES = ('builtin', 'python-docx', 'pandoc') TABLE = '| Head | Description |\n|---|---|\n| Alpha | First |\n| Beta | Second |' @@ -74,3 +75,172 @@ def test_legacy_code_uses_linked_editable_word_base(tmp_path, engine): inline = styles.find("w:style[@w:styleId='MDHelperInlineCode']",NS) assert inline.find(W+'basedOn').get(W+'val') == 'MDHelperCodeChar' assert inline.find('w:rPr/w:color',NS) is None + + +@pytest.mark.parametrize('engine',ENGINES) +def test_legacy_code_can_still_request_surrounding_color(tmp_path,engine): + rules={**CODE_RULES,'paragraph':{'font_color':'#008000'},'inline_code':{'font_color':'inherit'}} + doc,styles=parts(export_markdown_to_docx(CODE_SOURCE,tmp_path/'context-code.docx',engine=engine,style_rules=rules)) + run=next(r for r in effective_document(doc,styles).iter(W+'r') if ''.join(r.itertext())=='Inline') + assert run.find('w:rPr/w:color',NS).get(W+'val')=='008000' + assert styles.find("w:style[@w:styleId='MDHelperInlineCode']/w:basedOn",NS) is None + + +def test_graphical_table_layout_overrides_important_legacy_border(qt_application,tmp_path): + dialog=DocumentStyleEditorDialog({'css':'table,th,td {border-style:solid!important;border-width:2pt;border-color:red;}'}) + try: + dialog.select_target('table') + for mode,expected in [('none',['none','none']),('horizontal',['none','solid']),('grid',['solid','solid'])]: + dialog.table_border_mode_box.setCurrentIndex(dialog.table_border_mode_box.findData(mode)) + payload=dialog.style_payload() + assert normalize_payload(payload)==payload + assert browser(qt_application,tmp_path,payload,TABLE,"(()=>{const s=getComputedStyle(document.querySelector('td'));return [s.borderLeftStyle,s.borderTopStyle]})()") == expected + finally:dialog.close() + + +@pytest.mark.parametrize('background',['#ffeecc','transparent']) +def test_bare_cell_css_wins_over_optional_stripes(qt_application,tmp_path,background): + payload=normalize_payload({'css':f'table {{ --mdhelper-table-banded-rows:true; }} td {{background-color:{background};}}'}) + colors=browser(qt_application,tmp_path,payload,TABLE,"[...document.querySelectorAll('tbody td')].map(e=>getComputedStyle(e).backgroundColor)") + assert len(set(colors))==1 + for engine in ENGINES: + _,styles=parts(export_markdown_to_docx(TABLE,tmp_path/f'{engine}.docx',engine=engine,style_rules=payload['rules'])) + for band in ('band1Horz','band2Horz'): + shade=styles.find(f"w:style[@w:styleId='MDHelperTable']/w:tblStylePr[@w:type='{band}']/w:tcPr/w:shd",NS) + assert shade.get(W+'fill') == ('auto' if background=='transparent' else background[1:]) + + +@pytest.mark.parametrize('legacy',['','table,th,td {background-color:red!important;color:red!important;}']) +def test_detached_table_text_preserves_table_decoration(qt_application,tmp_path,legacy): + dialog=DocumentStyleEditorDialog({'css':legacy+' table {--mdhelper-table-banded-rows:true;}'}) + try: + for target in ('table_head','table_cell'): + dialog.select_target(target);dialog.based_on_box.setCurrentIndex(dialog.based_on_box.findData('')) + payload=dialog.style_payload() + actual=browser(qt_application,tmp_path,payload,TABLE,"[...document.querySelectorAll('tr > :first-child')].map(e=>{const s=getComputedStyle(e);return [s.backgroundColor,s.color]})") + assert [r[0] for r in actual]==['rgb(241, 245, 249)','rgba(0, 0, 0, 0)','rgb(248, 250, 252)'] + assert all(r[1]!='rgb(255, 0, 0)' for r in actual) + finally:dialog.close() + + +def test_important_code_css_respects_graphical_child_and_detachment(qt_application,tmp_path): + dialog=DocumentStyleEditorDialog({'css':'pre,code {color:red!important;}'}) + try: + dialog.select_target('code_block');dialog.color_combo.setCurrentIndex(dialog.color_combo.findData('custom')) + dialog.color_button.setText('#0000ff');dialog._store_and_refresh() + dialog.select_target('inline_code');dialog.based_on_box.setCurrentIndex(dialog.based_on_box.findData('')) + payload=dialog.style_payload() + colors=browser(qt_application,tmp_path,payload,CODE_SOURCE,"[...document.querySelectorAll('code')].map(e=>getComputedStyle(e).color)") + assert colors[0]!='rgb(255, 0, 0)' and colors[1]=='rgb(0, 0, 255)' + for engine in ENGINES: + doc,styles=parts(export_markdown_to_docx(CODE_SOURCE,tmp_path/f'{engine}.docx',engine=engine,style_rules=payload['rules'])) + actual={''.join(p.itertext()):p.find('.//w:rPr/w:color',NS).get(W+'val') for p in effective_document(doc,styles).iter(W+'p')} + assert actual['Inline']!='ff0000' and actual['Block']=='0000ff' + finally:dialog.close() + + +@pytest.mark.parametrize('bad',['color:#gggggg','color:12pt','font-size:"10pt"','font-style:italic normal','font:garbage','text-align:"left"']) +def test_invalid_css_keeps_last_valid_core_values(qt_application,tmp_path,bad): + payload=normalize_payload({'css':'p {color:red;font-size:20pt;font-style:italic;text-align:center;'+bad+';}'}) + rule=payload['rules']['paragraph'] + assert rule['font_color']=='#ff0000' and rule['font_size']==20 and rule['italic'] and rule['alignment']=='center' + assert browser(qt_application,tmp_path,payload,'Fallback',"(()=>{const s=getComputedStyle(document.querySelector('p'));return [s.color,s.fontStyle,s.textAlign]})()") == ['rgb(255, 0, 0)','italic','center'] + + +@pytest.mark.parametrize('engine',ENGINES) +def test_inner_quote_and_container_list_cascade(tmp_path,engine): + source='- Item\n\n > Quote\n\n- Second' + rules={'blockquote':{'font_color':'#ff0000'},'list_bullet':{'font_color':'#0000ff'}} + doc,styles=parts(export_markdown_to_docx(source,tmp_path/'inner.docx',engine=engine,style_rules=rules)) + actual={''.join(p.itertext()):p.find('.//w:rPr/w:color',NS).get(W+'val') for p in effective_document(doc,styles).iter(W+'p')} + assert actual=={'Item':'0000ff','Quote':'ff0000','Second':'0000ff'} + styles.find("w:style[@w:styleId='MDHelperBlockquote']/w:rPr/w:color",NS).set(W+'val','008000') + quote=next(p for p in effective_document(doc,styles).iter(W+'p') if ''.join(p.itertext())=='Quote') + assert quote.find('.//w:rPr/w:color',NS).get(W+'val')=='008000' + for css,color in [('blockquote {color:red;} li {color:blue;}','0000ff'),('blockquote p {color:red;} li {color:blue;}','ff0000')]: + payload=normalize_payload({'css':css}) + doc,styles=parts(export_markdown_to_docx('> - First\n>\n> - Second',tmp_path/'outer.docx',engine=engine,style_rules=payload['rules'])) + assert all(p.find('.//w:rPr/w:color',NS).get(W+'val')==color for p in effective_document(doc,styles).iter(W+'p')) + + +def test_nested_decoration_cancellation_and_wrapping(qt_application,tmp_path): + rules={'strong':{'underline':True,'strike':True},'emphasis':{'underline':False}} + payload=normalize_payload({'rules':rules}) + source='**Outer *Inner words still wrap* outer**' + actual=browser(qt_application,tmp_path,payload,source,"""(()=>{ + const p=document.querySelector('p');p.style.width='80px'; + return {leaves:[...p.querySelectorAll('[data-mdh-text]')].map(e=>[e.textContent,getComputedStyle(e).textDecorationLine]), + outer:getComputedStyle(p.querySelector('strong')).textDecorationLine, + inner:getComputedStyle(p.querySelector('em')).textDecorationLine, width:p.scrollWidth}; + })()""") + assert actual['outer']=='none' and actual['inner']=='none' + assert actual['leaves']==[['Outer ','underline line-through'],['Inner words still wrap','line-through'],[' outer','underline line-through']] + assert actual['width']<=81 + for engine in ENGINES: + doc,styles=parts(export_markdown_to_docx(source,tmp_path/f'{engine}.docx',engine=engine,style_rules=payload['rules'])) + run=next(r for r in effective_document(doc,styles).iter(W+'r') if ''.join(r.itertext())=='Inner words still wrap') + assert run.find('w:rPr/w:u',NS).get(W+'val')=='none' + assert run.find('w:rPr/w:strike',NS).get(W+'val')=='1' + + +def test_switching_builtin_preset_refreshes_style_panel(qt_application,tmp_path,monkeypatch): + from PySide6.QtCore import QSettings,Qt + from mdhelper import main_window + monkeypatch.setattr(main_window,'QSettings',lambda *_:QSettings(str(tmp_path/'settings.ini'),QSettings.Format.IniFormat)) + window=main_window.MainWindow(None,app_root=tmp_path) + try: + window._set_document_style('default');window.show_style_panel();panel=window.style_panel;panel.refresh(force=True) + window._set_document_style('serif');panel.refresh() + item=next(panel.listing.item(i) for i in range(panel.listing.count()) if panel.listing.item(i).data(Qt.ItemDataRole.UserRole)=='paragraph') + assert item.font().family()=='SimSun' + finally:window.close() + + +def test_text_decoration_keeps_code_math_entities_and_raw_content(qt_application,tmp_path): + from mdhelper.reader_decoration import wrap_decoration_text + raw='
<x>\nline 2
x & y
A --> B
' + assert wrap_decoration_text(raw)==raw + wrapped=wrap_decoration_text('

A & B C

') + assert wrap_decoration_text(wrapped)==wrapped + payload=normalize_payload({'rules':{'strong':{'underline':True},'emphasis':{'underline':False},'code_block':{'underline':True}}}) + assert browser(qt_application,tmp_path,payload,'**Outer *Inner***\n\n```text\nCode\n```', + "getComputedStyle(document.querySelector('pre')).textDecorationLine")=='underline' + + +@pytest.mark.parametrize('conditional',[False,True]) +def test_nested_decoration_preserves_advanced_css_effects(qt_application,tmp_path,conditional): + css='strong {text-decoration:underline;} em {text-decoration:none;} .reader a {text-decoration:line-through wavy red;}' + if conditional:css+=' @media screen {.reader a {text-decoration-line:underline;}}' + payload=normalize_payload({'css':css}) + assert browser(qt_application,tmp_path,payload,'**Outer *Inner*** [Decor](#link)', + "(()=>{const s=getComputedStyle(document.querySelector('a [data-mdh-text]'));return [s.textDecorationLine,s.textDecorationStyle,s.textDecorationColor]})()") == ['underline' if conditional else 'line-through','wavy','rgb(255, 0, 0)'] + + +@pytest.mark.parametrize('kind',['table','code','nested']) +@pytest.mark.parametrize('success',[False,True]) +def test_copy_buttons_report_failure_and_copy_only_own_cells(qt_application,tmp_path,kind,success): + import json,time + from PySide6.QtWebEngineCore import QWebEnginePage + from mdhelper.markdown_renderer import MarkdownRenderer + page=QWebEnginePage();loaded=[] + def wait(condition): + end=time.monotonic()+15 + while not condition() and time.monotonic()Outer
InnerAInnerB
Last' if kind=='nested' else TABLE + selector='.copy-code-button' if kind=='code' else '.copy-table-button' + try: + page.loadFinished.connect(loaded.append);page.setHtml(MarkdownRenderer(tmp_path).render_source(source,tmp_path/'copy.md'));wait(lambda:loaded) + js("(()=>{Object.defineProperty(navigator,'clipboard',{value:{writeText:async()=>{throw Error('denied')}}});document.execCommand=()=>{window.copied=document.querySelector('textarea').value;return "+str(success).lower()+"};document.querySelector('"+selector+"').click();return true})()") + wait(lambda:js("document.querySelector('"+selector+"').textContent") in ('已复制','复制失败,请重试')) + assert js("document.querySelector('"+selector+"').textContent")==('已复制' if success else '复制失败,请重试') + copied=js('window.copied') + if kind=='nested': + assert copied.count('InnerA')==1 and copied.count('InnerB')==1 + assert len(copied.split('\n'))==1 and len(copied.split('\t'))==2 + elif kind=='code':assert copied.strip()=='Block' + else:assert copied=='Head\tDescription\nAlpha\tFirst\nBeta\tSecond' + assert js("document.querySelectorAll('textarea').length")==0 + finally:page.deleteLater() diff --git a/tests/word_revision_054_smoke.ps1 b/tests/word_revision_054_smoke.ps1 index 21b7295..0ffe671 100644 --- a/tests/word_revision_054_smoke.ps1 +++ b/tests/word_revision_054_smoke.ps1 @@ -10,7 +10,14 @@ sys.path.insert(0,str(Path('tests').resolve())) from test_style_revision_054 import * folder=Path(tempfile.mkdtemp(prefix='MDHelper-054-Word-')) for engine in ENGINES: - for name,source,rules in [('code',CODE_SOURCE,CODE_RULES),('continuation',CONTINUATION_SOURCE,{}),('nested',NESTED_SOURCE,NESTED_RULES),('background',TABLE,BACKGROUND_RULES)]: + for name,source,rules in [('code',CODE_SOURCE,CODE_RULES),('continuation',CONTINUATION_SOURCE,{}),('nested',NESTED_SOURCE,NESTED_RULES),('background',TABLE,BACKGROUND_RULES), + ('inner-quote','- Item\n\n > Quote\n\n- Second',{'blockquote':{'font_color':'#ff0000'},'list_bullet':{'font_color':'#0000ff'}}), + ('container-quote','> - First\n>\n> - Second',normalize_payload({'css':'blockquote {color:red;} li {color:blue;}'})['rules']), + ('decoration','**Outer *Inner* outer**',{'strong':{'underline':True,'strike':True},'emphasis':{'underline':False}}), + ('invalid','Fallback',normalize_payload({'css':'p {color:red;font-size:20pt;font-style:italic;color:#gggggg;font-size:"10pt";font-style:italic normal;font:garbage;}'})['rules']), + ('cell-fill',TABLE,normalize_payload({'css':'table {--mdhelper-table-banded-rows:true;} td {background-color:#ffeecc;}'})['rules']), + ('detached',TABLE,{'table':{'table_banded_rows':True},'_metadata':{'table_head':{'based_on':''},'table_cell':{'based_on':''}}}), + ('context-code',CODE_SOURCE,{**CODE_RULES,'paragraph':{'font_color':'#008000'},'inline_code':{'font_color':'inherit'}})]: export_markdown_to_docx(source,folder/f'{engine}-{name}.docx',engine=engine,style_rules=rules) print(folder) '@ | & $Python -B -).Trim() @@ -19,7 +26,7 @@ print(folder) $word.Visible=$false $word.DisplayAlerts=0 foreach($engine in @('builtin','python-docx','pandoc')) { - foreach($case in @('code','continuation','nested','background')) { + foreach($case in @('code','continuation','nested','background','inner-quote','container-quote','decoration','invalid','cell-fill','detached','context-code')) { $doc=$word.Documents.Open((Join-Path $folder "$engine-$case.docx"),$false,$true) try { if($case -eq 'code') { @@ -40,7 +47,7 @@ print(folder) $range=$doc.Content.Duplicate;[void]$range.Find.Execute($pair[0]) if([Math]::Abs($range.ParagraphFormat.LeftIndent-$pair[1]) -gt 0.1){throw "$engine $($pair[0]) wrong indent: $($range.ParagraphFormat.LeftIndent)"} } - } else { + } elseif($case -eq 'background') { $table=$doc.Tables.Item(1) $table.Style.Table.Condition(0).Shading.BackgroundPatternColor=65535 if($table.Cell(1,1).Shading.BackgroundPatternColor -ne 65535){throw "$engine table style cannot change header"} @@ -48,6 +55,28 @@ print(folder) $range=$table.Cell($row,1).Range.Duplicate;$range.End=$range.End-1 if($range.ParagraphFormat.Shading.BackgroundPatternColor -ne -16777216){throw "$engine inherited paragraph shading remains"} } + } elseif($case -eq 'inner-quote') { + $range=$doc.Content.Duplicate;[void]$range.Find.Execute('Quote') + if($range.Font.Color -ne 255 -or $range.ListFormat.ListString.Trim() -ne ''){throw "$engine lost inner quote style or added a bullet"} + $range.Style.Font.Color=65280 + if($range.Font.Color -ne 65280){throw "$engine quote style edit blocked"} + } elseif($case -eq 'container-quote') { + $range=$doc.Content.Duplicate;[void]$range.Find.Execute('First') + if($range.Font.Color -ne 16711680){throw "$engine inherited container color overrides list color"} + } elseif($case -eq 'decoration') { + $range=$doc.Content.Duplicate;[void]$range.Find.Execute('Inner') + if($range.Font.Underline -ne 0 -or $range.Font.StrikeThrough -ne -1 -or $range.Font.Bold -ne -1 -or $range.Font.Italic -ne -1){throw "$engine nested decoration or protected emphasis changed"} + } elseif($case -eq 'invalid') { + $range=$doc.Content.Duplicate;[void]$range.Find.Execute('Fallback') + if($range.Font.Color -ne 255 -or $range.Font.Size -ne 20 -or $range.Font.Italic -ne -1){throw "$engine invalid CSS erased valid typography"} + } elseif($case -eq 'cell-fill') { + foreach($row in @(2,3)) {if($doc.Tables.Item(1).Cell($row,1).Shading.BackgroundPatternColor -ne 13430527){throw "$engine explicit cell background lost"}} + } elseif($case -eq 'detached') { + $table=$doc.Tables.Item(1) + if($table.Cell(1,1).Shading.BackgroundPatternColor -ne 16381425 -or $table.Cell(3,1).Shading.BackgroundPatternColor -ne 16579320){throw "$engine detached text lost table decorations"} + } elseif($case -eq 'context-code') { + $range=$doc.Content.Duplicate;[void]$range.Find.Execute('Inline') + if($range.Font.Color -ne 32768){throw "$engine inline code cannot use surrounding color"} } Write-Output "$engine $case passed" } finally {$doc.Close(0);[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc)}