11from __future__ import annotations
22
33import re
4- from os .path import abspath
4+ from os .path import abspath , relpath
5+ from pathlib import Path
56from typing import TYPE_CHECKING , Any , cast
67
78from docutils import nodes
1920from sphinx .util .docutils import SphinxDirective
2021from sphinx .util .matching import Matcher , patfilter
2122from sphinx .util .nodes import explicit_title_re
22- from sphinx .util .osutil import os_path
2323
2424if TYPE_CHECKING :
2525 from docutils .nodes import Element , Node
@@ -373,24 +373,25 @@ class Include(BaseInclude, SphinxDirective):
373373
374374 def run (self ) -> list [Node ]:
375375
376- # To properly emit "source -read" events from included RST text,
376+ # To properly emit "include -read" events from included RST text,
377377 # we must patch the ``StateMachine.insert_input()`` method.
378378 # In the future, docutils will hopefully offer a way for Sphinx
379379 # to provide the RST parser to use
380380 # when parsing RST text that comes in via Include directive.
381381 def _insert_input (include_lines , source ):
382382 # First, we need to combine the lines back into text so that
383- # we can send it with the source -read event.
383+ # we can send it with the include -read event.
384384 # In docutils 0.18 and later, there are two lines at the end
385385 # that act as markers.
386- # We must preserve them and leave them out of the source -read event:
386+ # We must preserve them and leave them out of the include -read event:
387387 text = "\n " .join (include_lines [:- 2 ])
388388
389- # The docname to pass into the source-read event
390- docname = self .env .path2doc (abspath (os_path (source )))
391- # Emit the "source-read" event
389+ path = Path (relpath (abspath (source ), start = self .env .srcdir ))
390+ docname = self .env .docname
391+
392+ # Emit the "include-read" event
392393 arg = [text ]
393- self .env .app .events .emit ("source -read" , docname , arg )
394+ self .env .app .events .emit ('include -read' , path , docname , arg )
394395 text = arg [0 ]
395396
396397 # Split back into lines and reattach the two marker lines
@@ -401,8 +402,8 @@ def _insert_input(include_lines, source):
401402 # the *Instance* method and this call is to the *Class* method.
402403 return StateMachine .insert_input (self .state_machine , include_lines , source )
403404
404- # Only enable this patch if there are listeners for 'source -read'.
405- if self .env .app .events .listeners .get ('source -read' ):
405+ # Only enable this patch if there are listeners for 'include -read'.
406+ if self .env .app .events .listeners .get ('include -read' ):
406407 # See https://github.com/python/mypy/issues/2427 for details on the mypy issue
407408 self .state_machine .insert_input = _insert_input # type: ignore[method-assign]
408409
0 commit comments