Skip to content

Commit e7c1656

Browse files
committed
fix: keep underscores in identifier heading anchors
1 parent 370af6f commit e7c1656

1 file changed

Lines changed: 24 additions & 5 deletions

File tree

‎scripts/lib/anchors.mjs‎

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,31 @@ import fs from 'fs';
1313
import GithubSlugger from 'github-slugger';
1414
import { HEADING_ID } from '../../plugins/remark-heading-id.mjs';
1515

16+
// Emphasis, per CommonMark: `*` opens and closes anywhere, including inside a
17+
// word, while `_` does not do so intraword. Keeping that distinction is what
18+
// lets an identifier heading (`flexible_http_request`,
19+
// `canister_inspect_message`) keep the underscores the site slugs it with,
20+
// while *emphasis* is still stripped. One rule over both delimiters read
21+
// `_http_` as emphasis and dropped it.
22+
const STAR_EMPHASIS = /\*{1,3}([^*]+)\*{1,3}/g;
23+
const UNDERSCORE_EMPHASIS = /(^|[^\w])_{1,3}([^_]+)_{1,3}(?=[^\w]|$)/g;
24+
1625
function renderedText(heading) {
17-
return heading
18-
.replace(/`([^`]*)`/g, '$1')
19-
.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
20-
.replace(/[*_]{1,3}([^*_]+)[*_]{1,3}/g, '$1')
21-
.replace(/<[^>]+>/g, '')
26+
// A link's text can hold a code span, so links are unwrapped first, over the
27+
// whole heading.
28+
const linked = heading.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1');
29+
// Inline code is literal, so no other rule may reach inside it.
30+
return linked
31+
.split(/(`[^`]*`)/g)
32+
.map((part, i) =>
33+
i % 2 === 1
34+
? part.slice(1, -1)
35+
: part
36+
.replace(STAR_EMPHASIS, '$1')
37+
.replace(UNDERSCORE_EMPHASIS, '$1$2')
38+
.replace(/<[^>]+>/g, '')
39+
)
40+
.join('')
2241
.trim();
2342
}
2443

0 commit comments

Comments
 (0)