myst_parser.slugs#
Slug generation for heading anchors.
This is the single source of truth for heading slugs,
shared by the renderer (myst_heading_anchors) and the myst-anchors CLI.
The functions here are pure and dependency-free (standard library only),
so that alternative implementations of MyST can replicate them from this file;
for the same reason, the unit-test corpus is kept as a language-agnostic
data file (tests/fixtures/slugs.json).
A slug function may return an empty string (e.g. for a punctuation-only
title, or a non-Latin title under the docutils preset); an empty slug
means the heading gets no anchor.
1. Module Contents#
1.1. Functions#
Convert a heading title to a GitHub-style slug. |
|
Convert a heading title to a GitLab-style slug. |
|
Convert a heading title to a docutils/reStructuredText-style id. |
|
Suffix |
1.2. Data#
Named slugify functions, usable as |
1.3. API#
- myst_parser.slugs.github_slugify(title: str) str[source]#
Convert a heading title to a GitHub-style slug.
Algorithm: lowercase the title; replace spaces with hyphens
-; remove every character that is not a word character (\w), a CJK ideograph (U+4E00-U+9FFF), a hyphen or a space.Leading/trailing whitespace is deliberately not stripped first, so it survives as leading/trailing hyphens (e.g.
" a b "->"-a-b-"); see the v0.18.1 changelog.See jch/html-pipeline and https://gist.github.com/asabaylus/3071099
- myst_parser.slugs.gitlab_slugify(title: str) str[source]#
Convert a heading title to a GitLab-style slug.
Algorithm: strip and lowercase the title; remove every character that is not a word character (
\w), a hyphen or a space; replace spaces with hyphens; squeeze consecutive hyphens; prefixanchor-if the result consists only of digits.See https://docs.gitlab.com/ee/user/markdown.html#heading-ids-and-links and
Gitlab::Utils::Markdown#string_to_anchor.
- myst_parser.slugs.docutils_slugify(title: str) str[source]#
Convert a heading title to a docutils/reStructuredText-style id.
Byte-identical to
docutils.nodes.make_id, for uniform anchors across mixed rST + Markdown projects. Algorithm: lowercase the title; map the digraph letters ß æ œ ȸ ȹ and 33 further stroked/hooked Latin letters to ASCII equivalents; NFKD-normalize and drop every remaining non-ASCII character; normalize whitespace runs to single spaces (kept formake_idstep-parity, though subsumed by the next step); collapse each run of characters outside[a-z0-9]to a single hyphen; strip leading digits/hyphens and trailing hyphens.The result matches
[a-z](-?[a-z0-9]+)*or is empty — the latter for any title with no Latin letters (so such headings get no anchor), and docutils’ own duplicate-id handling (idN) is not emulated: deduplication is governed byunique_slug(), whatever the preset.