145 lines
7.0 KiB
Python
145 lines
7.0 KiB
Python
"""Semantic style identities, inheritance and Markdown usage, independent of widgets."""
|
|
from __future__ import annotations
|
|
from dataclasses import dataclass
|
|
from copy import deepcopy
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class StyleDefinition:
|
|
key: str
|
|
name: str
|
|
kind: str
|
|
syntax: str
|
|
base: str = ''
|
|
|
|
|
|
DEFINITIONS = (
|
|
StyleDefinition('paragraph', '正文', 'paragraph', '普通段落'),
|
|
*(StyleDefinition(f'h{i}', f'标题 {i}', 'paragraph', '#' * i + ' 标题') for i in range(1, 7)),
|
|
StyleDefinition('list', '列表基准', 'paragraph', '所有列表项'),
|
|
StyleDefinition('blockquote', '引用', 'paragraph', '> 引用'),
|
|
StyleDefinition('code', '代码基准', 'paragraph', '兼容原代码设置'),
|
|
StyleDefinition('table', '表格基准', 'table', 'Markdown 表格'),
|
|
StyleDefinition('list_bullet', '无序列表', 'paragraph', '- 列表', 'list'),
|
|
StyleDefinition('list_ordered', '有序列表', 'paragraph', '1. 列表', 'list'),
|
|
StyleDefinition('list_task', '任务列表', 'paragraph', '- [ ] 任务', 'list'),
|
|
StyleDefinition('code_block', '代码块', 'paragraph', '围栏代码 / 缩进代码', 'code'),
|
|
StyleDefinition('table_head', '表头文字', 'paragraph', '表格表头'),
|
|
StyleDefinition('table_cell', '单元格文字', 'paragraph', '表格单元格'),
|
|
StyleDefinition('strong', '加粗', 'character', '**文字**'),
|
|
StyleDefinition('emphasis', '强调', 'character', '*文字*'),
|
|
StyleDefinition('strike', '删除线', 'character', '~~文字~~'),
|
|
StyleDefinition('link', '超链接', 'character', '[文字](地址)'),
|
|
StyleDefinition('inline_code', '行内代码', 'character', '`代码`'),
|
|
)
|
|
CATALOG = {item.key: item for item in DEFINITIONS}
|
|
KINDS = {'paragraph': '段落', 'character': '字符', 'table': '表格'}
|
|
CHARACTER_FIELDS = {'chinese_font_family', 'english_font_family', 'font_size', 'font_size_unit',
|
|
'bold', 'italic', 'font_color', 'letter_spacing', 'underline', 'strike', 'background_color'}
|
|
CHARACTER_DEFAULTS = {'strong': {'bold': True}, 'emphasis': {'italic': True}, 'strike': {'strike': True},
|
|
'link': {'font_color': '#0563c1', 'underline': True},
|
|
'inline_code': {'english_font_family': 'Consolas'}}
|
|
|
|
|
|
def normalize_metadata(value):
|
|
result = {}
|
|
if not isinstance(value, dict): return result
|
|
for key, item in value.items():
|
|
if key not in CATALOG or not isinstance(item, dict): continue
|
|
clean = {}
|
|
if isinstance(item.get('name'), str) and item['name'].strip(): clean['name'] = item['name'].strip()[:80]
|
|
base = item.get('based_on')
|
|
if base == '' or isinstance(base, str) and base in CATALOG and CATALOG[base].kind == CATALOG[key].kind and base != key:
|
|
clean['based_on'] = base
|
|
if clean: result[key] = clean
|
|
# Imported cycles are repaired without throwing away independent formatting.
|
|
for key in list(result):
|
|
seen, current = set(), key
|
|
while current:
|
|
if current in seen:
|
|
result[key]['based_on'] = ''
|
|
break
|
|
seen.add(current)
|
|
current = result.get(current, {}).get('based_on', CATALOG[current].base)
|
|
return result
|
|
|
|
|
|
def style_name(key, rules=None):
|
|
return normalize_metadata((rules or {}).get('_metadata')).get(key, {}).get('name', CATALOG[key].name)
|
|
|
|
|
|
def parent_style(key, rules):
|
|
return normalize_metadata(rules.get('_metadata')).get(key, {}).get('based_on', CATALOG[key].base)
|
|
|
|
|
|
def explicit_rules(rules):
|
|
"""Resolve authored declarations only; absent character fields inherit their paragraph."""
|
|
rules = rules if isinstance(rules, dict) else {}
|
|
metadata = normalize_metadata(rules.get('_metadata'))
|
|
result = {}
|
|
def resolve(key):
|
|
if key in result: return result[key]
|
|
base = metadata.get(key, {}).get('based_on', CATALOG[key].base)
|
|
own = rules.get(key, {})
|
|
own = own if isinstance(own, dict) else {}
|
|
inherited = dict(resolve(base)) if base else {}
|
|
if base and CATALOG[key].kind == 'character':
|
|
inherited = {**CHARACTER_DEFAULTS.get(base, {}), **inherited}
|
|
if key in ('table_head', 'table_cell') and not base:
|
|
legacy = rules.get('table') if isinstance(rules.get('table'), dict) else {}
|
|
inherited.update({k: v for k, v in legacy.items() if k not in {'border_color', 'border_width', 'cell_padding'}})
|
|
if key == 'inline_code' and not base:
|
|
legacy = rules.get('code') if isinstance(rules.get('code'), dict) else {}
|
|
inherited.update({k: v for k, v in legacy.items() if k in CHARACTER_FIELDS})
|
|
inherited.update(own)
|
|
if CATALOG[key].kind == 'character': inherited = {k: v for k, v in inherited.items() if k in CHARACTER_FIELDS}
|
|
result[key] = inherited
|
|
return inherited
|
|
for key in CATALOG: resolve(key)
|
|
return result
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class StyleRegion:
|
|
start: int
|
|
end: int
|
|
style: str
|
|
characters: tuple[str, ...] = ()
|
|
|
|
|
|
def token_regions(tokens):
|
|
regions, used, stack = [], set(), []
|
|
inline_styles = {'strong_open': 'strong', 'em_open': 'emphasis', 's_open': 'strike',
|
|
'link_open': 'link', 'code_inline': 'inline_code'}
|
|
for index, token in enumerate(tokens):
|
|
if token.nesting == -1:
|
|
if stack: stack.pop()
|
|
continue
|
|
contexts = [kind for kind, _ in stack]
|
|
target = None
|
|
if token.type == 'heading_open': target = token.tag
|
|
elif token.type in ('fence', 'code_block'): target = 'code_block'
|
|
elif token.type == 'table_open': target = 'table'
|
|
elif token.type in ('th_open', 'td_open'): target = 'table_head' if token.type == 'th_open' else 'table_cell'
|
|
elif token.type == 'list_item_open':
|
|
target = 'list_task' if 'task-list-item' in (token.attrGet('class') or '') else next(
|
|
('list_ordered' if kind == 'ordered_list_open' else 'list_bullet' for kind, _ in reversed(stack)
|
|
if kind in ('ordered_list_open', 'bullet_list_open')), 'list_bullet')
|
|
elif token.type == 'paragraph_open':
|
|
target = next((style for _, style in reversed(stack) if style in ('list_bullet', 'list_ordered', 'list_task', 'table_head', 'table_cell')), None)
|
|
target = target or ('blockquote' if 'blockquote_open' in contexts else 'paragraph')
|
|
if token.nesting == 1: stack.append((token.type, target))
|
|
if target:
|
|
used.add(target)
|
|
children = tokens[index + 1].children if index + 1 < len(tokens) and tokens[index + 1].type == 'inline' else []
|
|
characters = tuple(dict.fromkeys(inline_styles[c.type] for c in children or [] if c.type in inline_styles))
|
|
used.update(characters)
|
|
if token.map: regions.append(StyleRegion(token.map[0], token.map[1], target, characters))
|
|
return regions, used
|
|
|
|
|
|
def document_styles(source):
|
|
from .markdown_renderer import MarkdownRenderer
|
|
from pathlib import Path
|
|
return token_regions(MarkdownRenderer(Path.cwd()).markdown.parse(source, {}))
|