diff --git a/sphinx/ext/viewcode.py b/sphinx/ext/viewcode.py index 0446fa94159..ffd90f1549e 100644 --- a/sphinx/ext/viewcode.py +++ b/sphinx/ext/viewcode.py @@ -262,14 +262,16 @@ def collect_pages(app: Sphinx) -> Generator[tuple[str, dict[str, Any], str], Non lines[0:1] = [before + '
', after]
         # nothing to do for the last line; it always starts with 
anyway # now that we have code lines (starting at index 1), insert anchors for - # the collected tags + # the collected tags (HACK: this only works if the tag boundaries are + # properly nested!) + max_index = len(lines) - 1 for name, docname in used.items(): type, start, end = tags[name] backlink = urito(pagename, docname) + '#' + refname + '.' + name lines[start] = ( - '{_("[docs]")}\n' + - lines[start]) + f'
\n' + f'{_("[docs]")}\n' + lines[start]) + lines[min(end, max_index)] += '
\n' # try to find parents (for submodules) parents = [] diff --git a/tests/test_ext_viewcode.py b/tests/test_ext_viewcode.py index 5579cb6f2d9..3460ccfcbc8 100644 --- a/tests/test_ext_viewcode.py +++ b/tests/test_ext_viewcode.py @@ -32,8 +32,8 @@ def check_viewcode_output(app, status, warning): result = (app.outdir / '_modules/spam/mod1.html').read_text(encoding='utf8') result = re.sub('', '', result) # filter pygments classes - assert ('[docs]\n') in result + assert ('
\n' + '[docs]\n') in result assert '@decorator\n' in result assert 'class Class1:\n' in result if pygments.__version__ >= '2.14.0':