Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[RFC] Rebuild link labels for Sphinx i18n support #800

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions myst_parser/mdit_to_docutils/base.py
Expand Up @@ -948,6 +948,15 @@ def render_link_url(
uri = cast(str, token.attrGet("href") or "")
implicit_text: str | None = None

# cache label references for possible i8n support
# (see also: MystParser.parse)
if uri and "label" in token.meta:
label = token.meta["label"]
env = self.sphinx_env
docname = env.docname
labelrefs = env.metadata[docname].setdefault("myst_labelrefs", {})
labelrefs[label] = uri

if conversion is not None:
# implicit_template: str | None = None
# if isinstance(conversion, (list, tuple)):
Expand Down
3 changes: 3 additions & 0 deletions myst_parser/parsers/mdit.py
Expand Up @@ -120,6 +120,9 @@ def create_md_parser(
"typographer": typographer,
"linkify": "linkify" in config.enable_extensions,
"myst_config": config,
# store labels for references so we can rebuild link labels
# when using Sphinx Internationalization translation building
"store_labels": True,
}
)

Expand Down
19 changes: 19 additions & 0 deletions myst_parser/parsers/sphinx_.py
Expand Up @@ -69,6 +69,25 @@ def parse(self, inputstring: str, document: nodes.document) -> None:
)
config = merge_file_level(config, topmatter, warning)

# inject label references for a partial document string
#
# When processing translations in Sphinx, after Sphinx's i8n transform
# replaces parts of a document with a translation, document is
# processed a message at a time through the MyST-parser. For
# references using link labels, these may not be to the parse for the
# specific messages that need them. If we detect we have a cache of
# label references (from an initial pass before translation), rebuild
# the label references and append them to the specific message about
# to be parsed. This will ensure references will be resolved/built as
# expected.
env = document.settings.env
labelrefs = env.metadata[env.docname].get("myst_labelrefs", {})
if labelrefs:
postfix = "\n\n"
for label, uri in labelrefs.items():
postfix += f"[{label}]: {uri}\n"
inputstring += postfix

parser = create_md_parser(config, SphinxRenderer)
parser.options["document"] = document
parser.render(inputstring)