diff --git a/docs/user_manual.md b/docs/user_manual.md
index 24d8a1f..1ecd62c 100644
--- a/docs/user_manual.md
+++ b/docs/user_manual.md
@@ -167,6 +167,8 @@ Markdown 支持:
行内代码、表头和单元格的“兼容:代码基准 / 表格基准”表示沿用旧配置。显式选择“文档默认 / 所在段落”会解除该兼容继承;也可以重新选择兼容基准。仅修改名称不会解除原有继承。
+Word 导出通过关联的段落/字符基准保留旧代码设置。在 Word 中修改“MDHelper 代码基准”的字体、字号、颜色,会同步影响未独立覆盖的代码块和行内代码。列表项中的续段不会新增编号;宽松嵌套列表的段落左右边距与列表层级缩进叠加。表格文字继承段落样式时,单元格底色仍由共享表格样式控制,不叠加父段落底色。
+
### 样式面板与 Word 导出
打开“样式 → 样式面板”,可查看全部样式或当前文档已用样式。编辑 Markdown 时,面板提示光标所在段落及其中包含的字符样式。双击条目修改样式名称、同类型基准及格式;改变样式不会改写 Markdown 内容。基于内置样式修改时自动创建自定义样式集,并保留原内置样式的字体、行距等基础信息,导出 Word 和迁移样式文件后继续生效。
diff --git a/mdhelper/docx_exporter.py b/mdhelper/docx_exporter.py
index 5c56829..3137ada 100644
--- a/mdhelper/docx_exporter.py
+++ b/mdhelper/docx_exporter.py
@@ -15,7 +15,7 @@ from markdown_it import MarkdownIt
from markdown_it.token import Token
from .markdown_compat import cjk_strong_plugin
-from .docx_inline import source_style_name, LIST_PARAGRAPH_STYLE, QUOTED_LIST_PARAGRAPH_STYLE, SOURCE_PARAGRAPH_STYLES
+from .docx_inline import source_style_name, LIST_PARAGRAPH_STYLE, QUOTED_LIST_PARAGRAPH_STYLE, SOURCE_PARAGRAPH_STYLES, CONTINUATION
WP_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
@@ -254,6 +254,7 @@ def _add_python_docx_paragraph(document: object, block: ParagraphBlock) -> None:
marker.base_style = document.styles[style]
style = name
paragraph = document.add_paragraph(style=style)
+ if block.continuation: paragraph._p.set(CONTINUATION, '1')
if block.list_kind:
from docx.oxml import parse_xml
paragraph._p.get_or_add_pPr().append(parse_xml(f''))
@@ -332,6 +333,7 @@ class ParagraphBlock:
list_start: int = 1
loose: bool = False
alignment: str = ''
+ continuation: bool = False
@dataclass
@@ -349,6 +351,7 @@ class _DocxBuilder:
self.list_ids: list[int] = []
self.list_starts: list[int] = []
self.list_sequence = 1000
+ self.item_pending: list[bool] = []
self.quote_depth = 0
def build(self) -> list[ParagraphBlock | TableBlock]:
@@ -365,6 +368,10 @@ class _DocxBuilder:
if token.type in {"fence", "code_block"}:
for line in token.content.rstrip("\n").splitlines() or [""]:
self.blocks.append(ParagraphBlock([(line, {"code": True})], style="Code"))
+ elif token.type == 'list_item_open':
+ self.item_pending.append(True)
+ elif token.type == 'list_item_close':
+ self.item_pending.pop()
elif token.type == "blockquote_open":
self.quote_depth += 1
elif token.type == "blockquote_close":
@@ -391,7 +398,9 @@ class _DocxBuilder:
runs = _inline_runs(inline.children if inline is not None else None)
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))
+ 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])))
+ if self.item_pending: self.item_pending[-1] = False
self.index += 3
def _collect_table(self) -> TableBlock:
@@ -496,7 +505,8 @@ def _paragraph_xml(block: ParagraphBlock) -> str:
props.append('')
if block.alignment: props.append(f'')
ppr = f"{''.join(props)}" if props else ""
- return f"{ppr}{''.join(_run_xml(text, style) for text, style in block.runs)}"
+ marker = ' xmlns:mdh="urn:mdhelper:source" mdh:continuation="1"' if block.continuation else ''
+ return f"{ppr}{''.join(_run_xml(text, style) for text, style in block.runs)}"
def _run_xml(text: str, style: dict[str, object]) -> str:
diff --git a/mdhelper/docx_inline.py b/mdhelper/docx_inline.py
index 61834bc..e497629 100644
--- a/mdhelper/docx_inline.py
+++ b/mdhelper/docx_inline.py
@@ -3,6 +3,7 @@ PREFIX = 'MDHelperSource_'
LIST_PARAGRAPH_STYLE = 'MDHelperSourceListParagraph'
QUOTED_LIST_PARAGRAPH_STYLE = 'MDHelperSourceQuotedListParagraph'
SOURCE_PARAGRAPH_STYLES = (LIST_PARAGRAPH_STYLE, QUOTED_LIST_PARAGRAPH_STYLE)
+CONTINUATION = '{urn:mdhelper:source}continuation'
CODES = {'strong': 'B', 'emphasis': 'I', 'strike': 'S', 'link': 'L', 'inline_code': 'C'}
diff --git a/mdhelper/docx_semantic.py b/mdhelper/docx_semantic.py
index cc63d83..4f6e3d9 100644
--- a/mdhelper/docx_semantic.py
+++ b/mdhelper/docx_semantic.py
@@ -13,7 +13,7 @@ from lxml import etree as ET
from .document_style import resolved_rules, normalize_rule, font_points, length_points, number
from .style_catalog import CATALOG, CHARACTER_DEFAULTS, explicit_rules, parent_style, style_name, legacy_base
from .docx_style import W, NS, child, val, properties, _run_properties, _paragraph_properties, _order_properties
-from .docx_inline import source_style_order, ordered_styles, LIST_PARAGRAPH_STYLE, QUOTED_LIST_PARAGRAPH_STYLE, SOURCE_PARAGRAPH_STYLES
+from .docx_inline import source_style_order, ordered_styles, LIST_PARAGRAPH_STYLE, QUOTED_LIST_PARAGRAPH_STYLE, SOURCE_PARAGRAPH_STYLES, CONTINUATION
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()
@@ -137,6 +137,10 @@ class WordStyles:
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)
+ if key in ('table_head', 'table_cell') and base and base != 'table':
+ # Cell shading belongs to the table style. Explicitly cancel any
+ # paragraph shading inherited now or added to its parent in Word.
+ child(child(style, 'pPr'), 'shd').attrib.update({W+'val': 'clear', W+'fill': 'auto'})
val(style, 'next', style_id('paragraph'))
return identifier
@@ -155,6 +159,15 @@ class WordStyles:
base = parent_style(key, self.rules)
base_id = self.character(base) if base else ''
rule = self.character_rule(key)
+ legacy = key == 'inline_code' and not base and legacy_base(key, self.rules)
+ if legacy:
+ base_id = 'MDHelperCodeChar'
+ if base_id not in self.created:
+ paragraph_id = self.paragraph('code')
+ shared = self.new(base_id, 'character', 'MDHelper 代码基准字符')
+ val(shared, 'link', paragraph_id)
+ val(self.created[paragraph_id], 'link', base_id)
+ _run_properties(child(shared, 'rPr'), self.explicit['code'])
# Word cannot clear one inherited character-style property. Preserve
# the resolved remaining properties and inherit color from the text.
if rule.get('font_color') == 'inherit' and base and self.character_rule(base).get('font_color') not in (None, 'inherit'):
@@ -163,7 +176,7 @@ class WordStyles:
_run_properties(child(style, 'rPr'), rule)
if base_id:
old = ET.Element(W + 'rPr')
- _run_properties(old, self.character_rule(base))
+ _run_properties(old, self.explicit['code'] if legacy else self.character_rule(base))
_delta(child(style, 'rPr'), old, normalize_rule(self.rules.get(key)))
return identifier
@@ -290,7 +303,7 @@ class WordStyles:
child(style, 'pPr').append(ind)
return identifier
- def list_paragraph(self, target, base_id):
+ 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'))
if not own: return base_id
@@ -299,6 +312,19 @@ class WordStyles:
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'
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)
@@ -429,6 +455,7 @@ class WordStyles:
def apply(self, document):
for paragraph in document.iter(W + 'p'):
+ continuation = paragraph.attrib.pop(CONTINUATION, '') == '1'
ppr = properties(paragraph, 'pPr')
original_id = reference(ppr, 'pStyle') or 'Normal'
names = {reference(style, 'name') for style in self.chain(original_id)}
@@ -442,8 +469,9 @@ class WordStyles:
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 loose: identifier = self.list_paragraph(target, identifier)
+ 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',))
alignment = reference(ppr, 'jc')
if target in ('table_head','table_cell') and alignment in ('left','center','right','both'):
identifier = self.table_column(target, alignment)
diff --git a/mdhelper/resources/reader.css b/mdhelper/resources/reader.css
index 89fd96a..b1a1002 100644
--- a/mdhelper/resources/reader.css
+++ b/mdhelper/resources/reader.css
@@ -228,7 +228,7 @@ table {
position: absolute;
bottom: 100%;
right: 2px;
- margin-bottom: 4px;
+ padding-bottom: 4px;
display: flex;
justify-content: flex-end;
opacity: 0;
diff --git a/tests/table_hover_smoke.py b/tests/table_hover_smoke.py
new file mode 100644
index 0000000..ec22ea4
--- /dev/null
+++ b/tests/table_hover_smoke.py
@@ -0,0 +1,47 @@
+"""Native pointer regression: reach and click the floating table copy button."""
+import os,sys,time,json,tempfile
+from pathlib import Path
+os.environ.pop('QT_QPA_PLATFORM',None)
+os.environ['QTWEBENGINE_CHROMIUM_FLAGS']='--log-level=3'
+sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
+from PySide6.QtWidgets import QApplication
+from PySide6.QtWebEngineWidgets import QWebEngineView
+from PySide6.QtCore import QPoint,Qt
+from PySide6.QtTest import QTest
+from PySide6.QtGui import QCursor
+from mdhelper.markdown_renderer import MarkdownRenderer
+
+app=QApplication([])
+view=QWebEngineView();view.resize(850,450)
+view.setWindowFlag(Qt.WindowType.WindowStaysOnTopHint,True)
+loaded=[];view.loadFinished.connect(loaded.append)
+
+def wait(condition):
+ end=time.monotonic()+20
+ while not condition() and time.monotonic(){const t=document.querySelector('table').getBoundingClientRect(),b=document.querySelector('button').getBoundingClientRect();return {top:t.top,bottom:b.bottom,by:(b.top+b.bottom)/2,x:(b.left+b.right)/2}})()")
+ target=view.windowHandle()
+ js("(()=>{window.moves=[];document.addEventListener('mousemove',e=>window.moves.push([e.clientX,e.clientY,e.target.tagName]));return true})()")
+ QCursor.setPos(target.mapToGlobal(QPoint(20,20)));QTest.qWait(150)
+ for y in (bounds['top']+10,bounds['top']+1,(bounds['top']+bounds['bottom'])/2,bounds['by']):
+ point=QPoint(round(bounds['x']),round(y))
+ QCursor.setPos(target.mapToGlobal(point));QTest.mouseMove(target,point);QTest.qWait(400)
+ assert js("getComputedStyle(document.querySelector('.table-tools')).opacity")=='1', (y, js("({moves:window.moves,hover:[...document.querySelectorAll(':hover')].map(e=>e.className),width:innerWidth,height:innerHeight})"), app.platformName(), target.size(), view.size())
+ js("(()=>{window.copied=null;Object.defineProperty(navigator,'clipboard',{value:{writeText:async text=>{window.copied=text}}});return true})()")
+ QTest.mouseClick(target,Qt.MouseButton.LeftButton,pos=QPoint(round(bounds['x']),round(bounds['by'])))
+ QTest.qWait(200)
+ assert js('window.copied')=='A\tB\nX\tY'
+ print('Native hover and copy passed: continuous pointer path and expected table text.')
+finally:
+ view.close()
diff --git a/tests/test_style_revision_054.py b/tests/test_style_revision_054.py
new file mode 100644
index 0000000..26a0ec9
--- /dev/null
+++ b/tests/test_style_revision_054.py
@@ -0,0 +1,76 @@
+"""Regressions from the 0.5.3 style and table audit."""
+import pytest
+import zipfile
+from lxml import etree as ET
+from mdhelper.docx_exporter import export_markdown_to_docx
+from mdhelper.docx_style import W, NS
+from mdhelper.style_sync import normalize_payload
+from test_style_regressions import browser, parts
+from docx_assertions import effective_document
+
+ENGINES = ('builtin', 'python-docx', 'pandoc')
+TABLE = '| Head | Description |\n|---|---|\n| Alpha | First |\n| Beta | Second |'
+BACKGROUND_RULES = {'h1': {'background_color': '#ff0000'},
+ 'table_head': {'background_color': '#0000ff'}, 'table_cell': {'background_color': '#00ff00'},
+ '_metadata': {'table_head': {'based_on': 'h1'}, 'table_cell': {'based_on': 'h1'}}}
+CONTINUATION_SOURCE = '1. First\n\n Continuation\n\n2. Second'
+NESTED_SOURCE = '- Outer\n\n - Inner\n\n - NestedSecond\n\n- Second'
+NESTED_RULES = normalize_payload({'css': 'p {margin-left:12pt;} li {margin-left:24pt;}'})['rules']
+CODE_SOURCE = '`Inline`\n\n```text\nBlock\n```'
+CODE_RULES = {'code': {'font_color': '#ff0000', 'font_size': 20, 'font_size_unit': 'pt'}}
+
+
+def test_copy_button_has_continuous_pointer_path(qt_application, tmp_path):
+ assert browser(qt_application, tmp_path, normalize_payload({}), TABLE, """(()=>{
+ const button=document.querySelector('.copy-table-button');button.focus();
+ const b=button.getBoundingClientRect(),t=document.querySelector('table').getBoundingClientRect();
+ const tools=document.querySelector('.table-tools').getBoundingClientRect();
+ return tools.bottom >= t.top && tools.top <= b.top;
+ })()""")
+
+
+@pytest.mark.parametrize('engine', ENGINES)
+def test_table_background_cancels_paragraph_parent_shading(tmp_path, engine):
+ doc, styles = parts(export_markdown_to_docx(TABLE,tmp_path/'shade.docx',engine=engine,style_rules=BACKGROUND_RULES))
+ for p in effective_document(doc,styles).iter(W+'p'):
+ assert p.find('w:pPr/w:shd',NS).get(W+'fill') == 'auto'
+ for key, color in (('firstRow','0000ff'),('band1Horz','00ff00')):
+ assert styles.find(f"w:style[@w:styleId='MDHelperTable']/w:tblStylePr[@w:type='{key}']/w:tcPr/w:shd",NS).get(W+'fill') == color
+ assert not doc.findall('.//w:tcPr/w:shd',NS)
+
+
+@pytest.mark.parametrize('engine', ENGINES)
+def test_list_continuation_does_not_consume_a_number(tmp_path, engine):
+ path=export_markdown_to_docx(CONTINUATION_SOURCE,tmp_path/'list.docx',engine=engine)
+ doc, styles = parts(path)
+ with zipfile.ZipFile(path) as z: numbering=ET.fromstring(z.read('word/numbering.xml'))
+ numbered=[]
+ for p in effective_document(doc,styles).iter(W+'p'):
+ num=p.find('w:pPr/w:numPr',NS)
+ if num is None: continue
+ nid=num.find(W+'numId').get(W+'val')
+ if nid=='0': continue
+ aid=numbering.find(f"w:num[@w:numId='{nid}']/w:abstractNumId",NS).get(W+'val')
+ level=num.find(W+'ilvl').get(W+'val')
+ lvl=numbering.find(f"w:abstractNum[@w:abstractNumId='{aid}']/w:lvl[@w:ilvl='{level}']",NS)
+ if lvl.find(W+'numFmt').get(W+'val')!='none' and lvl.find(W+'lvlText').get(W+'val').strip():
+ numbered.append(''.join(p.itertext()))
+ assert numbered == ['First','Second']
+ assert not any('{urn:mdhelper:source}continuation' in p.attrib for p in doc.iter(W+'p'))
+
+
+@pytest.mark.parametrize('engine', ENGINES)
+def test_loose_nested_list_adds_inner_paragraph_margin(tmp_path, engine):
+ doc, styles = parts(export_markdown_to_docx(NESTED_SOURCE,tmp_path/'nested.docx',engine=engine,style_rules=NESTED_RULES))
+ indents = {''.join(p.itertext()): int(p.find('w:pPr/w:ind',NS).get(W+'left'))/20 for p in effective_document(doc,styles).iter(W+'p')}
+ assert indents['Outer'] == 36 and indents['Inner'] == 72
+
+
+@pytest.mark.parametrize('engine', ENGINES)
+def test_legacy_code_uses_linked_editable_word_base(tmp_path, engine):
+ _, styles = parts(export_markdown_to_docx(CODE_SOURCE,tmp_path/'code.docx',engine=engine,style_rules=CODE_RULES))
+ assert styles.find("w:style[@w:styleId='MDHelperCode']/w:link",NS).get(W+'val') == 'MDHelperCodeChar'
+ assert styles.find("w:style[@w:styleId='MDHelperCodeChar']/w:link",NS).get(W+'val') == 'MDHelperCode'
+ inline = styles.find("w:style[@w:styleId='MDHelperInlineCode']",NS)
+ assert inline.find(W+'basedOn').get(W+'val') == 'MDHelperCodeChar'
+ assert inline.find('w:rPr/w:color',NS) is None
diff --git a/tests/word_revision_054_smoke.ps1 b/tests/word_revision_054_smoke.ps1
new file mode 100644
index 0000000..21b7295
--- /dev/null
+++ b/tests/word_revision_054_smoke.ps1
@@ -0,0 +1,59 @@
+param([string]$Python = (Join-Path $PSScriptRoot '..\mdhelper_env\mdhelper_env\Scripts\python.exe'))
+$ErrorActionPreference='Stop'
+Push-Location (Join-Path $PSScriptRoot '..')
+$word=$null
+try {
+ $folder = (@'
+import sys,tempfile
+from pathlib import Path
+sys.path.insert(0,str(Path('tests').resolve()))
+from test_style_revision_054 import *
+folder=Path(tempfile.mkdtemp(prefix='MDHelper-054-Word-'))
+for engine in ENGINES:
+ for name,source,rules in [('code',CODE_SOURCE,CODE_RULES),('continuation',CONTINUATION_SOURCE,{}),('nested',NESTED_SOURCE,NESTED_RULES),('background',TABLE,BACKGROUND_RULES)]:
+ 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')) {
+ foreach($case in @('code','continuation','nested','background')) {
+ $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('Block')
+ $base=$range.Style.BaseStyle
+ $doc.Styles.Item($base).Font.Color=16711680
+ foreach($text in @('Inline','Block')) {
+ $range=$doc.Content.Duplicate;[void]$range.Find.Execute($text)
+ if($range.Font.Color -ne 16711680){throw "$engine $text does not follow code base: $($range.Font.Color)"}
+ }
+ } elseif($case -eq 'continuation') {
+ foreach($pair in @(@('First','1.'),@('Continuation',''),@('Second','2.'))) {
+ $range=$doc.Content.Duplicate;[void]$range.Find.Execute($pair[0])
+ if($range.ListFormat.ListString.Trim() -ne $pair[1]){throw "$engine $($pair[0]) wrong numbering: $($range.ListFormat.ListString)"}
+ }
+ } elseif($case -eq 'nested') {
+ 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 $($pair[0]) wrong indent: $($range.ParagraphFormat.LeftIndent)"}
+ }
+ } else {
+ $table=$doc.Tables.Item(1)
+ $table.Style.Table.Condition(0).Shading.BackgroundPatternColor=65535
+ if($table.Cell(1,1).Shading.BackgroundPatternColor -ne 65535){throw "$engine table style cannot change header"}
+ foreach($row in @(1,2)) {
+ $range=$table.Cell($row,1).Range.Duplicate;$range.End=$range.End-1
+ if($range.ParagraphFormat.Shading.BackgroundPatternColor -ne -16777216){throw "$engine inherited paragraph shading remains"}
+ }
+ }
+ 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)}
+ Pop-Location
+}