Skip to content

genindex.html: have linked name + separate qualifier #14390

@giampaolo

Description

@giampaolo

Hi!

First of all, congratulations on Sphinx. I've been using it for years, but only recently started exploring more advanced use cases, and I started loving it.

I recently exposed the genindex in the psutil documentation. By default, Sphinx generates entries as a single <a href="...">NAME (qualifier)</a> element, which I find a bit sub-optimal.

To improve this, I wrote a small extension that transforms it into <a href="...">NAME</a> <span class="index-qualifier">(qualifier)</span>, so that only the name is part of the link, while the qualifier is styled separately.

import pathlib
import re

# Matches <a href="...">NAME (qualifier)</a> where NAME does not start
# with "(" — leaving pure-paren sub-entries like "(psutil.Foo method)" alone.
REGEX = re.compile(r'<a href="([^"]+)">([^(<][^<]*?) (\([^)]+\))</a>')


def _replace(m):
    href, name, qualifier = m.group(1), m.group(2), m.group(3)
    return (
        f'<a href="{href}">{name}</a> <span'
        f' class="index-qualifier">{qualifier}</span>'
    )


def on_build_finished(app, exception):
    if exception or app.builder.name != "html":
        return
    genindex = pathlib.Path(app.outdir) / "genindex.html"
    if not genindex.exists():
        return
    original = genindex.read_text(encoding="utf-8")
    processed = REGEX.sub(_replace, original)
    if processed != original:
        genindex.write_text(processed, encoding="utf-8")


def setup(app):
    app.connect("build-finished", on_build_finished)
    return {"parallel_read_safe": True, "parallel_write_safe": True}

Would this be a reasonable change to consider in Sphinx itself?

In other words, I’m proposing to turn this:

Image

...into this:

Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions