Skip to content

Commit 04e4539

Browse files
committed
[singlehtml] Append docname to refid and ids
Use doc path to make ids unique with format ``/docname/#id``. Compensates for the loss of the pathname in the href. This will break existing hyperlinks to `singlehtml` HTML documents since it alters the format
1 parent 91bbe10 commit 04e4539

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

sphinx/builders/singlehtml.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def get_outdated_docs(self) -> str | list[str]: # type: ignore[override]
4242
def get_target_uri(self, docname: str, typ: str | None = None) -> str:
4343
if docname in self.env.all_docs:
4444
# all references are on the same page...
45-
return '#document-' + docname
45+
return '#/' + docname + '/'
4646
else:
4747
# chances are this is a html_additional_page
4848
return docname + self.out_suffix
@@ -88,13 +88,28 @@ def _get_local_toctree(
8888
)
8989
return self.render_partial(toctree)['fragment']
9090

91+
def ensure_fully_qualified_refids(self, tree: nodes.document) -> None:
92+
"""Append docname to refids and ids using format
93+
/docname/#id. Compensates for loss of the pathname section
94+
of the href, that ensures uniqueness in the html builder.
95+
"""
96+
for node in tree.findall(nodes.Element):
97+
assert node.document is not None
98+
if 'refid' in node or 'ids' in node:
99+
docname = self.env.path2doc(node.document['source'])
100+
if 'refid' in node:
101+
node['refid'] = f'/{docname}/#{node["refid"]}'
102+
if 'ids' in node:
103+
node['ids'] = [f'/{docname}/#{id}' for id in node['ids']]
104+
91105
def assemble_doctree(self) -> nodes.document:
92106
master = self.config.root_doc
93107
tree = self.env.get_doctree(master)
94108
logger.info(darkgreen(master))
95109
tree = inline_all_toctrees(self, set(), master, tree, darkgreen, [master])
96110
tree['docname'] = master
97111
self.env.resolve_references(tree, master, self)
112+
self.ensure_fully_qualified_refids(tree)
98113
return tree
99114

100115
def assemble_toc_secnumbers(self) -> dict[str, dict[str, tuple[int, ...]]]:

sphinx/writers/html5.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def __init__(self, document: nodes.document, builder: Builder) -> None:
6767
def visit_start_of_file(self, node: Element) -> None:
6868
# only occurs in the single-file builder
6969
self.docnames.append(node['docname'])
70-
self.body.append('<span id="document-%s"></span>' % node['docname'])
70+
self.body.append('<span id="/%s/"></span>' % node['docname'])
7171

7272
def depart_start_of_file(self, node: Element) -> None:
7373
self.docnames.pop()

0 commit comments

Comments
 (0)