fix: preserve list context and nested CSS decoration behavior
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -15,7 +16,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, INNER_QUOTE_STYLE
|
||||
from .docx_inline import source_style_name, LIST_PARAGRAPH_STYLE, QUOTED_LIST_PARAGRAPH_STYLE, SOURCE_PARAGRAPH_STYLES, CONTINUATION, INNER_QUOTE_STYLE, LIST_TARGET
|
||||
|
||||
|
||||
WP_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
|
||||
@@ -256,6 +257,7 @@ def _add_python_docx_paragraph(document: object, block: ParagraphBlock) -> None:
|
||||
style = name
|
||||
paragraph = document.add_paragraph(style=style)
|
||||
if block.continuation: paragraph._p.set(CONTINUATION, '1')
|
||||
if block.list_target: paragraph._p.set(LIST_TARGET, block.list_target)
|
||||
if block.list_kind:
|
||||
from docx.oxml import parse_xml
|
||||
paragraph._p.get_or_add_pPr().append(parse_xml(f'<w:numPr xmlns:w="{WP_NS}"><w:ilvl w:val="{block.list_level}"/><w:numId w:val="{block.list_id}"/></w:numPr>'))
|
||||
@@ -336,6 +338,7 @@ class ParagraphBlock:
|
||||
alignment: str = ''
|
||||
continuation: bool = False
|
||||
inner_quote: bool = False
|
||||
list_target: str = ''
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -354,6 +357,7 @@ class _DocxBuilder:
|
||||
self.list_starts: list[int] = []
|
||||
self.list_sequence = 1000
|
||||
self.item_pending: list[bool] = []
|
||||
self.item_targets: list[str] = []
|
||||
self.list_quote_depths: list[int] = []
|
||||
self.quote_depth = 0
|
||||
|
||||
@@ -373,8 +377,10 @@ class _DocxBuilder:
|
||||
self.blocks.append(ParagraphBlock([(line, {"code": True})], style="Code"))
|
||||
elif token.type == 'list_item_open':
|
||||
self.item_pending.append(True)
|
||||
self.item_targets.append('list_ordered' if self.list_stack[-1] == 'number' else 'list_bullet')
|
||||
elif token.type == 'list_item_close':
|
||||
self.item_pending.pop()
|
||||
self.item_targets.pop()
|
||||
elif token.type == "blockquote_open":
|
||||
self.quote_depth += 1
|
||||
elif token.type == "blockquote_close":
|
||||
@@ -401,10 +407,13 @@ class _DocxBuilder:
|
||||
def _add_next_inline(self, style: str, list_kind: str = "") -> None:
|
||||
inline = self.tokens[self.index + 1] if self.index + 1 < len(self.tokens) else None
|
||||
runs = _inline_runs(inline.children if inline is not None else None)
|
||||
if list_kind and self.item_pending[-1] and inline is not None:
|
||||
if re.match(r'^\[[ xX]\]\s', inline.content): self.item_targets[-1] = 'list_task'
|
||||
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]),
|
||||
list_target=self.item_targets[-1] if list_kind else '',
|
||||
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
|
||||
@@ -512,7 +521,9 @@ def _paragraph_xml(block: ParagraphBlock) -> str:
|
||||
props.append('<w:ind w:left="720"/>')
|
||||
if block.alignment: props.append(f'<w:jc w:val="{block.alignment}"/>')
|
||||
ppr = f"<w:pPr>{''.join(props)}</w:pPr>" if props else ""
|
||||
marker = ' xmlns:mdh="urn:mdhelper:source" mdh:continuation="1"' if block.continuation else ''
|
||||
marker = ' xmlns:mdh="urn:mdhelper:source"' if block.continuation or block.list_target else ''
|
||||
if block.continuation: marker += ' mdh:continuation="1"'
|
||||
if block.list_target: marker += f' mdh:list-target="{block.list_target}"'
|
||||
return f"<w:p{marker}>{ppr}{''.join(_run_xml(text, style) for text, style in block.runs)}</w:p>"
|
||||
|
||||
|
||||
|
||||
@@ -3,8 +3,12 @@ PREFIX = 'MDHelperSource_'
|
||||
LIST_PARAGRAPH_STYLE = 'MDHelperSourceListParagraph'
|
||||
QUOTED_LIST_PARAGRAPH_STYLE = 'MDHelperSourceQuotedListParagraph'
|
||||
INNER_QUOTE_STYLE = 'MDHelperSourceInnerQuote'
|
||||
SOURCE_PARAGRAPH_STYLES = (LIST_PARAGRAPH_STYLE, QUOTED_LIST_PARAGRAPH_STYLE, INNER_QUOTE_STYLE)
|
||||
LIST_TARGETS = ('list_bullet', 'list_ordered', 'list_task')
|
||||
SOURCE_LIST_STYLES = {base + '_' + target: (base, target)
|
||||
for base in (LIST_PARAGRAPH_STYLE, QUOTED_LIST_PARAGRAPH_STYLE) for target in LIST_TARGETS}
|
||||
SOURCE_PARAGRAPH_STYLES = (LIST_PARAGRAPH_STYLE, QUOTED_LIST_PARAGRAPH_STYLE, INNER_QUOTE_STYLE, *SOURCE_LIST_STYLES)
|
||||
CONTINUATION = '{urn:mdhelper:source}continuation'
|
||||
LIST_TARGET = '{urn:mdhelper:source}list-target'
|
||||
CODES = {'strong': 'B', 'emphasis': 'I', 'strike': 'S', 'link': 'L', 'inline_code': 'C'}
|
||||
|
||||
|
||||
|
||||
+35
-27
@@ -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, INNER_QUOTE_STYLE
|
||||
from .docx_inline import source_style_order, ordered_styles, LIST_PARAGRAPH_STYLE, QUOTED_LIST_PARAGRAPH_STYLE, SOURCE_PARAGRAPH_STYLES, CONTINUATION, INNER_QUOTE_STYLE, LIST_TARGET, LIST_TARGETS, SOURCE_LIST_STYLES
|
||||
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()
|
||||
@@ -327,6 +327,29 @@ class WordStyles:
|
||||
child(style, 'pPr').append(ind)
|
||||
return identifier
|
||||
|
||||
def contextual_list_rule(self, target, own, level):
|
||||
"""Compose a real inner paragraph with its list container geometry."""
|
||||
base = self.effective[target]
|
||||
rule = {**base, **own}
|
||||
for side in ('left', 'right'):
|
||||
field, unit = f'{side}_indent_value', f'{side}_indent_unit'
|
||||
if field not in own and base[unit] == 'em' and font_points(base) == font_points(rule):
|
||||
if side == 'left': rule[field] += level * number(base.get('level_indent', 36)) / font_points(base)
|
||||
continue
|
||||
rule[field] = length_points(base[field], base[unit], font_points(base))
|
||||
if field in own:
|
||||
rule[field] += length_points(own[field], own.get(unit, 'pt'), font_points(rule))
|
||||
if side == 'left': rule[field] += level * number(base.get('level_indent', 36))
|
||||
rule[unit] = 'pt'
|
||||
# text-indent is inherited as a computed length. An inner p's font
|
||||
# must not resize an em indent declared on li. Absolute hanging units
|
||||
# also stop Word's character indent from flattening nested levels.
|
||||
if rule['indent_mode'] in ('hanging', 'first') and rule.get('indent_unit', 'em') == 'em' and (rule['left_indent_unit'] != 'em' or font_points(rule) != font_points(base)):
|
||||
origin = rule if 'indent_mode' in own else base
|
||||
rule['indent_value'] = length_points(rule['indent_value'], 'em', font_points(origin))
|
||||
rule['indent_unit'] = 'pt'
|
||||
return rule
|
||||
|
||||
def list_paragraph(self, target, base_id, level=0):
|
||||
"""A loose Markdown list contains a real p element; a tight one does not."""
|
||||
own = normalize_rule(self.rules.get('_list_paragraph'))
|
||||
@@ -335,25 +358,14 @@ class WordStyles:
|
||||
if identifier not in self.created:
|
||||
style = self.new(identifier, 'paragraph', 'MDHelper ' + style_name(target, self.rules) + '(段落)' + base_id.removeprefix(style_id(target)), base_id)
|
||||
base = self.effective[target]
|
||||
rule = {**base, **own}
|
||||
# A p's margins are inside its li, so they add to the list's
|
||||
# indentation rather than replacing it (including nested levels).
|
||||
for side in ('left', 'right'):
|
||||
field, unit = f'{side}_indent_value', f'{side}_indent_unit'
|
||||
if field in own:
|
||||
rule[field] = length_points(base[field], base[unit], font_points(base)) + length_points(own[field], own.get(unit, 'pt'), font_points(rule))
|
||||
if side == 'left': rule[field] += level * number(base.get('level_indent', 36))
|
||||
rule[unit] = 'pt'
|
||||
if 'left_indent_value' in own and rule['indent_mode'] == 'hanging' and rule.get('indent_unit', 'em') == 'em':
|
||||
# Word otherwise substitutes the character hanging width for
|
||||
# this absolute left margin, flattening nested list levels.
|
||||
rule['indent_value'] = length_points(rule['indent_value'], 'em', font_points(rule))
|
||||
rule['indent_unit'] = 'pt'
|
||||
rule = self.contextual_list_rule(target, own, level)
|
||||
authored = {**own, **{field: rule[field] for field in ('left_indent_unit', 'right_indent_unit', 'indent_unit')
|
||||
if rule.get(field) != base.get(field)}}
|
||||
for tag, writer in (('pPr', _paragraph_properties), ('rPr', _run_properties)):
|
||||
props, old = child(style, tag), ET.Element(W + tag)
|
||||
writer(props, rule); writer(old, base)
|
||||
if tag == 'rPr': remove_fields(props, ('shd',)); remove_fields(old, ('shd',))
|
||||
_delta(props, old, own)
|
||||
_delta(props, old, authored)
|
||||
return identifier
|
||||
|
||||
def quoted_list(self, target, base_id, level):
|
||||
@@ -363,22 +375,12 @@ class WordStyles:
|
||||
quote_id = self.paragraph('blockquote')
|
||||
style = self.new(identifier, 'paragraph', 'MDHelper ' + style_name(target, self.rules) + '(引用内段落)' + (str(level + 1) if level else ''), quote_id)
|
||||
own = self.explicit['blockquote']
|
||||
rule = {**self.effective[target], **normalize_rule(self.rules.get('_list_paragraph')), **own}
|
||||
# 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:
|
||||
points = font_points(rule)
|
||||
offset = level * number(rule.get('level_indent', 36))
|
||||
if rule['left_indent_unit'] == 'em': rule['left_indent_value'] += offset / points
|
||||
else:
|
||||
rule['left_indent_value'] = length_points(rule['left_indent_value'], rule['left_indent_unit'], points) + offset
|
||||
rule['left_indent_unit'] = 'pt'
|
||||
rule = self.contextual_list_rule(target, {**normalize_rule(self.rules.get('_list_paragraph')), **own, **overrides}, level)
|
||||
for tag, writer in (('pPr', _paragraph_properties), ('rPr', _run_properties)):
|
||||
props, old = child(style, tag), ET.Element(W + tag)
|
||||
writer(props, rule); writer(old, self.effective['blockquote'])
|
||||
@@ -486,11 +488,17 @@ class WordStyles:
|
||||
def apply(self, document):
|
||||
for paragraph in document.iter(W + 'p'):
|
||||
continuation = paragraph.attrib.pop(CONTINUATION, '') == '1'
|
||||
list_target = paragraph.attrib.pop(LIST_TARGET, '')
|
||||
ppr = properties(paragraph, 'pPr')
|
||||
original_id = reference(ppr, 'pStyle') or 'Normal'
|
||||
names = {reference(style, 'name') for style in self.chain(original_id)}
|
||||
for name in tuple(names):
|
||||
if name in SOURCE_LIST_STYLES:
|
||||
base, list_target = SOURCE_LIST_STYLES[name]
|
||||
names.add(base)
|
||||
loose = bool(names & set(SOURCE_PARAGRAPH_STYLES))
|
||||
target = self.classify(paragraph, original_id)
|
||||
if target.startswith('list_') and list_target in LIST_TARGETS: target = list_target
|
||||
identifier = self.paragraph(target)
|
||||
if continuation and target == 'blockquote': remove_fields(ppr, ('numPr',))
|
||||
if target.startswith('list_'):
|
||||
|
||||
@@ -47,7 +47,7 @@ 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)):
|
||||
for key,rule in {key: {**inherited.get(key, {}), **rules.get(key, {})} for key in CATALOG}.items()):
|
||||
return source
|
||||
root='.reader[data-mdh-leaf-decoration]'
|
||||
parts=[MARKER, root+' { --mdh-line-underline: ; --mdh-line-strike: ; }']
|
||||
@@ -66,52 +66,54 @@ def decoration_css(rules, inherited, selectors, source):
|
||||
# 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(scope+' { --mdh-decoration-mode: initial; --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; }')
|
||||
# A variable may contain a complete shorthand (including color/style).
|
||||
# Let the browser resolve it on text leaves; an inner core rule resets
|
||||
# the inherited mode so it can still cancel decorations independently.
|
||||
leaf=root+' [data-mdh-text]'
|
||||
parts.append(leaf+' { 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; }')
|
||||
parts.append('@container style(--mdh-decoration-mode: raw) { '+leaf+' { text-decoration: var(--mdh-decoration-shorthand); } }')
|
||||
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
|
||||
from .style_sync import DECORATION_EXPRESSION, _invalid_core_value
|
||||
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_blocks_contents(node.content);visit(children)
|
||||
node.content=css.parse_component_value_list(css.serialize(children))
|
||||
elif node.type=='qualified-rule':
|
||||
declarations=css.parse_blocks_contents(node.content,skip_whitespace=False,skip_comments=False)
|
||||
visit(declarations)
|
||||
output=[]
|
||||
for declaration in declarations:
|
||||
# Invalid declarations have no serializable representation.
|
||||
# Keep valid siblings, including nested qualified rules.
|
||||
if declaration.type=='error': continue
|
||||
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)
|
||||
output=[]
|
||||
for declaration in nodes:
|
||||
if declaration.type=='error': continue
|
||||
if declaration.type=='qualified-rule' or (declaration.type=='at-rule' and declaration.content is not None
|
||||
and declaration.lower_at_keyword in ('media','supports','layer','container')):
|
||||
children=css.parse_blocks_contents(declaration.content,skip_whitespace=False,skip_comments=False)
|
||||
declaration.content=css.parse_component_value_list(css.serialize(visit(children)))
|
||||
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-mode:initial{suffix};--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
|
||||
if _invalid_core_value(declaration.lower_name, declaration.value): continue
|
||||
tokens=[t.lower_value for t in declaration.value if t.type=='ident']
|
||||
lines=set(tokens)&{'none','underline','line-through','overline'}
|
||||
if declaration.lower_name=='text-decoration' and any(t.type=='function' for t in declaration.value):
|
||||
values={'--mdh-decoration-mode':'raw','--mdh-decoration-shorthand':value}
|
||||
elif lines and not ('none' in lines and len(lines)>1):
|
||||
values={'--mdh-decoration-mode':'initial','--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-mode':'initial','--mdh-decoration-raw':value}
|
||||
else:continue
|
||||
output.extend(css.parse_declaration_list(''.join(f'{prop}:{val}{suffix};' for prop,val in values.items())))
|
||||
return output
|
||||
return css.serialize(visit(css.parse_stylesheet(source)))
|
||||
|
||||
@@ -48,9 +48,14 @@ local function mark(items, stack)
|
||||
end
|
||||
local function list_paragraphs(list)
|
||||
for _, item in ipairs(list.content) do
|
||||
local target = list.t == 'OrderedList' and 'list_ordered' or 'list_bullet'
|
||||
local text = pandoc.utils.stringify(item[1] or {})
|
||||
if text:match('^%[[ xX]%]') or text:sub(1, #'☐') == '☐' or text:sub(1, #'☒') == '☒' or text:sub(1, #'☑') == '☑' then
|
||||
target = 'list_task'
|
||||
end
|
||||
for index, block in ipairs(item) do
|
||||
if block.t == 'Para' then
|
||||
item[index] = pandoc.Div({block}, pandoc.Attr('', {}, {['custom-style']='MDHelperSourceListParagraph'}))
|
||||
item[index] = pandoc.Div({block}, pandoc.Attr('', {}, {['custom-style']='MDHelperSourceListParagraph_' .. target}))
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -63,8 +68,9 @@ local function quoted_paragraphs(quote)
|
||||
end
|
||||
end
|
||||
return quote:walk({Div=function(block)
|
||||
if block.attributes['custom-style'] == 'MDHelperSourceListParagraph' then
|
||||
block.attributes['custom-style'] = 'MDHelperSourceQuotedListParagraph'
|
||||
local name = block.attributes['custom-style'] or ''
|
||||
if name:match('^MDHelperSourceListParagraph') then
|
||||
block.attributes['custom-style'] = name:gsub('^MDHelperSourceListParagraph', 'MDHelperSourceQuotedListParagraph')
|
||||
end
|
||||
return block
|
||||
end})
|
||||
|
||||
@@ -425,6 +425,7 @@ class DocumentStyleEditorDialog(QDialog):
|
||||
if hasattr(self.parent(), '_configure_web_settings'):
|
||||
self.parent()._configure_web_settings(self.actual_preview.settings())
|
||||
sample = '# 标题 1 中的 **加粗** 与 [链接](#预览)\n\n## 标题 2\n\n### 标题 3\n\n#### 标题 4\n\n##### 标题 5\n\n###### 标题 6\n\n正文段落:中文与 English,**加粗**、*强调*、~~删除线~~、`inline code`。\n\n第二段文字,用于观察段间距。\n\n> 引用段落中的 **重点**。\n\n- 无序列表\n - 第二级列表\n\n1. 有序列表\n2. 第二项\n\n- [ ] 任务列表\n\n```text\n代码块 code block\n第二行\n```\n\n| 表头 | Heading |\n|---|---|\n| 单元格 | Cell |'
|
||||
sample += '\n| 第二行 | Alternating row |\n| 第三行 | Third row |'
|
||||
parent = self.parent()
|
||||
root = getattr(parent, 'project_root', Path.cwd())
|
||||
content = MarkdownRenderer(root).render_source(sample, root / '__style_preview__.md',
|
||||
|
||||
+36
-1
@@ -11,6 +11,7 @@ import re
|
||||
|
||||
import tinycss2 as css
|
||||
from tinycss2.color3 import parse_color
|
||||
from tinycss2.color4 import parse_color as parse_modern_color
|
||||
|
||||
from .document_style import (STYLE_TARGETS, normalize_rule, css_declarations,
|
||||
build_document_style_css, fmt, font_points, resolved_rules)
|
||||
@@ -253,13 +254,39 @@ def _invalid_core_value(prop, tokens):
|
||||
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 token.lower_name in ('rgb','rgba','hsl','hsla','hwb','lab','lch','oklab','oklch','color'):
|
||||
# Relative colors and math are valid browser expressions that the
|
||||
# scalar color parser cannot evaluate. Preserve those as CSS.
|
||||
if not any(t.type=='function' or t.type=='ident' and t.lower_value=='from' for t in token.arguments):
|
||||
try: return parse_modern_color(token) is None
|
||||
except (ValueError, TypeError): return True
|
||||
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.
|
||||
size_index = next((i for i,t in enumerate(tokens)
|
||||
if t.type in ('dimension','percentage','function') and not (t.type=='dimension' and t.lower_unit in ('deg','grad','rad','turn'))
|
||||
or t.type=='number' and t.value==0
|
||||
or t.type=='ident' and t.lower_value in ('xx-small','x-small','small','medium','large','x-large','xx-large','xxx-large','smaller','larger')), None)
|
||||
if size_index is None or _invalid_core_value('font-size', [tokens[size_index]]): return True
|
||||
prefix_names = {'normal','italic','oblique','small-caps','bold','bolder','lighter',
|
||||
'ultra-condensed','extra-condensed','condensed','semi-condensed',
|
||||
'semi-expanded','expanded','extra-expanded','ultra-expanded'}
|
||||
for token in tokens[:size_index]:
|
||||
if token.type=='ident' and token.lower_value in prefix_names: continue
|
||||
if token.type=='number' and 1 <= token.value <= 1000: continue
|
||||
if token.type=='dimension' and token.lower_unit in ('deg','grad','rad','turn'): continue
|
||||
return True
|
||||
end = size_index + 1
|
||||
if end < len(tokens) and tokens[end].type=='literal' and tokens[end].value=='/':
|
||||
end += 2
|
||||
if end > len(tokens) or _invalid_core_value('line-height', [tokens[end-1]]): return True
|
||||
if end >= len(tokens): return True
|
||||
try: _font_names(_text(tokens[end:]))
|
||||
except ValueError: return True
|
||||
# Retain valid, unsupported prefixes and relative sizes as CSS.
|
||||
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'}
|
||||
@@ -270,6 +297,14 @@ def _invalid_core_value(prop, tokens):
|
||||
selected = [name for name in names if name in lines]
|
||||
if 'none' in selected and len(selected)>1 or len(selected)!=len(set(selected)): return True
|
||||
if prop == 'text-decoration-line': return any(t.type!='ident' or t.lower_value not in lines for t in tokens)
|
||||
for token in tokens:
|
||||
if token.type=='ident' and token.lower_value in lines | {'solid','double','dotted','dashed','wavy','auto','from-font'}: continue
|
||||
if token.type=='function':
|
||||
if _invalid_core_value('color', [token]): return True
|
||||
continue # Includes variable colors/thickness.
|
||||
if parse_color(token) is not None: continue
|
||||
if token.type in ('dimension','percentage','number') and not _invalid_core_value('font-size',[token]): continue
|
||||
return True
|
||||
if len(tokens) != 1: return False
|
||||
token = tokens[0]
|
||||
if token.type == 'string' and prop != 'font-family' and not prop.startswith('--'): return True
|
||||
|
||||
@@ -152,13 +152,15 @@ def test_nested_quoted_lists_keep_depth_numbering_and_emphasis(tmp_path,engine):
|
||||
values={}
|
||||
for p in effective_document(doc,styles).iter(W+'p'):
|
||||
text=''.join(p.itertext()); props=p.find(W+'pPr')
|
||||
values[text]=props.find(W+'ind').get(W+'leftChars')
|
||||
# Absolute indents are needed when the quote and list use different
|
||||
# font sizes. Compare the resulting distance, not its storage unit.
|
||||
values[text]=int(props.find(W+'ind').get(W+'left'))
|
||||
assert props.find(W+'numPr') is not None
|
||||
if text in ('OuterQuote','NestedQuote'):
|
||||
run=next(r for r in p.iter(W+'r') if ''.join(r.itertext())==text)
|
||||
assert run.find('w:rPr/w:b',NS).get(W+'val')=='1'
|
||||
assert run.find('w:rPr/w:color',NS).get(W+'val')=='ff0000'
|
||||
assert int(values['NestedQuote'])>int(values['OuterQuote'])
|
||||
assert values['NestedQuote']-values['OuterQuote']==36*20
|
||||
|
||||
|
||||
def test_graphical_quote_edit_overrides_important_broad_p(qt_application,tmp_path):
|
||||
|
||||
@@ -12,6 +12,11 @@ ENGINES = ('builtin', 'python-docx', 'pandoc')
|
||||
CODE_SOURCE = '# Parent\n\n`Inline`\n\n```text\nBlock\n```'
|
||||
CODE_RULES = {'h1': {'font_color': '#ff0000', 'font_size': 20, 'font_size_unit': 'pt'},
|
||||
'_metadata': {'code': {'based_on': 'h1'}}}
|
||||
ORDERED = '1. First\n\n Continuation\n\n2. Second'
|
||||
TASK = '- [ ] First\n\n Continuation\n\n- [x] Second'
|
||||
QUOTED = '> - Outer\n>\n> - Inner\n>\n> - NestedSecond\n>\n> - Second'
|
||||
MARGINS = 'p {margin-left:12pt;} li {margin-left:24pt;}'
|
||||
MIXED = 'li {font-size:12pt;margin-left:24pt;text-indent:-1em;} p {font-size:20pt;margin-left:12pt;}'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('nested', ['& strong {color:red}', '@media screen { & strong {color:red} }'])
|
||||
@@ -60,3 +65,97 @@ def test_word_code_keeps_editable_parent_chain(tmp_path, engine):
|
||||
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') == '0000ff'
|
||||
assert run.find('w:rPr/w:sz', NS).get(W+'val') == '56'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ENGINES)
|
||||
@pytest.mark.parametrize('source,target', [(ORDERED,'list_ordered'), (TASK,'list_task')])
|
||||
def test_word_continuation_preserves_semantic_list_type(tmp_path, engine, source, target):
|
||||
rules = {target: {'font_color': '#ff0000'}, 'list_bullet': {'font_color': '#0000ff'}}
|
||||
doc, styles = parts(export_markdown_to_docx(source,tmp_path/'continuation.docx',engine=engine,style_rules=rules))
|
||||
assert not any(a.startswith('{urn:mdhelper:source}') for p in doc.iter(W+'p') for a in p.attrib)
|
||||
from mdhelper.docx_semantic import style_id
|
||||
base = styles.find(f"w:style[@w:styleId='{style_id(target)}']",NS)
|
||||
base.find('w:rPr/w:color',NS).set(W+'val','008000')
|
||||
for p in effective_document(doc,styles).iter(W+'p'):
|
||||
for run in p.iter(W+'r'):
|
||||
if ''.join(run.itertext()).strip(): assert run.find('w:rPr/w:color',NS).get(W+'val')=='008000'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ENGINES)
|
||||
def test_quoted_list_keeps_additive_nested_indents(tmp_path, engine):
|
||||
doc, styles = parts(export_markdown_to_docx(QUOTED,tmp_path/'quoted.docx',engine=engine,style_rules=normalize_payload({'css':MARGINS})['rules']))
|
||||
for p in effective_document(doc,styles).iter(W+'p'):
|
||||
text=''.join(p.itertext())
|
||||
if text in ('Outer','Inner'):
|
||||
ind=p.find('w:pPr/w:ind',NS)
|
||||
assert int(ind.get(W+'left'))/20 == (36 if text=='Outer' else 72)
|
||||
assert ind.get(W+'hangingChars','0')=='0'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ENGINES)
|
||||
def test_inherited_list_hanging_uses_container_font(tmp_path, engine):
|
||||
doc,styles=parts(export_markdown_to_docx('- Outer\n\n- Second',tmp_path/'hanging.docx',engine=engine,style_rules=normalize_payload({'css':MIXED})['rules']))
|
||||
for p in effective_document(doc,styles).iter(W+'p'):
|
||||
assert p.find('w:pPr/w:ind',NS).get(W+'hanging') == '240'
|
||||
|
||||
|
||||
def test_legacy_code_can_cancel_outer_decoration(qt_application,tmp_path):
|
||||
payload=normalize_payload({'rules':{'strong':{'underline':True},'code':{'underline':False}}})
|
||||
result=browser(qt_application,tmp_path,payload,'**Outer `Inner` outer**',
|
||||
"[document.querySelector('strong'),document.querySelector('strong > [data-mdh-text]'),document.querySelector('code [data-mdh-text]')].map(e=>getComputedStyle(e).textDecorationLine)")
|
||||
assert result==['none','underline','none']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('bad',['color:rgb(nope)','color:rgba(1,2)','color:hsl(nope)','font:bold garbage','font:italic 12pt','font:bold nonsense 20pt Arial'])
|
||||
def test_invalid_function_and_font_keep_valid_core_values(qt_application,tmp_path,bad):
|
||||
payload=normalize_payload({'css':'p{color:red;font-size:20pt;'+bad+'}'})
|
||||
assert payload['rules']['paragraph']['font_color']=='#ff0000'
|
||||
assert payload['rules']['paragraph']['font_size']==20
|
||||
assert normalize_payload(payload)==payload
|
||||
assert browser(qt_application,tmp_path,payload,'Fallback',"getComputedStyle(document.querySelector('p')).color")=='rgb(255, 0, 0)'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('invalid', ['underline nonsense','underline rgb(nope)'])
|
||||
def test_invalid_decoration_does_not_draw_an_extra_line(qt_application,tmp_path,invalid):
|
||||
payload=normalize_payload({'css':'em{text-decoration:none} strong{text-decoration:line-through;text-decoration:'+invalid+'}'})
|
||||
assert browser(qt_application,tmp_path,payload,'**Text**',"getComputedStyle(document.querySelector('strong [data-mdh-text]')).textDecorationLine")=='line-through'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('value,line,style,color', [('line-through','line-through','solid','rgb(23, 105, 170)'),
|
||||
('underline line-through wavy red','underline line-through','wavy','rgb(255, 0, 0)')])
|
||||
def test_variable_decoration_shorthand_keeps_browser_effect(qt_application,tmp_path,value,line,style,color):
|
||||
payload=normalize_payload({'css':'em{text-decoration:none} a{text-decoration:var(--custom-line);--custom-line:'+value+'}'})
|
||||
assert browser(qt_application,tmp_path,payload,'[Link](#link)',"(()=>{const s=getComputedStyle(document.querySelector('a [data-mdh-text]'));return [s.textDecorationLine,s.textDecorationStyle,s.textDecorationColor]})()") == [line,style,color]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('scope', ['a { %s }','a { @media screen { %s } }','@supports (display:grid) { a { %s } }'])
|
||||
def test_variable_decorations_survive_nested_conditions(qt_application,tmp_path,scope):
|
||||
payload=normalize_payload({'css':'em{text-decoration:none} '+scope % 'text-decoration:var(--line);--line:line-through wavy red;'})
|
||||
actual=browser(qt_application,tmp_path,payload,'[Outer *Inner*](#link)',
|
||||
"[...document.querySelectorAll('a [data-mdh-text]')].map(e=>getComputedStyle(e).textDecorationLine)")
|
||||
assert actual==['line-through','none']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('css', ['color:rgb(255 0 0 / .5)', 'color:rgb(from red r g b)', 'color:rgb(calc(255 / 2) 0 0)', 'font:italic 2em Arial'])
|
||||
def test_valid_advanced_values_remain_css_only(css):
|
||||
from mdhelper.style_sync import analyze_css
|
||||
result=analyze_css('p{color:blue;font-size:20pt;'+css+'}')
|
||||
assert not result.errors and not any('已忽略无效' in note for note in result.notes)
|
||||
|
||||
|
||||
def test_actual_table_preview_shows_alternating_rows(qt_application):
|
||||
import json,time
|
||||
dialog=DocumentStyleEditorDialog({'rules':{'table':{'table_banded_rows':True,'table_stripe_color':'#ff0000'}}})
|
||||
try:
|
||||
dialog.tabs.setCurrentIndex(2)
|
||||
values=[]
|
||||
end=time.monotonic()+20
|
||||
while time.monotonic()<end:
|
||||
values.clear()
|
||||
dialog.actual_preview.page().runJavaScript("JSON.stringify([...document.querySelectorAll('tbody tr')].map(tr=>getComputedStyle(tr.cells[0]).backgroundColor))",values.append)
|
||||
while not values and time.monotonic()<end: qt_application.processEvents();time.sleep(.01)
|
||||
if values and values[0] and len(json.loads(values[0]))>=3: break
|
||||
qt_application.processEvents();time.sleep(.01)
|
||||
colors=json.loads(values[0])
|
||||
assert len(colors)>=3 and colors[1]=='rgb(255, 0, 0)' and colors[0]!=colors[1] and colors[2]!=colors[1]
|
||||
finally: dialog.close()
|
||||
|
||||
@@ -10,23 +10,60 @@ sys.path.insert(0,str(Path('tests').resolve()))
|
||||
from test_style_revision_055 import *
|
||||
folder=Path(tempfile.mkdtemp(prefix='MDHelper-055-Word-'))
|
||||
for engine in ENGINES:
|
||||
export_markdown_to_docx(CODE_SOURCE,folder/f'{engine}-code.docx',engine=engine,style_rules=CODE_RULES)
|
||||
for name,source,rules in [('code',CODE_SOURCE,CODE_RULES),
|
||||
('ordered',ORDERED,{'list_ordered':{'font_color':'#ff0000'},'list_bullet':{'font_color':'#0000ff'}}),
|
||||
('task',TASK,{'list_task':{'font_color':'#ff0000'},'list_bullet':{'font_color':'#0000ff'}}),
|
||||
('quoted',QUOTED,normalize_payload({'css':MARGINS})['rules']),
|
||||
('hanging','- Outer\n\n- Second',normalize_payload({'css':MIXED})['rules']),
|
||||
('invalid','Fallback',normalize_payload({'css':'p{color:red;color:rgb(nope);font-size:20pt;font:bold garbage;}'})['rules']),
|
||||
('legacy','**Outer `Inner` outer**',{'strong':{'underline':True},'code':{'underline':False}})]:
|
||||
export_markdown_to_docx(source,folder/f'{engine}-{name}.docx',engine=engine,style_rules=rules)
|
||||
print(folder)
|
||||
'@ | & $Python -B -).Trim()
|
||||
if ($LASTEXITCODE -ne 0) {throw 'Fixture generation failed'}
|
||||
$word=New-Object -ComObject Word.Application
|
||||
$word.Visible=$false;$word.DisplayAlerts=0
|
||||
foreach($engine in @('builtin','python-docx','pandoc')) {
|
||||
$doc=$word.Documents.Open((Join-Path $folder "$engine-code.docx"),$false,$true)
|
||||
foreach($case in @('code','ordered','task','quoted','hanging','invalid','legacy')) {
|
||||
$doc=$word.Documents.Open((Join-Path $folder "$engine-$case.docx"),$false,$true)
|
||||
try {
|
||||
if($case -eq 'code') {
|
||||
$range=$doc.Content.Duplicate;[void]$range.Find.Execute('Parent')
|
||||
$range.Style.Font.Color=16711680;$range.Style.Font.Size=28
|
||||
foreach($text in @('Inline','Block')) {
|
||||
$range=$doc.Content.Duplicate;[void]$range.Find.Execute($text)
|
||||
if($range.Font.Color -ne 16711680 -or $range.Font.Size -ne 28){throw "$engine $text does not follow ancestor: $($range.Font.Color), $($range.Font.Size)"}
|
||||
}
|
||||
Write-Output "$engine code ancestor edits passed"
|
||||
} elseif($case -in @('ordered','task')) {
|
||||
$range=$doc.Content.Duplicate;[void]$range.Find.Execute('First')
|
||||
$name=if($case -eq 'ordered'){'MDHelper 有序列表'}else{'MDHelper 任务列表'}
|
||||
$base=$doc.Styles.Item($name)
|
||||
$base.Font.Color=65280
|
||||
foreach($text in @('First','Continuation','Second')) {
|
||||
$range=$doc.Content.Duplicate;[void]$range.Find.Execute($text)
|
||||
if($range.Font.Color -ne 65280){throw "$engine $case $text lost editable list base: $($range.Font.Color)"}
|
||||
if($text -eq 'Continuation' -and $range.ListFormat.ListString.Trim() -ne ''){throw "$engine continuation consumed a marker"}
|
||||
}
|
||||
} elseif($case -eq 'quoted') {
|
||||
foreach($pair in @(@('Outer',36),@('Inner',72))) {
|
||||
$range=$doc.Content.Duplicate;[void]$range.Find.Execute($pair[0])
|
||||
if([Math]::Abs($range.ParagraphFormat.LeftIndent-$pair[1]) -gt 0.1){throw "$engine quoted $($pair[0]) indent: $($range.ParagraphFormat.LeftIndent)"}
|
||||
}
|
||||
} elseif($case -eq 'hanging') {
|
||||
$range=$doc.Content.Duplicate;[void]$range.Find.Execute('Outer')
|
||||
if($range.ParagraphFormat.FirstLineIndent -ne -12 -or $range.Font.Size -ne 20){throw "$engine inherited hanging indent resized: $($range.ParagraphFormat.FirstLineIndent), font $($range.Font.Size)"}
|
||||
} 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){throw "$engine invalid CSS discarded valid fallback"}
|
||||
} elseif($case -eq 'legacy') {
|
||||
foreach($pair in @(@('Outer',1),@('Inner',0))) {
|
||||
$range=$doc.Content.Duplicate;[void]$range.Find.Execute($pair[0])
|
||||
if($range.Font.Underline -ne $pair[1] -or $range.Font.Bold -ne -1){throw "$engine legacy decoration or emphasis changed"}
|
||||
}
|
||||
}
|
||||
Write-Output "$engine $case passed"
|
||||
} finally {$doc.Close(0);[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc)}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if($word){$word.Quit();[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($word)}
|
||||
|
||||
Reference in New Issue
Block a user