第3讲:每道题嵌题目级双向链接

之前只有点末一张「本点关联」表,做题时想回查某一节、或跳到别处同类题,
得先滚到文件底部。现在 24 道题每题末尾都有一行:

> **关联** · 盘点 §2.1 判据总表 [§1.3 定义] | 上游 — |
> 下游 [点 2 题 1 求秩] | 速查 [十个判据]

四个方向:盘点(定义定理出处)、上游(做这题前要先会)、
下游(这个结论在哪被用)、速查(考前十分钟)。24 题共 96 条出链。

反向索引由同一份映射自动生成,保证对称不漏:
- 盘点 §0.4 从「章节 ↔ 练习文件」升级为「章节 ↔ 题目」,23 节 42 条
- 速查卡「回查」同样升级到题目级,8 条 24 条

锚点规则(实测 Gitea,两条方向相反,容易踩):
  标题 id = user-content- + 小写化(空格→-,其余标点全删)
  同文件 #anchor            → Gitea 自动补前缀
  跨文件 file.md#user-content-anchor → Gitea 不补,必须手写
含公式的标题也核过:`## 问题 3 · 抽象:$AB=O$ 能推出什么`
→ user-content-问题-3--抽象abo-能推出什么($ 与 = 都被删)。

新增 check_md_links.py:校验 md 内部链接的目标文件与锚点是否存在。
本次 11 个文件 235 条链接全部命中,0 异常。
README 补「文件之间怎么跳」「锚点怎么写」两节。
This commit is contained in:
2026-10-23 17:23:23 +08:00
parent 5c51bab7d4
commit 2b1788bea9
13 changed files with 210 additions and 44 deletions
+93
View File
@@ -0,0 +1,93 @@
# -*- coding: utf-8 -*-
"""校验 Markdown 内部链接:目标文件是否存在、锚点是否命中。
Gitea 规则(实测):
标题 id = "user-content-" + anchor(标题原文)
anchor = 小写,保留字母数字汉字与下划线,空格变 -,其余字符全删
同文件链接写 #anchor —— Gitea 渲染时自动补 user-content-
跨文件链接写 file.md#user-content-anchor —— Gitea 不补,必须手写
用法:
python check_md_links.py <目录或文件> [更多...]
"""
import os
import re
import sys
def anchor(title):
out = []
for ch in title.lower():
if ch.isalnum() or ch == '_':
out.append(ch)
elif ch in ' \t':
out.append('-')
return ''.join(out)
def read(p):
with open(p, encoding='utf-8', newline='') as f:
return f.read().replace('\r\n', '\n')
def headings(txt):
return [m.group(1).strip()
for m in re.finditer(r'^#{1,6}\s+(.*)$', txt, re.M)]
def collect(paths):
files = []
for p in paths:
if os.path.isdir(p):
for fn in sorted(os.listdir(p)):
if fn.endswith('.md'):
files.append(os.path.join(p, fn))
else:
files.append(p)
return files
LINK = re.compile(r'\[([^\]]*)\]\(([^)\s]+)\)')
def main(paths):
files = collect(paths)
ids = {}
for p in files:
ids[os.path.abspath(p)] = {anchor(t) for t in headings(read(p))}
bad = 0
total = 0
for p in files:
base = os.path.dirname(p)
txt = read(p)
# 跳过围栏代码块中的链接
txt = re.sub(r'^```.*?^```', '', txt, flags=re.M | re.S)
for text, target in LINK.findall(txt):
if target.startswith(('http://', 'https://', 'mailto:')):
continue
total += 1
if '#' in target:
tfile, frag = target.split('#', 1)
else:
tfile, frag = target, None
tgt = os.path.abspath(os.path.join(base, tfile)) if tfile else os.path.abspath(p)
tag = '%s -> %s' % (os.path.basename(p), target)
if not os.path.exists(tgt):
print(' ✗ 文件不存在 %s' % tag)
bad += 1
continue
if frag is None:
continue
pure = frag[len('user-content-'):] if frag.startswith('user-content-') else frag
if pure not in ids.get(tgt, set()):
print(' ✗ 锚点未命中 %s' % tag)
bad += 1
print('检查 %d 个文件、%d 条内部链接,异常 %d 条' % (len(files), total, bad))
return 0 if bad == 0 else 1
if __name__ == '__main__':
if len(sys.argv) < 2:
raise SystemExit(__doc__)
raise SystemExit(main(sys.argv[1:]))