fix: preserve list context and nested CSS decoration behavior

This commit is contained in:
2026-11-05 09:49:52 +08:00
parent d0f95d277a
commit 77ee046463
10 changed files with 284 additions and 79 deletions
+13 -2
View File
@@ -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>"
+5 -1
View File
@@ -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
View File
@@ -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_'):
+42 -40
View File
@@ -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)))
+9 -3
View File
@@ -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})
+1
View File
@@ -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
View File
@@ -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