Skip to content
This repository was archived by the owner on Nov 23, 2026. It is now read-only.

Commit 793dd43

Browse files
committed
Add the Sphinx ids to headings as anchor aliases
1 parent f7a45aa commit 793dd43

5 files changed

Lines changed: 134 additions & 4 deletions

File tree

‎admin/convert.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ function load_filters(): array
7070
'doc_link',
7171
'admonitions',
7272
'includes',
73+
'anchor_aliases',
7374
];
7475

7576
foreach (array_unique(array_merge($beforeFilters, $afterFilters)) as $filter) {

‎admin/filters/anchor_aliases.php‎

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* Appends the ids that Sphinx gave each heading, so that links to the old anchors still land.
7+
*/
8+
function after_filter_anchor_aliases(string $data, string $folder, string $path): ?string
9+
{
10+
$queues = [];
11+
12+
$page = substr($path, strlen(dirname(__DIR__, 2) . '/docs/'), -strlen('.md'));
13+
14+
foreach (alias_entries($page) as $entry) {
15+
$queues[$entry['slug']][] = $entry['ids'];
16+
}
17+
18+
if ($queues === []) {
19+
return $data;
20+
}
21+
22+
$fence = null;
23+
$lines = explode("\n", $data);
24+
25+
foreach ($lines as $i => $line) {
26+
if (preg_match('/^\s*(```+|~~~+)/', $line, $matches) === 1) {
27+
$fence = $fence === null ? $matches[1][0] : ($matches[1][0] === $fence ? null : $fence);
28+
29+
continue;
30+
}
31+
32+
if ($fence !== null || preg_match('/^#{1,6}\s+(.+?)\s*$/', $line, $matches) !== 1) {
33+
continue;
34+
}
35+
36+
$slug = heading_slug(html_entity_decode(preg_replace('/\[([^\]]*)\]\([^)]*\)/', '$1', $matches[1]), ENT_QUOTES | ENT_HTML5));
37+
38+
foreach (isset($queues[$slug]) ? array_shift($queues[$slug]) : [] as $id) {
39+
$lines[$i] .= sprintf('<a id="%s"></a>', $id);
40+
}
41+
}
42+
43+
return implode("\n", $lines);
44+
}
45+
46+
/**
47+
* The headings of the source page `$page` in order, each with its MkDocs slug and the Sphinx ids that differ from it.
48+
*
49+
* @return list<array{slug: string, ids: list<string>}>
50+
*/
51+
function alias_entries(string $page): array
52+
{
53+
$file = source_dir() . $page . '.rst';
54+
55+
if (!is_file($file)) {
56+
return [];
57+
}
58+
59+
$lines = file($file, FILE_IGNORE_NEW_LINES);
60+
$entries = [];
61+
$labels = [];
62+
$namespace = '';
63+
$class = '';
64+
65+
foreach ($lines as $i => $line) {
66+
if (preg_match('/^\s*\.\. _([^:`]+):\s*$/', $line, $matches) === 1) {
67+
$labels[] = docutils_id($matches[1]);
68+
} elseif (is_rst_heading($lines, $i)) {
69+
$text = rst_heading_text($line);
70+
$entries[] = alias_entry(heading_slug($text), [...$labels, docutils_id($text)]);
71+
$labels = [];
72+
} elseif (preg_match('/^\s*\.\.\s+php:(namespace|class|interface|trait|method|staticmethod|function|attr|const):: *(.+?)\s*$/', $line, $matches) === 1) {
73+
[, $kind, $signature] = $matches;
74+
$name = preg_replace('/[\s(].*$/', '', $signature);
75+
$prefix = $namespace === '' ? '' : $namespace . '\\';
76+
77+
if ($kind === 'namespace') {
78+
$namespace = $signature;
79+
$class = '';
80+
$entries[] = alias_entry(heading_slug($signature), ['namespace-' . $signature]);
81+
} elseif (in_array($kind, ['class', 'interface', 'trait'], true)) {
82+
$class = $prefix . $name;
83+
$entries[] = alias_entry(heading_slug($name), [$class]);
84+
} else {
85+
$owner = $class !== '' && !in_array($kind, ['function', 'const'], true) ? $class . '::' : $prefix;
86+
$entries[] = alias_entry(heading_slug($kind === 'const' ? $name : $signature), [$owner . $name]);
87+
}
88+
}
89+
}
90+
91+
return $entries;
92+
}
93+
94+
/**
95+
* The entry for a heading with the MkDocs slug `$slug`, keeping only the ids of `$ids` that differ from it.
96+
*
97+
* @param list<string> $ids
98+
*
99+
* @return array{slug: string, ids: list<string>}
100+
*/
101+
function alias_entry(string $slug, array $ids): array
102+
{
103+
return ['slug' => $slug, 'ids' => array_values(array_unique(array_diff($ids, [$slug, ''])))];
104+
}
105+
106+
/**
107+
* The MkDocs slug of the heading text `$text`, which Python-Markdown reads without its HTML tags.
108+
*/
109+
function heading_slug(string $text): string
110+
{
111+
return markdown_slug(preg_replace('/<[^>]*>/', '', $text));
112+
}
113+
114+
/**
115+
* The id that docutils makes from the section title or label `$text`.
116+
*/
117+
function docutils_id(string $text): string
118+
{
119+
return preg_replace('/^[-0-9]+|-+$/', '', preg_replace('/[^a-z0-9]+/', '-', strtolower($text)));
120+
}

‎admin/filters/doc_link.php‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ function rst_anchors(): array
116116
if (preg_match('/^\s*\.\. _([^:`]+):\s*$/', $line, $matches) === 1) {
117117
$labels[] = strtolower($matches[1]);
118118
} elseif (is_rst_heading($lines, $i)) {
119-
$text = preg_replace(['/:[\w:.+-]+:(?=`)/', '/\s*<[^`<>]*>(?=`)/'], '', $line);
119+
$text = rst_heading_text($line);
120120
$anchor = unique_anchor(markdown_slug($text), $anchors);
121121

122122
$targets['titles'][$page] ??= trim($line);
@@ -134,6 +134,14 @@ function rst_anchors(): array
134134
return $targets;
135135
}
136136

137+
/**
138+
* The RST section title `$line` without its role names and link targets.
139+
*/
140+
function rst_heading_text(string $line): string
141+
{
142+
return preg_replace(['/:[\w:.+-]+:(?=`)/', '/\s*<[^`<>]*>(?=`)/'], '', $line);
143+
}
144+
137145
/**
138146
* RST reference name of the link text or section title `$text`, compared case-insensitively with its whitespace collapsed.
139147
*/

‎admin/how_to_use_filters.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ all before filters on every page, then pandoc on every page, then all after filt
2323

2424
| Filter | Before | After |
2525
| --- | --- | --- |
26-
| `includes` | Replaces each `literalinclude`, `code-block` and `::` literal block with a `CodeBlockPlaceholder<n>` line | Runs last, and replaces each placeholder with its code as a fenced block |
26+
| `includes` | Replaces each `literalinclude`, `code-block` and `::` literal block with a `CodeBlockPlaceholder<n>` line | Replaces each placeholder with its code as a fenced block |
27+
| `anchor_aliases` | | Runs last, and appends an empty `<a id>` to each heading for the ids that Sphinx gave it: its RST labels, its docutils id and its PHP object id, so that links to the old anchors still land |
2728
| `doc_link` | Converts `:doc:`, `:ref:` and `:php:*:` roles, external links and `\|version\|` | Unescapes the link syntax and converts `title-ref` and label spans |
2829
| `class_reference` | Converts `php:namespace`, `php:class`, `php:interface`, `php:trait`, `php:method`, `php:function`, `php:attr`, `php:const` and their fields into headings and lists | Unescapes `\#` |
2930
| `list_indentation` | Adds the blank line that pandoc needs between a directive and a list that starts its body | Re-indents nested lists by four spaces per level and adds the blank line that Python-Markdown needs before a list |

‎admin/verify.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -337,7 +337,7 @@ function parse_markdown(string $path): array
337337
$result['prose'][$no + 1] = $line;
338338

339339
if (preg_match('/^#{1,6}\s+(.+?)\s*$/', $line, $matches)) {
340-
$result['headings'][] = ['line' => $no + 1, 'text' => normalise_signature(html_entity_decode($matches[1], ENT_QUOTES | ENT_HTML5))];
340+
$result['headings'][] = ['line' => $no + 1, 'text' => normalise_signature(html_entity_decode(preg_replace('/<a id="[^"]*"><\/a>/', '', $matches[1]), ENT_QUOTES | ENT_HTML5))];
341341
}
342342

343343
if (preg_match('/^(\s*)!!!\s+\w+(.*)$/', $line, $matches)) {
@@ -488,7 +488,7 @@ function check_leftovers(array &$checks, array $markdown, string $outputFile): v
488488
'leftover-div' => '/<div\b/i',
489489
'leftover-table' => '/<table\b/i',
490490
'leftover-span' => '/<span\b/i',
491-
'leftover-a' => '/<a\s/i',
491+
'leftover-a' => '/<a\s(?!id="[^"]*"><\/a>)/i',
492492
'leftover-directives' => '/^\s*\.\.\s+[A-Za-z][\w:-]*::/',
493493
'leftover-roles' => '/:(doc|ref|php:[a-z]+):/',
494494
'leftover-empty-links' => '/\]\(\)/',

0 commit comments

Comments
 (0)