Skip to content

Commit 9142d3f

Browse files
committed
Add emphasize-lines to testcode
1 parent 9bee330 commit 9142d3f

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

docs/source/conf.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,14 @@
66
import inspect
77
import os
88
import sys
9+
from typing import ClassVar
910

1011
import tomli
12+
from docutils.parsers.rst import directives
13+
from sphinx.application import Sphinx
14+
from sphinx.directives.code import parse_line_num_spec
15+
from sphinx.ext.doctest import TestcodeDirective
16+
from sphinx.util.typing import OptionSpec
1117

1218
# -- Project information -----------------------------------------------------
1319
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
@@ -135,3 +141,33 @@ def _get_version_str() -> str:
135141
except KeyError:
136142
version_str = "main"
137143
return version_str
144+
145+
146+
class _TestcodeWithEmphasisDirective(TestcodeDirective):
147+
"""
148+
Extension of ``.. testcode::`` that additionally supports ``:emphasize-lines:``.
149+
150+
Sphinx's built-in ``.. testcode::`` directive does not support ``:emphasize-lines:``. This
151+
subclass adds that option and forwards it as ``highlight_args['hl_lines']`` on the resulting
152+
node, which is the same mechanism used by ``.. code-block::``.
153+
"""
154+
155+
option_spec: ClassVar[OptionSpec] = {
156+
**TestcodeDirective.option_spec,
157+
"emphasize-lines": directives.unchanged_required,
158+
}
159+
160+
def run(self) -> list:
161+
result = super().run()
162+
linespec = self.options.get("emphasize-lines")
163+
if linespec and result:
164+
node = result[0]
165+
nlines = len(self.content)
166+
hl_lines = parse_line_num_spec(linespec, nlines)
167+
hl_lines = [x + 1 for x in hl_lines if x < nlines]
168+
node["highlight_args"] = {"hl_lines": hl_lines}
169+
return result
170+
171+
172+
def setup(app: Sphinx) -> None:
173+
app.add_directive("testcode", _TestcodeWithEmphasisDirective, override=True)

0 commit comments

Comments
 (0)