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 re 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).

1.  Module Contents#

1.1.  Functions#

github_slugify

Convert a heading title to a GitHub-style slug.

gitlab_slugify

Convert a heading title to a GitLab-style slug.

unique_slug

Suffix slug with -1, -2, … until it is not in existing.

1.2.  Data#

SLUG_PRESETS

Named slugify functions, usable as myst_heading_slug_func values.

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; prefix anchor- 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.SLUG_PRESETS: dict[str, collections.abc.Callable[[str], str]] = None#

Named slugify functions, usable as myst_heading_slug_func values.

myst_parser.slugs.unique_slug(slug: str, existing: collections.abc.Container[str]) str[source]#

Suffix slug with -1, -2, … until it is not in existing.

The base never changes, so duplicates of x become x, x-1, x-2, ... (GitHub behaviour), not x, x-1, x-1-2, ....