Files
MathNotesVersion2/.workbuddy/tools/md2pdf/fix_gitea_math.py
T
Yimu d27575eb3c 修公式内嵌套 $:点 13 过渡矩阵一行的中文挪出公式
- 14-点13 第 28 行 `\text{$\alpha$ 到 $\beta$ 的过渡矩阵}` 在公式里又套了
  一层 $,KaTeX 在数学模式遇到 $ 会报错,整块公式在网页上露源码。
  拆成「$$P=A^{-1}B$$ + 正文说明」,并把「方向」写成一句提示
- fix_gitea_math.py 新增 scan_nested_dollar():扫描公式内部嵌套 $
  (含跨行 $$ 块),排除 `\tag{$*$}` 这种合法写法;只报告不自动改
2026-11-01 21:47:30 +08:00

387 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
fix_gitea_math.py —— 修复 Gitea 网页端 Markdown 公式/加粗不渲染的问题
【问题一:行内公式不渲染】
Gitea 的解析器 modules/markup/markdown/math/inline_parser.go 规则写死:
收尾 $ 的后一个字节必须 ∈ { 空格, 换行, 行尾, '.', '!', '?', ',', ';', ':', ')', '$' }
开头 $ 的左邻不能是 ASCII 字母/数字或 . ! ? , ; :
中文字与全角标点(,。、;())都是多字节字符,单字节值 ≥ 0x80,全部落空,
于是整对 $...$ 被当作普通文本原样显示。
→ 修法:在收尾 $ 与紧跟的非空白字符之间补一个半角空格。
【问题二:加粗失效】
CommonMark 要求收尾 ** 必须是 right-flanking:
不被空白前导,且(不被标点前导 或 被标点前导但被空白/标点后继)。
形如 **…"一致性"**的 的写法(收尾 ** 前是标点、后是汉字的)不满足条件,
加粗失效,星号会被原样显示(网页与 PDF 皆然)。
→ 修法:在收尾 ** 后补一个半角空格。
用法:
python fix_gitea_math.py --check # 全文统计
python fix_gitea_math.py --check --scope=prob # 只看概率论在学练习/小练/知识点
python fix_gitea_math.py --apply --scope=prob # 就地修复
"""
import os
import re
import subprocess
import sys
import unicodedata
ROOT = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..'))
SCOPES = {
'prob': [
'基于考研的学习/数学一/在学练习/',
'基于考研的学习/数学一/每日小练/',
'基于考研的学习/数学一/知识点/',
],
}
def iter_md_files(scope=None):
"""只处理 git 已跟踪的 .md(排除 参考仓库),与网页上能看到的内容一致。
若 scope 是一个真实目录,则改为直接遍历该目录下的全部 .md(含未跟踪的新文件)。
"""
if scope and os.path.isdir(os.path.join(ROOT, scope)):
base = os.path.join(ROOT, scope)
for dirpath, _dirs, files in os.walk(base):
for fn in sorted(files):
if fn.endswith('.md'):
yield os.path.join(dirpath, fn)
return
out = subprocess.run(['git', 'ls-files', '-z', '--', '*.md'],
cwd=ROOT, capture_output=True, check=True).stdout.decode('utf-8')
prefixes = SCOPES.get(scope) if scope else None
for rel in out.split('\0'):
if not rel or rel.startswith('参考仓库/') or rel.startswith('.workbuddy/'):
continue
if prefixes and not any(rel.startswith(p) for p in prefixes):
continue
yield os.path.join(ROOT, rel.replace('/', os.sep))
# ------------------------------------------------------------------ 遮罩
def mask_code(text):
"""遮罩围栏代码块与行内代码,返回等长字符串(被遮位置为 \\x00)。"""
n = len(text)
mask = [''] * n
def paint(a, b):
for i in range(max(0, a), min(b, n)):
mask[i] = '\x00'
for m in re.finditer(r'(`+)([^\n]*?)\1', text):
paint(m.start(), m.end())
# 围栏代码块:行级状态机(开/闭成对,绝不会误遮到文件末尾)
in_fence = False
pos = 0
for line in text.split('\n'):
ln = len(line)
if re.match(r'^[ \t]*(```|~~~)', line):
in_fence = not in_fence
paint(pos, pos + ln)
elif in_fence:
paint(pos, pos + ln)
pos += ln + 1
return ''.join(c if c else text[i] for i, c in enumerate(mask))
def mask_code_and_math(text):
"""在 mask_code 基础上再遮罩公式(用于加粗判定,避免把公式里的 ** 当粗体)。"""
base = mask_code(text)
mask = list(base)
for a, b in find_math_any(text):
if base[a] == '\x00':
continue
for i in range(a, min(b + 1, len(text))):
mask[i] = '\x00'
return ''.join(mask)
# ------------------------------------------------------------------ 公式
def find_math_any(text):
"""返回 (open_idx, close_idx_inclusive) 列表,绝不跨行。"""
spans = []
i, n = 0, len(text)
while i < n:
c = text[i]
if c == '\\' and i + 1 < n and text[i + 1] == '$':
i += 2
continue
if c == '$' and i + 1 < n and text[i + 1] == '$':
end = text.find('$$', i + 2)
if end != -1 and '\n' not in text[i:end]:
spans.append((i, end + 1))
i = end + 2
continue
if c == '$':
j, close = i + 1, -1
while j < n and text[j] != '\n':
if text[j] == '\\':
j += 2
continue
if text[j] == '$':
close = j
break
j += 1
if close != -1 and close > i + 1:
spans.append((i, close))
i = close + 1
continue
i += 1
return spans
# Gitea 认可的收尾字符(单字节)
END_OK = set('.!?,;:') | {')', ' ', '\n', '$'}
# Gitea 不认可的开头左邻(ASCII 字母数字与下列标点)
BAD_OPEN_PREV = set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.!?,;:')
def is_punct(ch):
return unicodedata.category(ch)[0] in ('P', 'S')
def fix_math(text, mask):
inserts = []
for start, end in find_math_any(text):
if mask[start] == '\x00':
continue
if start > 0 and mask[start - 1] != '\x00' and text[start - 1] in BAD_OPEN_PREV:
inserts.append((start, '公式前'))
pos = end + 1
if pos < len(text) and mask[pos] != '\x00' and text[pos] not in END_OK:
inserts.append((pos, '公式后'))
return inserts
# ------------------------------------------------------------------ 加粗
# ------------------------------------------------------------------ 块级公式
def find_display(text):
"""配对 $$...$$(允许跨行),返回 (open_idx, close_idx)。"""
spans, i = [], 0
while True:
s = text.find('$$', i)
if s == -1:
break
if s > 0 and text[s - 1] == '\\':
i = s + 2
continue
e = text.find('$$', s + 2)
if e == -1:
break
spans.append((s, e))
i = e + 2
return spans
def fix_display(text, mask):
"""Gitea block_parser.go:多行 $$ 块的开头行/收尾行必须让 $$ 独占一行,否则整块被拒。
→ 在多行块的开头 $$ 之后、收尾 $$ 之前各插入一个换行。
(KaTeX 会 trim,渲染结果完全不变。)"""
inserts = []
for s, e in find_display(text):
if mask[s] == '\x00':
continue
if '\n' not in text[s + 2:e]:
continue # 单行块走 inline 分支,无此限制
nl = text.find('\n', s + 2)
if nl == -1:
nl = len(text)
if text[s + 2:nl].strip():
inserts.append((s + 2, '块公式前'))
ls = text.rfind('\n', 0, e) + 1
if text[ls:e].strip():
inserts.append((e, '块公式后'))
return inserts
def fix_bold(text, mask):
"""收尾 ** 被标点前导、被非空白非标点后继 → 右侧补空格,使其成为 right-flanking。"""
stars = [m.start() for m in re.finditer(r'\*\*', text) if mask[m.start()] != '\x00']
inserts = []
is_open = True
for idx in stars:
if is_open:
is_open = False
continue
is_open = True
prev = text[idx - 1] if idx > 0 else ''
nxt = text[idx + 2] if idx + 2 < len(text) else ''
if not prev or not nxt:
continue
if mask[idx - 1] == '\x00' or mask[idx + 2] == '\x00':
continue
if is_punct(prev) and not nxt.isspace() and not is_punct(nxt):
inserts.append((idx + 2, '加粗后'))
return inserts
# ------------------------------------------------------------------ 主流程
def fix_text(text):
mc = mask_code(text)
mcm = mask_code_and_math(text)
inserts = fix_bold(text, mcm) + fix_math(text, mc) + fix_display(text, mc)
if not inserts:
return text, []
seen = set()
uniq = []
for pos, kind in inserts:
if (pos, kind) in seen:
continue
seen.add((pos, kind))
uniq.append((pos, kind))
for pos, kind in sorted(uniq, reverse=True):
text = text[:pos] + ('\n' if kind.startswith('块公式') else ' ') + text[pos:]
return text, sorted(uniq, key=lambda x: x[0])
FM_MAP = [('$+$', '+'), ('$-$', '-'), ('$=$', '='), (r'$\to$', '→'),
(r'$\times$', '×'), ('$<$', '<'), ('$>$', '>')]
def fix_frontmatter(text):
"""Gitea 把 front matter 渲染成表格时**不解析 markdown**,
因此信息块里的 ``$...$`` 与反引号会原样露出(网页抓取才看得见)。
这里把常见符号转成纯字符,并去掉残留的 ``$`` 与反引号。"""
if not text.startswith('---'):
return text, 0
end = text.find('\n---', 3)
if end < 0:
return text, 0
head, tail = text[:end], text[end:]
hits = 0
lines = []
for ln in head.split('\n'):
if '$' not in ln and '`' not in ln:
lines.append(ln)
continue
hits += 1
for a, b in FM_MAP:
ln = ln.replace(a, b)
ln = ln.replace('$', '').replace('`', '')
lines.append(ln)
return '\n'.join(lines) + tail, hits
def scan_math_underscore(text):
"""公式内部写 ``______`` 会被 KaTeX 当成连续空下标,抛
``Expected group after '_'`` 导致整块渲染失败(网页端显示成源码)。
改法取决于题目意图(改成 ``\\underline{\\quad}`` 、或把空位挪到公式外),
无法自动修,因此只报告、不纳入 ``--apply`` 。"""
base = mask_code(text)
hits = []
for a, b in find_math_any(base):
seg = text[a:b + 1]
if '__' in seg.replace('\\_', ''):
hits.append((text.count('\n', 0, a) + 1, seg.replace('\n', ' ')[:90]))
return hits
def scan_nested_dollar(text):
"""公式内部又写了一层 ``$`` (典型:``$$P=A^{-1}B\\ (\\text{$\\alpha$ 到 $\\beta$ 的过渡矩阵})$$`` )。
KaTeX 在数学模式里遇到 ``$`` 会直接报错,整块公式在网页上原样露出源码;
而本地 md 预览用的是另一条渲染链,往往看不出问题。改法是把中文挪出公式、
公式只留 ``P=A^{-1}B`` ,或删掉内层 ``$`` ,取决于句子结构,故只报告不自动修。"""
hits = []
def check(lineno, seg):
inner = seg
for mark in ('$$', '$'):
if inner.startswith(mark):
inner = inner[len(mark):]
break
for mark in ('$$', '$'):
if inner.endswith(mark):
inner = inner[:-len(mark)]
break
if '$' in inner.replace('\\$', ''):
# \tag{$*$} 是 KaTeX 支持的写法(编号用星号),不算嵌套
if re.search(r'\$', re.sub(r'\\tag\{[^{}]*\}', '', inner).replace('\\$', '')):
hits.append((lineno, seg.replace('\n', ' ')[:90]))
# 1) 单行公式(含写在一行里的 $$...$$)
base = mask_code(text)
for a, b in find_math_any(base):
check(text.count('\n', 0, a) + 1, text[a:b + 1])
# 2) 跨行的 $$ ... $$ 块
lines = text.split('\n')
inblock, start = False, 0
for k, line in enumerate(lines):
st = line.strip()
if not st.startswith('$$') or st.count('$$') >= 2:
continue
inblock = not inblock
if inblock:
start = k
else:
check(start + 1, '\n'.join(lines[start:k + 1]))
return sorted(set(hits))
def main():
apply = '--apply' in sys.argv
scope = None
for a in sys.argv:
if a.startswith('--scope='):
scope = a.split('=', 1)[1]
total_files = total_hits = 0
report = []
warn = []
warn2 = []
for path in sorted(iter_md_files(scope)):
raw = open(path, encoding='utf-8').read()
rel = os.path.relpath(path, ROOT)
for ln, seg in scan_math_underscore(raw):
warn.append((rel, ln, seg))
for ln, seg in scan_nested_dollar(raw):
warn2.append((rel, ln, seg))
new, changes = fix_text(raw)
new2, fm_hits = fix_frontmatter(new)
if fm_hits:
changes = list(changes) + [(-1, '信息块') for _ in range(fm_hits)]
new = new2
if changes:
total_files += 1
total_hits += len(changes)
rel = os.path.relpath(path, ROOT)
report.append((rel, len(changes)))
if apply:
open(path, 'w', encoding='utf-8', newline='').write(new)
print(f'== {"已修复" if apply else "待修复(仅统计)"} ==')
for rel, cnt in report:
print(f' {cnt:4d} {rel}')
print(f'--- 共 {total_files} 个文件,{total_hits} 处需要修 ---')
if warn:
print()
print('== 提示:公式内连续下划线(KaTeX 会整块渲染失败,需手工改)==')
for rel, ln, seg in warn:
print(f' L{ln:<5d}{rel}')
print(f' {seg}')
print(f'--- 共 {len(warn)} 处,请把空位挪到公式外或改用 \\underline{{\\quad}} ---')
if warn2:
print()
print('== 提示:公式内部嵌套 $(KaTeX 报错,整块露源码,需手工改)==')
for rel, ln, seg in warn2:
print(f' L{ln:<5d}{rel}')
print(f' {seg}')
print(f'--- 共 {len(warn2)} 处,请把中文挪出公式,或删掉内层 $ ---')
if __name__ == '__main__':
main()