@@ -191,10 +191,12 @@ def do_format_signature(
191191 # Pygments sees it as a function call and not a function definition.
192192 # The result is that the function name is not parsed as such,
193193 # but instead as a regular name: `n` CSS class instead of `nf`.
194- # To fix it, we replace the first occurrence of an `n` CSS class
195- # with an `nf` one, unless we found `nf` already.
196- if signature .find ('class="nf"' ) == - 1 :
197- signature = signature .replace ('class="n"' , 'class="nf"' , 1 )
194+ # When the function name is a known special name like `__exit__`,
195+ # Pygments will set an `fm` (function -> magic) CSS class.
196+ # To fix this, we replace the CSS class in the first span with `nf`,
197+ # unless we already found an `nf` span.
198+ if not re .search (r'<span class="nf">' , signature ):
199+ signature = re .sub (r'<span class="[a-z]{1,2}">' , '<span class="nf">' , signature , count = 1 )
198200
199201 if stash := env .filters ["stash_crossref" ].stash :
200202 for key , value in stash .items ():
@@ -306,14 +308,14 @@ def do_format_type_alias(
306308 )
307309
308310 # Since we highlight the signature without `type`,
309- # Pygments sees only an assignment, not a type alias definition.
310- # (At the moment it does not understand type alias definitions anyway)
311+ # Pygments sees only an assignment, not a type alias definition
312+ # (at the moment it does not understand type alias definitions anyway).
311313 # The result is that the type alias name is not parsed as such,
312314 # but instead as a regular name: `n` CSS class instead of `nc`.
313315 # To fix it, we replace the first occurrence of an `n` CSS class
314316 # with an `nc` one, unless we found `nc` already.
315- if signature . find ( ' class="nc"' ) == - 1 :
316- signature = signature . replace ( ' class="n" ' , 'class="nc"' , 1 )
317+ if not re . search ( r'<span class="nc">' , signature ) :
318+ signature = re . sub ( r'<span class="[a-z]{1,2}"> ' , '<span class="nc"> ' , signature , count = 1 )
317319
318320 if stash := env .filters ["stash_crossref" ].stash :
319321 for key , value in stash .items ():
0 commit comments