fix: align nested Word blocks and synchronize CSS and heading navigation

This commit is contained in:
2026-11-05 12:11:42 +08:00
parent b3a0907e1a
commit 36f0d7856e
15 changed files with 383 additions and 96 deletions
+8
View File
@@ -173,6 +173,10 @@ Word 导出通过关联的段落/字符基准保留旧代码设置。在 Word
代码基准显式继承标题等段落样式时,行内代码也沿用该祖先的默认字体格式,并参与强调保护;代码位于加粗、链接等组合内部时,组合样式保留解析后的代码格式。列表项以标题或代码块开头时,仍保留连续编号;它们使用以相应标题或代码块为基准的派生样式,编号和缩进不会把文字改成普通列表样式。
列表中的续段使用可编辑的派生样式,继承原样式的字体和左右缩进,同时取消首行悬挂。多行代码保留在同一段落中,避免第二行跳到编号位置;列表缩进按实际长度写入,避免 Word 文档网格改变字符缩进。引用中的标题和代码块保留引用容器的层级缩进,字体仍继承对应标题或代码样式。引用段落的图形设置继续只作用于普通引用文字。
列表项以表格开头时,Word 在表格前使用一个空的编号段落,保留完整表头和表格后的续段;合并导出也保留列表标题前的编号及容器结构。
### 样式面板与 Word 导出
打开“样式 → 样式面板”,可查看全部样式或当前文档已用样式。编辑 Markdown 时,面板提示光标所在段落及其中包含的字符样式。双击条目修改样式名称、同类型基准及格式;改变样式不会改写 Markdown 内容。基于内置样式修改时自动创建自定义样式集,并保留原内置样式的字体、行距等基础信息,导出 Word 和迁移样式文件后继续生效。
@@ -209,6 +213,8 @@ Word 的字符样式会把加粗、斜体和删除线作为与段落格式叠加
嵌套字符样式可分别开启或关闭下划线与删除线。阅读器按最终文字样式绘制修饰,内层关闭下划线时可保留外层删除线,文字仍正常换行。高级 CSS 的修饰颜色、波浪线及条件规则继续用于阅读器和 HTML/PDF;Word 保留已支持的核心修饰和命名样式。
`text-decoration: unset` 和 `initial` 会同步关闭核心文字修饰;常规关键字的大小写不影响同步。无效字体简写中的未加引号的保留字和超出范围的 `deg` 斜体角度会被忽略,继续使用前面的有效声明。包含 ID 选择器及 `!important` 的外层文字修饰也遵循内层独立关闭设置。
普通 `p` 选择器也作用于引用和宽松列表中的段落,Word 会保留这些上下文格式;紧凑列表没有独立段落元素,不受该选择器影响。表头和单元格的段前、段后及左右间距作用于内部文字区域,表格内边距仍独立设置。明显无效的 CSS 值(例如 `font-size:nope`)会被忽略并提示,前面的有效声明继续同步;有效但不能转换为 Word 的扩展表达式仍保留为 CSS。
宽松列表中明确设置的 `p` 间距和缩进不会被列表辅助规则清零。图形设置修改引用等子对象时,会保留必要的 `!important` 优先级,使修改真正生效。无效的多值声明、错误单位和互斥文字修饰同样按浏览器的回退规则处理;`border-style:none` / `hidden` 会同步为 Word 无边框,改变宽度不会重新开启边框。
@@ -332,6 +338,8 @@ MDHelper 会保存:
- **恢复工作现场**:正常退出后,再次打开同一文件夹会恢复标签顺序、当前文档、编辑模式和分屏状态。后台标签在点击时加载;可在“文件 → 启动时恢复工作现场”中关闭。未保存草稿仍按原有方式提示恢复。
- **文档检查**:在“工具 → 检查文档链接与图片”中扫描当前项目,检查本地链接、图片和章节锚点。检查使用当前编辑内容,双击结果可定位 Markdown 编辑行或查看 HTML 源码。
- **安全重命名**:在文件树重命名时,若存在需要同步修改的引用,会显示差异预览。确认后统一保存这些修改,并更新标签、最近文件和书签。备份位于本地应用数据目录的 `MDHelper/rename-backups`。
批量导出和引用重命名在最终替换文件时也会核对实际被替换的版本。若此时发生外部保存,会停止事务并保留冲突内容;提示中的 `.conflict-….bak` 位于原文件旁,用于恢复同时发生的外部修改。已有文件不会仅凭较早的检查结果被无备份覆盖。
- **保存冲突对比**:磁盘被其他程序修改或删除时,保存前展示两份内容。勾选差异段落采用磁盘版本,也可以编辑合并结果;取消会保留当前编辑内容。
- **批量与合并导出**:在“文件 → 批量与合并导出”中勾选 Markdown 文件,调整顺序并选择 Word/PDF。默认分别输出,也可勾选合并为一份文档。使用当前样式和编辑内容,全部转换成功后才保存输出。
- **项目样式与导出预设**:在“工具 → 项目样式与导出预设”中启用项目默认,或应用预设模板。启用后,在主窗口调整字体、段落和样式,会自动记入当前项目;页面参数与 Word/PDF 共用。模板可独立导入和导出,切换项目会恢复各自的设置。
+17 -5
View File
@@ -17,6 +17,7 @@ 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, LIST_TARGET
from .docx_inline import QUOTE_DEPTH, LIST_LEVEL
WP_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
@@ -277,6 +278,7 @@ def _add_python_docx_paragraph(document: object, block: ParagraphBlock) -> None:
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.quote_depth: paragraph._p.set(QUOTE_DEPTH, str(block.quote_depth))
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>'))
@@ -319,6 +321,9 @@ def _add_python_docx_table(document: object, block: TableBlock) -> None:
return
column_count = max(len(row) for row in block.rows)
table = document.add_table(rows=len(block.rows), cols=column_count)
if block.list_target:
table._tbl.set(LIST_TARGET, block.list_target)
table._tbl.set(LIST_LEVEL, str(block.list_level))
table.style = "Table Grid"
for row_index, row in enumerate(block.rows):
for col_index in range(column_count):
@@ -364,6 +369,8 @@ class ParagraphBlock:
class TableBlock:
rows: list[list[list[tuple[str, dict[str, bool]]]]]
alignments: list[str] = field(default_factory=list)
list_target: str = ''
list_level: int = 0
class _DocxBuilder:
@@ -392,8 +399,11 @@ class _DocxBuilder:
self._add_next_inline(style, list_kind=self.list_stack[-1] if self.list_stack else "")
continue
if token.type in {"fence", "code_block"}:
for line in token.content.rstrip("\n").splitlines() or [""]:
self._append_paragraph([(line, {"code": True})], 'Code', self.list_stack[-1] if self.list_stack else '')
runs = []
for index, line in enumerate(token.content.rstrip("\n").split('\n')):
if index: runs.append(('\n', {}))
runs.append((line, {'code': True}))
self._append_paragraph(runs, 'Code', self.list_stack[-1] if self.list_stack else '')
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')
@@ -464,7 +474,7 @@ class _DocxBuilder:
self.index += 1
break
self.index += 1
return TableBlock(rows, alignments)
return TableBlock(rows, alignments, self.item_targets[-1] if self.item_targets else '', max(0, len(self.list_stack)-1))
def _inline_runs(children: list[Token] | None) -> list[tuple[str, dict[str, object]]]:
@@ -546,9 +556,10 @@ 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"' if block.continuation or block.list_target else ''
marker = ' xmlns:mdh="urn:mdhelper:source"' if block.continuation or block.list_target or block.quote_depth else ''
if block.continuation: marker += ' mdh:continuation="1"'
if block.list_target: marker += f' mdh:list-target="{block.list_target}"'
if block.quote_depth: marker += f' mdh:quote-depth="{block.quote_depth}"'
return f"<w:p{marker}>{ppr}{''.join(_run_xml(text, style) for text, style in block.runs)}</w:p>"
@@ -588,6 +599,7 @@ def _numbering_xml(blocks):
def _table_xml(block: TableBlock) -> str:
marker = f' xmlns:mdh="urn:mdhelper:source" mdh:list-target="{block.list_target}" mdh:list-level="{block.list_level}"' if block.list_target else ''
rows = []
for row in block.rows:
cells = []
@@ -596,7 +608,7 @@ def _table_xml(block: TableBlock) -> str:
cells.append(f"<w:tc><w:tcPr><w:tcW w:w=\"0\" w:type=\"auto\"/></w:tcPr>{_paragraph_xml(ParagraphBlock(cell, alignment=alignment))}</w:tc>")
rows.append(f"<w:tr>{''.join(cells)}</w:tr>")
return (
'<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/><w:tblW w:w="0" w:type="auto"/>'
f'<w:tbl{marker}><w:tblPr><w:tblStyle w:val="TableGrid"/><w:tblW w:w="0" w:type="auto"/>'
'<w:tblBorders><w:top w:val="single" w:sz="4" w:space="0" w:color="D0D7DE"/>'
'<w:left w:val="single" w:sz="4" w:space="0" w:color="D0D7DE"/>'
'<w:bottom w:val="single" w:sz="4" w:space="0" w:color="D0D7DE"/>'
+3
View File
@@ -9,6 +9,9 @@ SOURCE_LIST_STYLES = {base + '_' + target: (base, target)
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'
LIST_LEVEL = '{urn:mdhelper:source}list-level'
QUOTE_DEPTH = '{urn:mdhelper:source}quote-depth'
CONTEXT = '{urn:mdhelper:source}context'
CODES = {'strong': 'B', 'emphasis': 'I', 'strike': 'S', 'link': 'L', 'inline_code': 'C'}
+75 -8
View File
@@ -14,6 +14,7 @@ from .document_style import resolved_rules, normalize_rule, font_points, length_
from .style_catalog import CATALOG, CHARACTER_DEFAULTS, explicit_rules, character_declarations, 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, LIST_TARGET, LIST_TARGETS, SOURCE_LIST_STYLES
from .docx_inline import QUOTE_DEPTH, LIST_LEVEL, CONTEXT
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()
@@ -34,6 +35,15 @@ def remove_fields(parent, names):
for element in parent.findall(W + name): parent.remove(element)
def absolute_indents(rule):
"""Word character indents use its document grid, not the CSS em width."""
rule = dict(rule)
for value, unit in (('left_indent_value','left_indent_unit'), ('right_indent_value','right_indent_unit'), ('indent_value','indent_unit')):
rule[value] = length_points(rule.get(value, 0), rule.get(unit, 'em'), font_points(rule))
rule[unit] = 'pt'
return rule
def _delta(current, base, authored=None):
"""Keep just changed properties, allowing subsequent Word base-style edits."""
if base is None: return
@@ -132,6 +142,7 @@ class WordStyles:
base = 'table'
style = self.new(identifier, 'paragraph', 'MDHelper ' + style_name(key, self.rules), base_id)
rule = dict(self.effective[key])
if key == 'list' or key in LIST_TARGETS: rule = absolute_indents(rule)
if rule.get('font_color') == 'inherit': rule['font_color'] = 'auto'
_paragraph_properties(child(style, 'pPr'), rule)
if key in ('table_head', 'table_cell'): remove_fields(child(style, 'pPr'), ('shd',))
@@ -140,7 +151,8 @@ class WordStyles:
if base:
for tag, writer in (('pPr', _paragraph_properties), ('rPr', _run_properties)):
base_props = ET.Element(W + tag)
writer(base_props, self.effective[base])
base_rule = absolute_indents(self.effective[base]) if base == 'list' or base in LIST_TARGETS else self.effective[base]
writer(base_props, base_rule)
if tag == 'rPr': remove_fields(base_props, ('shd',))
_delta(child(style, tag), base_props, normalize_rule(self.rules.get(key)))
if re.fullmatch('h[1-6]', key): val(child(style, 'pPr'), 'outlineLvl', int(key[1]) - 1)
@@ -271,6 +283,10 @@ class WordStyles:
self.identify_numbering(abstract, abstract_id)
for root in (num, abstract):
for props in root.iter(W + 'pPr'): remove_fields(props, ('ind', 'tabs'))
for item in root.iter(W + 'lvl'):
# Right-align the marker before the text stop. Wide numbers
# and code fonts must not push the first line to the next tab.
val(item, 'lvlJc', 'right')
self.numbering.extend((abstract, num))
self.style_numbering[original] = str(num_id)
val(numpr, 'numId', self.style_numbering[original])
@@ -324,7 +340,7 @@ class WordStyles:
rule['left_indent_value'] = length_points(rule['left_indent_value'], rule['left_indent_unit'], points) + offset
rule['left_indent_unit'] = 'pt'
temp = ET.Element(W + 'pPr')
_paragraph_properties(temp, rule)
_paragraph_properties(temp, absolute_indents(rule))
ind = temp.find(W + 'ind')
for attr in list(ind.attrib):
if attr not in (W + 'left', W + 'leftChars'): del ind.attrib[attr]
@@ -337,9 +353,6 @@ class WordStyles:
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))
@@ -372,6 +385,38 @@ class WordStyles:
_delta(props, old, authored)
return identifier
def continuation_style(self, base_id):
identifier = base_id + 'Continuation'
if identifier not in self.created:
base = self.created[base_id]
style = self.new(identifier, 'paragraph', reference(base, 'name') + '(续段)', base_id)
child(child(style, 'pPr'), 'ind').attrib.update({W + key:'0' for key in ('firstLine','firstLineChars','hanging','hangingChars')})
return identifier
def quoted_block(self, base_id, target, depth):
identifier = base_id + 'Quote' + str(depth)
if identifier not in self.created:
style = self.new(identifier, 'paragraph', reference(self.created[base_id], 'name') + f'(引用第 {depth} 层)', base_id)
# Headings/code retain their own paragraph formatting. The quote
# container contributes its reader padding and border, not the
# separate blockquote-p controls (which only apply to text paragraphs).
attributes = {}
chain = []; current = base_id
while current in self.created:
chain.append(self.created[current]); current = reference(chain[-1], 'basedOn')
for base in reversed(chain):
ind = base.find('w:pPr/w:ind', NS)
if ind is not None: attributes.update(ind.attrib)
points = font_points(self.effective['paragraph'])
props = child(child(style, 'pPr'), 'ind')
for side, padding in (('left', points + 3), ('right', points)):
value = number(attributes.get(W + side, 0)) / 20
chars = number(attributes.get(W + side + 'Chars', 0))
if chars: value = chars / 100 * font_points(self.effective[target])
props.set(W + side, str(round((value + padding * depth) * 20)))
props.set(W + side + 'Chars', '0')
return identifier
def list_block(self, target, list_target, level):
"""Keep a heading/code style as the editable base inside a numbered item."""
identifier = style_id(target) + style_id(list_target) + 'Level' + str(level + 1)
@@ -503,9 +548,17 @@ class WordStyles:
for tag in tags: val(rpr, tag, int(merged[field]))
def apply(self, document):
for context in list(document.iter(CONTEXT)):
following = context.getnext()
while following is not None and following.tag not in (W+'p', W+'tbl'):
following = following.getnext()
if following is not None: following.attrib.update(context.attrib)
context.getparent().remove(context)
for paragraph in document.iter(W + 'p'):
continuation = paragraph.attrib.pop(CONTINUATION, '') == '1'
list_target = paragraph.attrib.pop(LIST_TARGET, '')
quote_depth = int(paragraph.attrib.pop(QUOTE_DEPTH, '0'))
paragraph.attrib.pop(LIST_LEVEL, None)
ppr = properties(paragraph, 'pPr')
original_id = reference(ppr, 'pStyle') or 'Normal'
names = {reference(style, 'name') for style in self.chain(original_id)}
@@ -521,6 +574,10 @@ class WordStyles:
if target.startswith('list_') and list_target in LIST_TARGETS: target = list_target
identifier = self.paragraph(target)
numpr = ppr.find(W + 'numPr')
if numpr is not None:
_, original_level = self.list_level(numpr)
if original_level is not None and not reference(original_level, 'lvlText').strip():
continuation = True
# Every numbered paragraph in a list must share the same rewritten
# numbering instance, including headings and code. Otherwise Word
# restarts numbering when the next ordinary paragraph is reached.
@@ -533,16 +590,20 @@ class WordStyles:
level, _ = self.list_level(numpr)
identifier = self.list_block(target, list_target, level)
marker = self.effective[list_target].get('list_marker')
if marker: self.apply_list_marker(numpr, list_target, marker)
if marker and not continuation: self.apply_list_marker(numpr, list_target, marker)
if continuation and target == 'blockquote': remove_fields(ppr, ('numPr',))
if target.startswith('list_'):
level, _ = self.list_level(numpr)
if level: identifier = self.nested_list(target, level)
marker = self.effective[target].get('list_marker')
if marker: self.apply_list_marker(numpr, target, marker)
if marker and not continuation: self.apply_list_marker(numpr, target, marker)
if loose: identifier = self.list_paragraph(target, identifier, level)
if QUOTED_LIST_PARAGRAPH_STYLE in names: identifier = self.quoted_list(target, identifier, level)
if continuation: remove_fields(ppr, ('numPr',))
if continuation:
remove_fields(ppr, ('numPr',))
identifier = self.continuation_style(identifier)
if quote_depth and (target == 'code_block' or re.fullmatch('h[1-6]', target)):
identifier = self.quoted_block(identifier, target, quote_depth)
alignment = reference(ppr, 'jc')
if target in ('table_head','table_cell') and alignment in ('left','center','right','both'):
identifier = self.table_column(target, alignment)
@@ -550,7 +611,13 @@ class WordStyles:
val(ppr, 'pStyle', identifier)
for run in paragraph.iter(W + 'r'): self.apply_run(run, target)
for table in document.iter(W + 'tbl'):
list_target = table.attrib.pop(LIST_TARGET, '')
level = int(table.attrib.pop(LIST_LEVEL, '0'))
table.attrib.pop(QUOTE_DEPTH, None); table.attrib.pop(CONTINUATION, None)
props = properties(table, 'tblPr')
if list_target in LIST_TARGETS:
rule = self.contextual_list_rule(list_target, {}, level)
child(props, 'tblInd').attrib.update({W+'type':'dxa', W+'w':str(round(rule['left_indent_value'] * 20))})
remove_fields(props, ('tblBorders', 'tblCellMar', 'shd'))
val(props, 'tblStyle', style_id('table'))
child(props, 'tblLayout').set(W + 'type', 'autofit')
+3 -27
View File
@@ -36,7 +36,7 @@ from PySide6.QtWidgets import (
)
from .markdown_renderer import MarkdownRenderer
from .markdown_utils import slugify_heading
from .markdown_utils import heading_locations
MAX_SYNTAX_HIGHLIGHT_CHARS = 1_000_000
@@ -453,32 +453,8 @@ class MarkdownEditorDialog(QDialog):
return True
def _heading_line_for_slug(self, target_slug: str) -> int | None:
seen: dict[str, int] = {}
in_fenced_block = False
for line_number, line in enumerate(self.source_text().splitlines()):
stripped = line.strip()
if stripped.startswith("```") or stripped.startswith("~~~"):
in_fenced_block = not in_fenced_block
continue
if in_fenced_block:
continue
match = re.match(r"^(#{1,6})\s+(.+?)\s*#*\s*$", stripped)
if not match:
continue
slug = slugify_heading(match.group(2).strip())
if not slug:
continue
count = seen.get(slug, 0)
seen[slug] = count + 1
if count:
slug = f"{slug}-{count + 1}"
if slug == target_slug:
return line_number
return None
return next((line for heading, line in heading_locations(self.source_text(), self.renderer.markdown)
if heading.slug == target_slug), None)
def _on_editor_text_changed(self) -> None:
+5 -28
View File
@@ -17,7 +17,7 @@ from pygments.lexers import get_lexer_by_name
from pygments.lexers.special import TextLexer
from pygments.util import ClassNotFound
from .markdown_utils import slugify_heading
from .markdown_utils import heading_tokens
from .markdown_compat import cjk_strong_plugin
from .media import is_qt_video_player_url, media_kind, media_mime_type
@@ -573,34 +573,11 @@ class MarkdownRenderer:
return re.sub(pattern, replace_keyword, escaped)
def _add_heading_ids(self, state: Any) -> None:
seen: dict[str, int] = {}
tokens = state.tokens
headings = state.env.setdefault("headings", [])
for index, token in enumerate(tokens):
if token.type != "heading_open" or index + 1 >= len(tokens):
continue
inline = tokens[index + 1]
if inline.type != "inline":
continue
slug = slugify_heading(inline.content)
if not slug:
continue
count = seen.get(slug, 0)
seen[slug] = count + 1
if count:
slug = f"{slug}-{count + 1}"
token.attrSet("id", slug)
headings = state.env.setdefault('headings', [])
for token, heading in heading_tokens(state.tokens):
token.attrSet('id', heading.slug)
if isinstance(headings, list):
try:
level = int(token.tag[1:])
except (TypeError, ValueError):
level = 1
headings.append({"level": level, "title": inline.content, "slug": slug})
headings.append({'level': heading.level, 'title': heading.title, 'slug': heading.slug})
def _convert_admonitions(self, state: Any) -> None:
labels = {
+19 -20
View File
@@ -20,36 +20,35 @@ def slugify_heading(text: str) -> str:
return slug.strip("-")
def extract_headings_from_text(markdown_text: str) -> list[Heading]:
headings: list[Heading] = []
def heading_tokens(tokens):
"""Shared title/anchor sequence for rendering, the outline and navigation."""
seen: dict[str, int] = {}
in_fenced_block = False
for line in markdown_text.splitlines():
stripped = line.strip()
if stripped.startswith("```") or stripped.startswith("~~~"):
in_fenced_block = not in_fenced_block
for index, token in enumerate(tokens):
if token.type != 'heading_open' or index + 1 >= len(tokens):
continue
if in_fenced_block:
inline = tokens[index + 1]
if inline.type != 'inline':
continue
match = re.match(r"^(#{1,6})\s+(.+?)\s*#*\s*$", stripped)
if not match:
continue
title = match.group(2).strip()
slug = slugify_heading(title)
slug = slugify_heading(inline.content)
if not slug:
continue
count = seen.get(slug, 0)
seen[slug] = count + 1
if count:
slug = f"{slug}-{count + 1}"
slug = f'{slug}-{count + 1}'
yield token, Heading(int(token.tag[1:]), inline.content, slug)
headings.append(Heading(level=len(match.group(1)), title=title, slug=slug))
return headings
def heading_locations(markdown_text: str, markdown=None):
if markdown is None:
# Lazy import avoids loading the renderer during application bootstrap.
from .markdown_renderer import MarkdownRenderer
markdown = MarkdownRenderer(Path.cwd()).markdown
return [(heading, token.map[0]) for token, heading in heading_tokens(markdown.parse(markdown_text, {})) if token.map]
def extract_headings_from_text(markdown_text: str) -> list[Heading]:
return [heading for heading, _ in heading_locations(markdown_text)]
def extract_headings(path: Path) -> list[Heading]:
+12 -1
View File
@@ -88,7 +88,7 @@ def decoration_css(rules, inherited, selectors, source):
def _decoration_variables(source):
"""Keep authored selectors, conditions, priority and decoration appearance."""
import tinycss2 as css
from .style_sync import DECORATION_EXPRESSION, _invalid_core_value
from .style_sync import DECORATION_EXPRESSION, _invalid_core_value, _split
dynamic = False
def visit(nodes):
nonlocal dynamic
@@ -100,6 +100,17 @@ def _decoration_variables(source):
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 == 'qualified-rule':
children = css.parse_blocks_contents(declaration.content)
if any(d.type == 'declaration' and d.lower_name in ('text-decoration','text-decoration-line')
and not _invalid_core_value(d.lower_name, d.value) for d in children):
# Suppress the ancestor at the same specificity and in the
# same cascade layer as its authored rule. A global helper
# cannot outrank an ID selector with !important.
selectors = [css.serialize(part).strip() for part in _split(declaration.prelude)]
selectors = [s + ':not(:where([data-mdh-text], pre, pre *))' for s in selectors if s and '::' not in s]
if selectors:
output.extend(css.parse_stylesheet(', '.join(selectors) + '{text-decoration-line:none!important;}'))
if declaration.type!='declaration': continue
value=css.serialize(declaration.value).strip()
suffix=' !important' if declaration.important else ''
+33 -1
View File
@@ -81,5 +81,37 @@ local function quoted_paragraphs(quote)
return block
end})
end
-- Raw metadata has no visible paragraph and does not consume a list number.
-- The style adapter consumes it before the final DOCX is written.
local function contexts(blocks, target, level, depth, item_state)
local output = pandoc.List()
for _, block in ipairs(blocks) do
if block.t == 'OrderedList' or block.t == 'BulletList' then
local nested_target = block.t == 'OrderedList' and 'list_ordered' or 'list_bullet'
for _, item in ipairs(block.content) do
local transformed = contexts(item, nested_target, level + 1, depth, {pending=true})
for i=#item,1,-1 do item:remove(i) end
item:extend(transformed)
end
elseif block.t == 'BlockQuote' then
block.content = contexts(block.content, target, level, depth + 1, item_state)
elseif block.t == 'Div' then
block.content = contexts(block.content, target, level, depth, item_state)
else
if block.t == 'Header' or block.t == 'CodeBlock' or block.t == 'Table' then
local continuation = item_state and not item_state.pending and '1' or '0'
output:insert(pandoc.RawBlock('openxml', '<mdh:context xmlns:mdh="urn:mdhelper:source"' ..
' mdh:list-target="' .. target .. '" mdh:list-level="' .. math.max(0,level) ..
'" mdh:quote-depth="' .. depth .. '" mdh:continuation="' .. continuation .. '"/>'))
end
if item_state and (block.t == 'Para' or block.t == 'Plain' or block.t == 'Header' or block.t == 'CodeBlock' or block.t == 'Table') then
item_state.pending = false
end
end
output:insert(block)
end
return output
end
return {{Inlines=function(items) return mark(items, {}) end},
{BulletList=list_paragraphs, OrderedList=list_paragraphs, BlockQuote=quoted_paragraphs}}
{BulletList=list_paragraphs, OrderedList=list_paragraphs, BlockQuote=quoted_paragraphs},
{Pandoc=function(doc) doc.blocks=contexts(doc.blocks, '', -1, 0, nil); return doc end}}
+10 -4
View File
@@ -238,6 +238,8 @@ def _font_names(value):
if len(tokens) == 1 and tokens[0].type == "string":
names.append(tokens[0].value)
elif tokens and all(t.type == "ident" for t in tokens):
if any(t.lower_value in ('inherit', 'initial', 'unset', 'revert', 'revert-layer', 'default') for t in tokens):
raise ValueError
names.append(" ".join(t.value for t in tokens))
else:
raise ValueError
@@ -286,6 +288,9 @@ def _invalid_core_value(prop, tokens):
group = 'weight'
elif token.type == 'dimension' and token.lower_unit in ('deg','grad','rad','turn'):
if not index or getattr(tokens[index-1], 'lower_value', '') != 'oblique': return True
# Qt's CSS parser accepts some non-degree expressions outside
# the converted interval. Keep those unsupported values as CSS.
if token.lower_unit == 'deg' and not -90 <= token.value <= 90: return True
continue
else: return True
if group in groups: return True
@@ -484,7 +489,7 @@ class _CoreRuleReader:
for key in ('underline', 'strike'):
self.choice('--mdhelper-' + key, key, {'true': True, 'false': False})
return
parts = value.split()
parts = value.lower().split()
if not parts or not set(parts) <= {'none', 'underline', 'line-through'}: raise ValueError
self.rule.update(underline='underline' in parts, strike='line-through' in parts)
@@ -519,7 +524,8 @@ class _CoreRuleReader:
def read(self, prop, convert):
if prop not in self.props:
return
if self.props[prop].lower() in ('inherit', 'unset', 'revert') and prop != 'color':
if self.props[prop].lower() in ('inherit', 'unset', 'revert') and prop != 'color' and not (
prop in ('text-decoration', 'text-decoration-line') and self.props[prop].lower() != 'inherit'):
return
try:
convert(self.props[prop])
@@ -558,14 +564,14 @@ class _CoreRuleReader:
self.rule['font_color'] = '#' + ''.join((f'{round(v * 255):02x}' for v in rgba[:3]))
def tracking(self, value):
amount, unit = (0, 'pt') if value == 'normal' else _length(value, ('pt', 'px'), negative=True)
amount, unit = (0, 'pt') if value.lower() == 'normal' else _length(value, ('pt', 'px'), negative=True)
amount *= 0.75 if unit == 'px' else 1
if abs(amount) > 100:
raise ValueError
self.rule['letter_spacing'] = amount
def line(self, value):
if value == 'normal':
if value.lower() == 'normal':
amount, mode = (1, 'multiple')
elif re.fullmatch('(?:\\d+(?:\\.\\d*)?|\\.\\d+)%?', value):
amount = float(value.rstrip('%')) / (100 if value.endswith('%') else 1)
+63
View File
@@ -0,0 +1,63 @@
"""CSS reset/grammar parity, graphical roundtrips and ancestor suppression."""
import pytest
from PySide6.QtCore import Qt
from mdhelper.style_sync import normalize_payload, analyze_css, patch_core
from mdhelper.style_dialog import DocumentStyleEditorDialog
from mdhelper.docx_exporter import export_markdown_to_docx
from mdhelper.docx_style import W, NS
from test_style_regressions import browser, parts
from docx_assertions import effective_document
@pytest.mark.parametrize('declaration', ['text-decoration:unset','text-decoration-line:UNSET','text-decoration:initial'])
def test_resets_disable_link_and_strike_core_styles(qt_application,tmp_path,declaration):
payload=normalize_payload({'css':f'a{{{declaration}}} s{{{declaration}}}'})
for key in ('link','strike'):
assert payload['rules'][key]['underline'] is False and payload['rules'][key]['strike'] is False
assert normalize_payload(payload)==payload
assert browser(qt_application,tmp_path,payload,'[Link](#x) ~~Strike~~',
"[...document.querySelectorAll('a,s')].map(e=>getComputedStyle(e.querySelector('[data-mdh-text]')||e).textDecorationLine)")==['none','none']
@pytest.mark.parametrize('engine', ['builtin','python-docx','pandoc'])
def test_css_resets_and_uppercase_reach_word(tmp_path,engine):
payload=normalize_payload({'css':'a{text-decoration:unset}s{text-decoration:unset}strong{text-decoration:UNDERLINE}p{line-height:NORMAL}'})
doc,styles=parts(export_markdown_to_docx('[Link](#x) ~~Strike~~ **Bold**',tmp_path/'reset.docx',engine=engine,style_rules=payload['rules']))
rendered=effective_document(doc,styles)
for r in rendered.iter(W+'r'):
text=''.join(r.itertext())
if text in ('Link','Strike','Bold'):
assert r.find('w:rPr/w:u',NS).get(W+'val')==('single' if text=='Bold' else 'none')
if text=='Strike': assert r.find('w:rPr/w:strike',NS).get(W+'val')=='0'
assert rendered.find('.//w:pPr/w:spacing',NS).get(W+'line')=='240'
@pytest.mark.parametrize('invalid', ['italic 30pt inherit','italic 30pt Arial, unset','oblique 200deg 30pt Arial','oblique -200deg 30pt Arial'])
def test_invalid_font_keeps_previous_declarations(qt_application,tmp_path,invalid):
payload=normalize_payload({'css':f'p{{font-size:20pt;font-style:normal;font:{invalid}}}'})
assert payload['rules']['paragraph']['font_size']==20 and payload['rules']['paragraph']['italic'] is False
assert any('已忽略无效' in note for note in analyze_css(payload['css']).notes)
result=browser(qt_application,tmp_path,payload,'Text',"[getComputedStyle(document.querySelector('p')).fontSize,getComputedStyle(document.querySelector('p')).fontStyle]")
assert abs(float(result[0][:-2])-20*96/72)<.01 and result[1]=='normal'
def test_uppercase_and_reset_controls_roundtrip(qt_application):
dialog=DocumentStyleEditorDialog({'css':'p{text-decoration:UNDERLINE;line-height:NORMAL;letter-spacing:NORMAL}'})
try:
assert dialog.bool_boxes['underline'].checkState()==Qt.CheckState.Checked
dialog.bool_boxes['underline'].setCheckState(Qt.CheckState.Unchecked)
assert analyze_css(dialog.style_payload()['css']).rules['paragraph']['underline'] is False
dialog.extra_css_edit.setPlainText('p{text-decoration:UNSET}')
assert dialog.style_payload()['rules']['paragraph']['underline'] is False
assert dialog.bool_boxes['underline'].checkState()==Qt.CheckState.Unchecked
finally:dialog.close()
@pytest.mark.parametrize('selector', ['#mdhelper-reader a','#mdhelper-reader.reader a',':is(#mdhelper-reader) a'])
def test_high_specificity_important_ancestor_does_not_paint_over_inner_toggle(qt_application,tmp_path,selector):
css=selector+'{text-decoration:underline line-through!important}'
css=patch_core(css,'emphasis',{}, {'underline':False})
payload=normalize_payload({'css':css})
result=browser(qt_application,tmp_path,payload,'[Outer *Inner*](#x)',
"[getComputedStyle(document.querySelector('a')).textDecorationLine,...[...document.querySelectorAll('[data-mdh-text]')].map(e=>getComputedStyle(e).textDecorationLine)]")
assert result==['none','underline line-through','line-through']
+6 -2
View File
@@ -106,7 +106,10 @@ def test_word_preserves_all_settings_and_content(tmp_path: Path, engine):
assert spacing.get(W + "before") == spacing.get(W + "after") == "0"
assert spacing.get(W + "line") == "400" and spacing.get(W + "lineRule") == "exact"
ind = ppr.find(W + "ind")
assert ind.get(W + "firstLineChars") == "200" and ind.get(W + "right") == "120"
# List geometry uses absolute lengths so Word's document grid cannot
# shift code/heading continuations away from their list's text column.
assert ind.get(W + "firstLineChars") == ("0" if ppr.find(W + 'numPr') is not None else "200")
assert ind.get(W + "firstLine") == "420" and ind.get(W + "right") == "120"
assert ind.get(W + "left") == "850"
for name, value in (("keepNext", "1"), ("keepLines", "1"), ("contextualSpacing", "1"), ("pageBreakBefore", "0"), ("widowControl", "0")):
assert ppr.find(W + name).get(W + "val") == value
@@ -181,4 +184,5 @@ def test_pandoc_style_processing_preserves_math_links_and_numbering(tmp_path):
levels = xml.findall(".//w:pPr[w:numPr]", NS)
nested = [p for p in levels if p.find("w:numPr/w:ilvl", NS).get(W + "val") == "1"]
assert nested and int(nested[0].find(W + "ind").get(W + "left")) > 720
assert nested[0].find(W + "ind").get(W + "leftChars") == "500"
assert nested[0].find(W + "ind").get(W + "leftChars") == "0"
assert nested[0].find(W + "ind").get(W + "left") == "1200"
+25
View File
@@ -0,0 +1,25 @@
import pytest
from mdhelper.markdown_utils import extract_headings_from_text, heading_locations
from mdhelper.markdown_renderer import MarkdownRenderer
from mdhelper.markdown_editor import MarkdownEditorDialog
@pytest.mark.parametrize('source,expected', [
('````markdown\n```\n# Fake\n````\n\n# Real',[('real',5)]),
('Title\n====\n\nBody',[('title',0)]),
('> # Quoted\n\n1. ### Listed',[('quoted',0),('listed',2)]),
(' # Fake\n\n# Real',[('real',2)]),
('# Same\n\nSame\n----\n\n> # Same',[('same',0),('same-2',2),('same-3',5)]),
('$$\n# Fake\n$$\n\n# Real',[('real',4)]),
])
def test_outline_reader_and_editor_use_identical_headings(qt_application,tmp_path,source,expected):
renderer=MarkdownRenderer(tmp_path);env={};renderer.markdown.parse(source,env)
assert [h.slug for h in extract_headings_from_text(source)]==[h['slug'] for h in env['headings']]
assert [(h.slug,line) for h,line in heading_locations(source)]==expected
editor=MarkdownEditorDialog(tmp_path/'note.md',source,renderer,'light',1,'',16)
try:
for slug,line in expected:
assert editor.scroll_to_heading(slug)
assert editor.editor.textCursor().blockNumber()==line
assert editor._heading_line_for_slug('fake') is None
finally:editor.close();editor.deleteLater()
+52
View File
@@ -0,0 +1,52 @@
"""Nested block geometry and editable style inheritance in all Word engines."""
import pytest
from mdhelper.docx_exporter import export_markdown_to_docx
from mdhelper.docx_style import W, NS
from test_style_regressions import parts
from docx_assertions import effective_document
ENGINES = ('builtin','python-docx','pandoc')
CONTINUED = '1. FirstText\n\n ContinuedText\n\n ### ContinuedHeading\n\n ```text\n CodeFirst\n CodeSecond\n ```\n\n2. LastText'
CODE = '1. ```text\n CodeFirst\n CodeSecond\n ```\n\n2. LastText'
QUOTE = '> ### QuotedHeading\n>\n> ```text\n> QuotedCode\n> ```\n>\n> > ### InnerHeading'
@pytest.mark.parametrize('engine', ENGINES)
def test_continuations_cancel_hanging_and_preserve_parent_styles(tmp_path, engine):
doc, styles = parts(export_markdown_to_docx(CONTINUED,tmp_path/'continued.docx',engine=engine))
effective = effective_document(doc,styles)
for p in effective.iter(W+'p'):
text = ''.join(p.itertext())
if text.startswith(('Continued','Code')):
ind=p.find('w:pPr/w:ind',NS)
assert int(ind.get(W+'left')) == 480
assert ind.get(W+'hanging','0') == ind.get(W+'hangingChars','0') == '0'
assert p.find('w:pPr/w:numPr',NS) is None
heading = next(p for p in doc.iter(W+'p') if ''.join(p.itertext()) == 'ContinuedHeading')
style_id=heading.find('w:pPr/w:pStyle',NS).get(W+'val')
assert 'ListOrdered' in style_id and 'Continuation' in style_id
styles.find("w:style[@w:styleId='MDHelperH3']/w:rPr/w:color",NS).set(W+'val','ff0000')
heading=next(p for p in effective_document(doc,styles).iter(W+'p') if ''.join(p.itertext()) == 'ContinuedHeading')
assert heading.find('w:r/w:rPr/w:color',NS).get(W+'val') == 'ff0000'
assert not any(a.startswith('{urn:mdhelper:source}') for el in doc.iter() for a in el.attrib)
@pytest.mark.parametrize('engine', ENGINES)
def test_multiline_code_remains_one_numbered_paragraph(tmp_path, engine):
doc, _ = parts(export_markdown_to_docx(CODE,tmp_path/'code.docx',engine=engine))
code = next(p for p in doc.iter(W+'p') if 'CodeFirst' in ''.join(p.itertext()))
assert 'CodeSecond' in ''.join(code.itertext()) and code.find('.//w:br',NS) is not None
assert code.find('w:pPr/w:numPr',NS) is not None
@pytest.mark.parametrize('engine', ENGINES)
def test_quote_blocks_keep_container_depth_and_editable_heading_base(tmp_path, engine):
doc, styles = parts(export_markdown_to_docx(QUOTE,tmp_path/'quote.docx',engine=engine))
rendered=effective_document(doc,styles)
for p in rendered.iter(W+'p'):
text=''.join(p.itertext())
if text in ('QuotedHeading','QuotedCode','InnerHeading'):
assert int(p.find('w:pPr/w:ind',NS).get(W+'left')) == (600 if text=='InnerHeading' else 300)
styles.find("w:style[@w:styleId='MDHelperH3']/w:rPr/w:sz",NS).set(W+'val','40')
for p in effective_document(doc,styles).iter(W+'p'):
if 'Heading' in ''.join(p.itertext()): assert p.find('w:r/w:rPr/w:sz',NS).get(W+'val')=='40'
+52
View File
@@ -8,9 +8,15 @@ import sys,tempfile
from pathlib import Path
sys.path.insert(0,str(Path('tests').resolve()))
from test_content_revision_057 import *
from test_style_revision_057 import CONTINUED,CODE,QUOTE
from mdhelper.style_sync import normalize_payload
folder=Path(tempfile.mkdtemp(prefix='MDHelper-057-Word-'))
for engine in ('builtin','python-docx','pandoc'):
export_markdown_to_docx(TABLE_LIST,folder/f'{engine}-table.docx',engine=engine)
for name,source in [('continued',CONTINUED),('code',CODE),('quote',QUOTE)]:
export_markdown_to_docx(source,folder/f'{engine}-{name}.docx',engine=engine)
rules=normalize_payload({'css':'a{text-decoration:unset}s{text-decoration:unset}strong{text-decoration:UNDERLINE}p{font-size:12pt;font:italic 30pt inherit;line-height:NORMAL}'})['rules']
export_markdown_to_docx('[Link](#x) ~~Strike~~ **Bold**',folder/f'{engine}-css.docx',engine=engine,style_rules=rules)
combined=batch.combine_documents([batch.BatchDocument(folder/'chapter.md',HEADING_LIST)],MarkdownRenderer(folder))
export_markdown_to_docx(combined.word_source,folder/'pandoc-combined.docx',engine='pandoc')
print(folder)
@@ -32,6 +38,32 @@ print(folder)
if($r.ListFormat.ListString.Trim() -ne '2.'){throw "$engine numbering restarted"}
Write-Output "$engine table content and numbering PASS"
} finally {$doc.Close(0)}
foreach($case in @('continued','code','quote','css')) {
$doc=$word.Documents.Open((Join-Path $folder "$engine-$case.docx"),$false,$true,$false)
try {
if($case -eq 'css') {
foreach($text in @('Link','Strike','Bold')) {
$r=$doc.Content.Duplicate;[void]$r.Find.Execute($text)
$expectedUnderline=if($text -eq 'Bold'){1}else{0}
if($r.Font.Underline -ne $expectedUnderline -or $r.Font.StrikeThrough -ne 0 -or $r.Font.Size -ne 12){throw "$engine CSS mismatch: $text"}
}
} else {
$doc.ExportAsFixedFormat((Join-Path $folder "$engine-$case.pdf"),17)
if($case -eq 'quote') {
$doc.Styles.Item('MDHelper 标题 3').Font.Size=20
foreach($text in @('QuotedHeading','InnerHeading')) {
$r=$doc.Content.Duplicate;[void]$r.Find.Execute($text)
if($r.Font.Size -ne 20){throw "$engine quote heading no longer inherits its base"}
}
} elseif($case -eq 'continued') {
$doc.Styles.Item('MDHelper 标题 3').Font.Color=255
$r=$doc.Content.Duplicate;[void]$r.Find.Execute('ContinuedHeading')
if($r.Font.Color -ne 255){throw "$engine list heading no longer inherits its base"}
}
}
Write-Output "$engine $case styles PASS"
} finally {$doc.Close(0)}
}
}
$doc=$word.Documents.Open((Join-Path $folder 'pandoc-combined.docx'),$false,$true,$false)
try {
@@ -41,6 +73,26 @@ print(folder)
}
Write-Output 'combined headings PASS'
} finally {$doc.Close(0)}
@'
import sys
from pathlib import Path
from pypdf import PdfReader
folder=Path(sys.argv[1])
for engine in ('builtin','python-docx','pandoc'):
for case in ('continued','code','quote'):
positions={}
def visit(text,cm,tm,font,size):
text=text.strip()
if text:positions[text]=tm[4]*cm[0]+tm[5]*cm[2]+cm[4]
for page in PdfReader(folder/f'{engine}-{case}.pdf').pages:page.extract_text(visitor_text=visit)
words={'continued':['FirstText','ContinuedText','ContinuedHeading','CodeFirst','CodeSecond','LastText'],
'code':['CodeFirst','CodeSecond','LastText'], 'quote':['QuotedHeading','QuotedCode']}[case]
values=[positions[word] for word in words]
assert max(values)-min(values)<.3,(engine,case,positions)
if case=='quote':assert abs(positions['InnerHeading']-positions['QuotedHeading']-15)<.3,(engine,positions)
print(engine,case,'actual Word PDF alignment PASS',positions)
'@ | & $Python -B - $folder
if($LASTEXITCODE -ne 0){throw 'Word PDF alignment failed'}
Write-Output "Fixtures: $folder"
} finally {
if($word){$word.Quit();[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($word)}