@@ -125,6 +125,15 @@ def __call__(self, crossref: str, *, length: int) -> str:
125125do_stash_crossref = _StashCrossRefFilter ()
126126"""Filter to stash cross-references (and restore them after formatting and highlighting)."""
127127
128+ _highlighting_span_re = re .compile (r'<span class="[a-z]{1,2}">' )
129+ _crossref_key_re = re .compile (r"\b_[A-Za-z0-9]{2,}\b" )
130+
131+
132+ def _restore_crossrefs (text : str , stash : dict [str , str ]) -> str :
133+ text = _crossref_key_re .sub (lambda match : stash .get (match [0 ], match [0 ]), text )
134+ stash .clear ()
135+ return text
136+
128137
129138def _format_signature (name : Markup , signature : str , line_length : int ) -> str :
130139 name = str (name ).strip () # type: ignore[assignment]
@@ -199,13 +208,11 @@ def do_format_signature(
199208 # Pygments will set an `fm` (function -> magic) CSS class.
200209 # To fix this, we replace the CSS class in the first span with `nf`,
201210 # unless we already found an `nf` span.
202- if not re . search ( r '<span class="nf">', signature ) :
203- signature = re .sub (r'<span class="[a-z]{1,2}">' , '<span class="nf">' , signature , count = 1 )
211+ if '<span class="nf">' not in signature :
212+ signature = _highlighting_span_re .sub ('<span class="nf">' , signature , count = 1 )
204213
205214 if stash := env .filters ["stash_crossref" ].stash :
206- for key , value in stash .items ():
207- signature = re .sub (rf"\b{ key } \b" , value , signature )
208- stash .clear ()
215+ signature = _restore_crossrefs (signature , stash )
209216
210217 return signature
211218
@@ -267,9 +274,7 @@ def do_format_attribute(
267274 )
268275
269276 if stash := env .filters ["stash_crossref" ].stash :
270- for key , value in stash .items ():
271- signature = re .sub (rf"\b{ key } \b" , value , signature )
272- stash .clear ()
277+ signature = _restore_crossrefs (signature , stash )
273278
274279 return signature
275280
@@ -322,13 +327,11 @@ def do_format_type_alias(
322327 # but instead as a regular name: `n` CSS class instead of `nc`.
323328 # To fix it, we replace the first occurrence of an `n` CSS class
324329 # with an `nc` one, unless we found `nc` already.
325- if not re . search ( r '<span class="nc">', signature ) :
326- signature = re .sub (r'<span class="[a-z]{1,2}">' , '<span class="nc">' , signature , count = 1 )
330+ if '<span class="nc">' not in signature :
331+ signature = _highlighting_span_re .sub ('<span class="nc">' , signature , count = 1 )
327332
328333 if stash := env .filters ["stash_crossref" ].stash :
329- for key , value in stash .items ():
330- signature = re .sub (rf"\b{ key } \b" , value , signature )
331- stash .clear ()
334+ signature = _restore_crossrefs (signature , stash )
332335
333336 return signature
334337
0 commit comments