Skip to content
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ coverage.xml

# Translations
*.mo
/python_docs_theme/locale/**/*.js
*.pot

# Django stuff:
Expand Down
48 changes: 48 additions & 0 deletions babel_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@

import argparse
import ast
import json
import subprocess
import tomllib
from pathlib import Path

from babel.messages.pofile import read_po
from hatchling.builders.hooks.plugin.interface import BuildHookInterface

# Global variables used by pybabel below (paths relative to PROJECT_DIR)
Expand Down Expand Up @@ -107,6 +109,52 @@ def compile_catalogs(locale: str) -> None:
cmd.extend(["-l", locale])
subprocess.run(cmd, cwd=PROJECT_DIR, check=True)

locale_dirs = PROJECT_DIR / LOCALES_DIR
catalogs = (
[locale_dirs / locale / "LC_MESSAGES" / f"{DOMAIN}.po"]
if locale
else sorted(locale_dirs.glob(f"*/LC_MESSAGES/{DOMAIN}.po"))
)
for pofile in catalogs:
compile_js_catalog(pofile)


def compile_js_catalog(pofile: Path) -> None:
"""Export translated JavaScript messages from the PO catalog."""
jsfile = pofile.with_suffix(".js")
with pofile.open("rb") as f:
source = read_po(f)
if source.fuzzy:
jsfile.unlink(missing_ok=True)
return
messages = {}
for message in source:
if not any(filename.endswith(".js") for filename, _ in message.locations):
continue
# Sphinx's JavaScript gettext runtime doesn't provide pgettext()
if message.context is not None:
continue
if message.fuzzy or not message.string:
continue
if message.pluralizable and not all(message.string):
continue
msgid = message.id[0] if message.pluralizable else message.id
messages[msgid] = message.string
serialized = json.dumps(
{
"locale": str(source.locale),
"messages": messages,
"plural_expr": f"Number({source.plural_expr})",
},
ensure_ascii=True,
sort_keys=True,
)
jsfile.write_text(
f"// {DOMAIN} translations for {pofile.parents[1].name}\n"
f"Documentation.addTranslations({serialized});\n",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 says this, does it matter here?


Documentation.addTranslations also replaces the global PLURAL_EXPR, and our file loads after Sphinx's translations.js, so our plural rule overrides Sphinx's. They don't always match: for German we emit a three-form rule but Sphinx's German catalog has two forms, so ngettext in searchtools.js would return undefined for most counts.

None of our three JS strings are plural, so let's merge into TRANSLATIONS and leave the plural rule to Sphinx:

        # The plural rule is global and set by Sphinx's own catalog
        if message.pluralizable:
            continue
        if message.fuzzy or not message.string:
            continue
        messages[message.id] = message.string
    serialized = json.dumps(messages, ensure_ascii=True, sort_keys=True)
    jsfile.write_text(
        f"// {DOMAIN} translations for {pofile.parents[1].name}\n"
        f"Object.assign(Documentation.TRANSLATIONS, {serialized});\n",
        encoding="utf-8",
    )

@m-aciek m-aciek Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's right, thank you. Potentially we could be incorrectly overriding core Sphinx plural rules for JS messages.

I've applied a fix while keeping support for ngettext, for potential future use. b85739d What do you think?

Regarding the undefined issue in forms I've opened sphinx-doc/sphinx#14872 in Sphinx.

@m-aciek m-aciek Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The most correct fix would be to bring support for plural rules per gettext domain in JS catalogs on Sphinx side, but I think the use of it is so niche that I'm not sure if it's worth ticketing now.

encoding="utf-8",
)


class CustomBuildHook(BuildHookInterface):
def initialize(self, version: str, build_data: dict[str, object]) -> None:
Expand Down
5 changes: 4 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,10 @@ entry-points."sphinx.html_themes".python_docs_theme = "python_docs_theme"

[tool.hatch]
version.path = "python_docs_theme/__init__.py"
build.artifacts = [ "python_docs_theme/locale/**/*.mo" ]
build.artifacts = [
"python_docs_theme/locale/**/*.js",
"python_docs_theme/locale/**/*.mo",
]
build.hooks.custom.path = "babel_runner.py"
build.targets.wheel.packages = [ "python_docs_theme" ]
build.targets.wheel.exclude = [
Expand Down
26 changes: 26 additions & 0 deletions python_docs_theme/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from __future__ import annotations

from gettext import find
from pathlib import Path
from shutil import copyfile

from sphinx.locale import get_translation

Expand Down Expand Up @@ -37,12 +39,36 @@ def combined(message: str) -> str:
context["_"] = context["gettext"] = context["ngettext"] = combined


def get_js_catalog(app: Sphinx) -> Path | None:
catalog = find(
MESSAGE_CATALOG_NAME,
localedir=LOCALE_DIR,
languages=[app.config.language or "en"],
)
if catalog is not None:
js_catalog = Path(catalog).with_suffix(".js")
if js_catalog.is_file():
return js_catalog
return None


def add_js_translations(app: Sphinx) -> None:
if app.builder.format != "html":
return
if catalog := get_js_catalog(app):
static_dir = Path(app.outdir) / "_static"
static_dir.mkdir(parents=True, exist_ok=True)
copyfile(catalog, static_dir / "python-docs-theme-translations.js")
app.add_js_file("python-docs-theme-translations.js")


def setup(app: Sphinx) -> ExtensionMetadata:
app.require_sphinx("7.3")

app.add_html_theme("python_docs_theme", str(THEME_PATH))
app.add_message_catalog(MESSAGE_CATALOG_NAME, LOCALE_DIR)
app.connect("html-page-context", add_translation_to_context)
app.connect("builder-inited", add_js_translations)

return {
"version": __version__,
Expand Down
Loading