fix: preserve nested Word structures and synchronize valid font families

This commit is contained in:
2026-11-05 21:54:52 +08:00
parent 0e072eed3b
commit 7f81c2015e
12 changed files with 292 additions and 28 deletions
+5 -3
View File
@@ -113,9 +113,11 @@ def main(argv: list[str] | None = None) -> int:
app.setOrganizationName("MDHelper")
settings = QSettings("MDHelper", "MDHelper")
if project_root is None:
last_project_root = Path(str(settings.value("project/last_root", ""))).expanduser()
if str(last_project_root) and last_project_root.exists():
project_root = last_project_root.resolve()
last_root = settings.value("project/last_root", "")
if isinstance(last_root, str) and last_root.strip():
last_project_root = Path(last_root).expanduser()
if last_project_root.is_dir():
project_root = last_project_root.resolve()
logging.getLogger(__name__).info(
"Starting MDHelper %s with project_root=%s content_root=%s log_root=%s",
+17 -4
View File
@@ -248,7 +248,10 @@ def _pandoc_list_tables(source: str) -> str:
if match:
prefix, marker, spacing = match.groups()
indent = prefix + ' ' * (len(marker) + len(spacing))
lines[row] = match.group() + '\n' + prefix + '\n' + indent + lines[row][match.end():]
# A bare '-' after parent text is a Setext heading underline.
# '+' is the same bullet without changing the parent's tightness.
marker = '+' if marker == '-' else marker
lines[row] = prefix + marker + spacing + '\n' + prefix + '\n' + indent + lines[row][match.end():]
return ''.join(lines)
@@ -324,6 +327,7 @@ def _add_python_docx_table(document: object, block: TableBlock) -> None:
if block.list_target:
table._tbl.set(LIST_TARGET, block.list_target)
table._tbl.set(LIST_LEVEL, str(block.list_level))
if block.quote_depth: table._tbl.set(QUOTE_DEPTH, str(block.quote_depth))
table.style = "Table Grid"
for row_index, row in enumerate(block.rows):
for col_index in range(column_count):
@@ -371,6 +375,7 @@ class TableBlock:
alignments: list[str] = field(default_factory=list)
list_target: str = ''
list_level: int = 0
quote_depth: int = 0
class _DocxBuilder:
@@ -415,6 +420,8 @@ class _DocxBuilder:
elif token.type == "blockquote_close":
self.quote_depth = max(0, self.quote_depth - 1)
elif token.type in ('bullet_list_open', 'ordered_list_open'):
if self.item_pending and self.item_pending[-1]:
self._append_list_marker()
self.list_stack.append('bullet' if token.type == 'bullet_list_open' else 'number')
self.list_sequence += 1
self.list_ids.append(self.list_sequence)
@@ -427,7 +434,7 @@ class _DocxBuilder:
self.list_quote_depths.pop()
elif token.type == "table_open":
if self.item_pending and self.item_pending[-1]:
self._append_paragraph([], 'Normal', self.list_stack[-1])
self._append_list_marker()
self.blocks.append(self._collect_table())
continue
elif token.type == "hr":
@@ -435,6 +442,12 @@ class _DocxBuilder:
self.index += 1
return self.blocks
def _append_list_marker(self) -> None:
self._append_paragraph([], 'Normal', self.list_stack[-1])
# The marker belongs to the list item, outside its leading quote/table.
self.blocks[-1].quote_depth = self.list_quote_depths[-1]
self.blocks[-1].inner_quote = False
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)
@@ -474,7 +487,7 @@ class _DocxBuilder:
self.index += 1
break
self.index += 1
return TableBlock(rows, alignments, self.item_targets[-1] if self.item_targets else '', max(0, len(self.list_stack)-1))
return TableBlock(rows, alignments, self.item_targets[-1] if self.item_targets else '', max(0, len(self.list_stack)-1), self.quote_depth)
def _inline_runs(children: list[Token] | None) -> list[tuple[str, dict[str, object]]]:
@@ -599,7 +612,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 ''
marker = f' xmlns:mdh="urn:mdhelper:source" mdh:list-target="{block.list_target}" mdh:list-level="{block.list_level}" mdh:quote-depth="{block.quote_depth}"' if block.list_target or block.quote_depth else ''
rows = []
for row in block.rows:
cells = []
+35 -13
View File
@@ -142,7 +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 key in ('list', 'blockquote') 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',))
@@ -151,7 +151,7 @@ class WordStyles:
if base:
for tag, writer in (('pPr', _paragraph_properties), ('rPr', _run_properties)):
base_props = ET.Element(W + tag)
base_rule = absolute_indents(self.effective[base]) if base == 'list' or base in LIST_TARGETS else self.effective[base]
base_rule = absolute_indents(self.effective[base]) if base in ('list', 'blockquote') 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)))
@@ -393,7 +393,7 @@ class WordStyles:
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):
def quoted_block(self, base_id, target, depth, *, offset_depth=None):
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)
@@ -408,12 +408,13 @@ class WordStyles:
ind = base.find('w:pPr/w:ind', NS)
if ind is not None: attributes.update(ind.attrib)
points = font_points(self.effective['paragraph'])
offset_depth = depth if offset_depth is None else offset_depth
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, str(round((value + padding * offset_depth) * 20)))
props.set(W + side + 'Chars', '0')
return identifier
@@ -486,6 +487,10 @@ class WordStyles:
rpr = numbering_level.find(W + 'rPr')
if rpr is not None: remove_fields(rpr, ('rFonts',))
def table_padding(self, side):
rule = self.effective['table']
return number(rule.get('cell_padding', font_points(rule) * (.76 if side in ('left', 'right') else .62)))
def table(self):
identifier = style_id('table')
style = self.new(identifier, 'table', 'MDHelper ' + style_name('table', self.rules))
@@ -504,7 +509,7 @@ class WordStyles:
element.attrib.update({W + 'val': border if visible else 'none', W + 'sz': str(max(2, round(width * 8))), W + 'color': color.lstrip('#') if color != 'transparent' else 'auto'})
margins = child(props, 'tblCellMar')
for side in ('top', 'left', 'bottom', 'right'):
padding = number(rule.get('cell_padding', font_points(rule) * (.76 if side in ('left', 'right') else .62)))
padding = self.table_padding(side)
child(margins, side).attrib.update({W + 'w': str(round(padding * 20)), W + 'type': 'dxa'})
if 'background_color' in rule:
child(child(style, 'tcPr'), 'shd').attrib.update({W + 'val': 'clear', W + 'fill': str(rule['background_color']).lstrip('#') if rule['background_color'] != 'transparent' else 'auto'})
@@ -558,7 +563,7 @@ class WordStyles:
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)
context_level = int(paragraph.attrib.pop(LIST_LEVEL, '0'))
ppr = properties(paragraph, 'pPr')
original_id = reference(ppr, 'pStyle') or 'Normal'
names = {reference(style, 'name') for style in self.chain(original_id)}
@@ -571,7 +576,7 @@ class WordStyles:
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
if target.startswith('list_') and target != 'list_task' and list_target in LIST_TARGETS: target = list_target
identifier = self.paragraph(target)
numpr = ppr.find(W + 'numPr')
if numpr is not None:
@@ -599,11 +604,20 @@ class WordStyles:
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)
elif target == 'blockquote' and list_target in LIST_TARGETS:
base = self.nested_list(list_target, context_level) if context_level else self.paragraph(list_target)
identifier = self.quoted_list(list_target, base, context_level)
marker = self.effective[list_target].get('list_marker')
if marker and not continuation: self.apply_list_marker(numpr, list_target, marker)
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)
if quote_depth:
# The legacy quote paragraph style already represents its first
# quote. Keep that base editable and add only deeper containers.
standalone_quote = target == 'blockquote' and list_target not in LIST_TARGETS
offset = quote_depth - 1 if standalone_quote else quote_depth
if offset: identifier = self.quoted_block(identifier, target, quote_depth, offset_depth=offset)
alignment = reference(ppr, 'jc')
if target in ('table_head','table_cell') and alignment in ('left','center','right','both'):
identifier = self.table_column(target, alignment)
@@ -613,11 +627,19 @@ class WordStyles:
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)
depth = int(table.attrib.pop(QUOTE_DEPTH, '0')); 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))})
if list_target in LIST_TARGETS or depth:
left = 0
if list_target in LIST_TARGETS:
rule = self.contextual_list_rule(list_target, {}, level)
left = rule['left_indent_value']
left += (font_points(self.effective['paragraph']) + 3) * depth
# With no tblInd, Word aligns the table edge at the margin.
# An explicit tblInd instead positions the first cell's text.
# Retain the cell inset so the whole table moves by the context.
left += self.table_padding('left')
child(props, 'tblInd').attrib.update({W+'type':'dxa', W+'w':str(round(left * 20))})
remove_fields(props, ('tblBorders', 'tblCellMar', 'shd'))
val(props, 'tblStyle', style_id('table'))
child(props, 'tblLayout').set(W + 'type', 'autofit')
+5 -2
View File
@@ -50,7 +50,9 @@ local function list_paragraphs(list)
for _, item in ipairs(list.content) do
-- Word numbers paragraphs, not tables. Give a table-first item its own
-- empty numbered paragraph; its following text remains a continuation.
if item[1] and item[1].t == 'Table' then
local first = item[1]
while first and (first.t == 'BlockQuote' or first.t == 'Div') do first = first.content[1] end
if first and first.t == 'Table' then
item:insert(1, pandoc.Div({pandoc.Para({pandoc.Str('\u{200b}')})},
pandoc.Attr('', {}, {['custom-style']='MDHelperSourceTableMarker'})))
end
@@ -98,7 +100,8 @@ local function contexts(blocks, target, level, depth, 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
if block.t == 'Header' or block.t == 'CodeBlock' or block.t == 'Table' or
(depth > 0 and (block.t == 'Para' or block.t == 'Plain')) 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) ..
+1 -1
View File
@@ -238,7 +238,7 @@ 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):
if len(tokens) == 1 and tokens[0].lower_value in ('inherit', 'initial', 'unset', 'revert', 'revert-layer', 'default'):
raise ValueError
names.append(" ".join(t.value for t in tokens))
else: