Skip to content

feat(*): allow internal link to point to customized anchors in a page#107

Draft
c-forrest wants to merge 3 commits intoOI-wiki:masterfrom
c-forrest:patch-anchor-link
Draft

feat(*): allow internal link to point to customized anchors in a page#107
c-forrest wants to merge 3 commits intoOI-wiki:masterfrom
c-forrest:patch-anchor-link

Conversation

@c-forrest
Copy link
Contributor

@c-forrest c-forrest commented Sep 2, 2025

closes OI-wiki/OI-wiki#6480

本次 PR 主要实现了如下功能:

  • 识别 Markdown 锚点:允许识别形式为 <a id="ref-id"></a> 的 anchor,并在相应的文档里插入一个相应的 anchor
    • 实际使用的 regex 是 /^<a\b[^>]*\bid="([^"]+)"[^>]*>$/u,即要求字符串以 <a 开始 > 结尾,且包含一个 id 字段,其中,id 字段必须以双引号包围
    • 尽管 regex 写得比较宽泛,预期标签的 id 字段应当和 slugify 的结果基本一致。对于 OI Wiki 的情形,基本上这相当于说,只包含汉字字符、小写英文字母、hyphen 和下划线
  • 添加小节标题锚点:将页面内所有等级的标题都插入一个相应的 anchor
    • 模拟了 mkdocs-material 的 slugify 的实现,把页面小节标题转换为 anchor id (含去重的部分)
  • 生成锚点标签:为了能够(使 latex)兼容这些 anchor 的标签,将所有标签文本用 JS 自带的 sha1 转成 hex 码然后截取前 16 个字符(计 64 个比特)
    • 在实际引用的时候,如果标签的首字母是 ascii,会导致标签后面的文字变成 percent-encoded,所以,索性把所有 unicode 文字都先转换为 percent-encoded(但保持 ascii 部分不变),然后再用 sha1 处理
    • 最后得到的锚点标签的实际格式为 PageName-AnchorID,这一格式有助于后文 typst 识别所在的 section
  • 允许内链引用锚点:改写了 internal link 部分,让它们能够把内链中页面内标签部分识别出来,并引到定义的 anchor 上
    • 改写了 joinRelative 的实现,允许识别裸 anchor 的情形,即 [Something](#ref-id)
    • 改写了 typst 编译的头文件关于引用的部分,允许用 @ref-id[complement] 格式引用任意位置锚点,并输出小节序号和引用所在页码
  • 保证文档渲染效果:对于只含有一个 anchor 的空段落:
    • typst 不添加段落标记,即 #h(2em),否则 typst 会在 pdf 里添加一个空白行
    • latex 需要添加段落标记(即保持原状),否则 latex 会把 anchor 放到前一段落末尾

为查看实际效果,请参考 PDF 的如下章节:

  • 简介 > 格式手册【列表内锚点】
  • 简介 > 数学符号表【表格内锚点】
  • 数学 > 数论 > 同余方程【Details 框前方锚点】
  • 数学 > 数论 > 阶 & 原根【Details 框前方锚点、跨小节引用】

@c-forrest c-forrest force-pushed the patch-anchor-link branch 3 times, most recently from 2671e94 to 1dad854 Compare September 2, 2025 23:46
@c-forrest c-forrest force-pushed the patch-anchor-link branch 2 times, most recently from 947fa6c to ce69819 Compare September 11, 2025 21:54
@c-forrest c-forrest marked this pull request as ready for review September 12, 2025 00:19
@c-forrest c-forrest marked this pull request as draft September 16, 2025 16:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[功能请求] 添加页面 anchor 功能

1 participant