54 lines
2.3 KiB
Python
54 lines
2.3 KiB
Python
"""Resolve the style cascade for appearance assertions; never modifies the DOCX."""
|
|
from copy import deepcopy
|
|
from lxml import etree as ET
|
|
from mdhelper.docx_style import W, NS
|
|
|
|
|
|
def effective_document(document, styles):
|
|
result = deepcopy(document)
|
|
by_id = {s.get(W + 'styleId'): s for s in styles.findall(W + 'style')}
|
|
|
|
def merge(target, source):
|
|
if source is None: return
|
|
for node in source:
|
|
old = target.find(node.tag)
|
|
if old is None: target.append(deepcopy(node))
|
|
elif node.tag in {W + 'rFonts', W + 'spacing', W + 'ind'}: old.attrib.update(node.attrib)
|
|
else:
|
|
target.replace(old, deepcopy(node))
|
|
|
|
def resolve(identifier, tag, seen=()):
|
|
result = ET.Element(W + tag)
|
|
if identifier in seen or identifier not in by_id: return result
|
|
style = by_id[identifier]
|
|
parent = style.find(W + 'basedOn')
|
|
if parent is not None: merge(result, resolve(parent.get(W + 'val'), tag, seen + (identifier,)))
|
|
merge(result, style.find(W + tag))
|
|
return result
|
|
|
|
for paragraph in result.iter(W + 'p'):
|
|
direct = paragraph.find(W + 'pPr')
|
|
if direct is None:
|
|
direct = ET.Element(W + 'pPr'); paragraph.insert(0, direct)
|
|
style = direct.find(W + 'pStyle')
|
|
identifier = style.get(W + 'val') if style is not None else 'Normal'
|
|
ppr = resolve(identifier, 'pPr')
|
|
merge(ppr, direct)
|
|
paragraph.replace(direct, ppr)
|
|
for run in paragraph.iter(W + 'r'):
|
|
direct = run.find(W + 'rPr')
|
|
rpr = resolve(identifier, 'rPr')
|
|
ref = direct.find(W + 'rStyle') if direct is not None else None
|
|
if ref is not None:
|
|
character = resolve(ref.get(W + 'val'), 'rPr')
|
|
for tag in ('b', 'bCs', 'i', 'iCs', 'strike'):
|
|
node, inherited = character.find(W + tag), rpr.find(W + tag)
|
|
if node is not None and inherited is not None:
|
|
on = lambda n: n.get(W + 'val', '1') not in ('0', 'false', 'off')
|
|
node.set(W + 'val', str(int(on(node) != on(inherited))))
|
|
merge(rpr, character)
|
|
merge(rpr, direct)
|
|
if direct is not None: run.replace(direct, rpr)
|
|
else: run.insert(0, rpr)
|
|
return result
|