1313_HEADING_LINE_RE = re .compile (r'^(\s*)(#{1,6})(?!#)(?=\S)' )
1414_REF_LINK_OR_IMAGE_RE = re .compile (r'!?\[[^\]]+\]\s*\[[^\]]*\]' )
1515_REF_DEF_LINE_RE = re .compile (r'^\s{0,3}\[[^\]]+\]:\s+\S+' )
16- _FENCE_RE = re .compile (r'^\s*(```|~~~ )' )
16+ _FENCE_RE = re .compile (r'^\s*(`{3,}|~{3,} )' )
1717_INLINE_MARKERS = {
1818 'strong' : '**' ,
1919 'emphasis' : '*' ,
@@ -293,8 +293,11 @@ def _find_next_tag(self, text: str):
293293 matches .append ((match .start (), name , match ))
294294 if not matches :
295295 return None , None
296- _ , name , match = min (matches , key = lambda item : item [0 ])
297- return name , match
296+ matches .sort (key = lambda item : item [0 ])
297+ for _ , name , match in matches :
298+ if not _is_inside_fenced_block (text , match .start ()):
299+ return name , match
300+ return None , None
298301
299302 def _parse_markdown (self , text : str ):
300303 normalized = _remove_spaces_from_empty_lines (text )
@@ -360,15 +363,20 @@ def _extract_reference_definitions(text: str):
360363 output = []
361364 definitions = {}
362365 fence = None
366+ fence_len = 0
363367 counter = 0
364368 for line in lines :
365369 fence_match = _FENCE_RE .match (line )
366370 if fence_match :
367371 marker = fence_match .group (1 )
372+ marker_len = len (marker )
373+ marker_char = marker [0 ]
368374 if fence is None :
369- fence = marker
370- elif fence == marker :
375+ fence = marker_char
376+ fence_len = marker_len
377+ elif marker_char == fence and marker_len >= fence_len :
371378 fence = None
379+ fence_len = 0
372380 output .append (line )
373381 continue
374382
@@ -384,6 +392,28 @@ def _extract_reference_definitions(text: str):
384392 return '\n ' .join (output ), definitions
385393
386394
395+ def _is_inside_fenced_block (text : str , offset : int ) -> bool :
396+ fence = None
397+ fence_len = 0
398+ running = 0
399+ for line in text .splitlines (True ):
400+ line_len = len (line )
401+ if running + line_len > offset :
402+ return fence is not None
403+ fence_match = _FENCE_RE .match (line )
404+ if fence_match :
405+ marker = fence_match .group (1 )
406+ marker_len = len (marker )
407+ if fence is None :
408+ fence = marker [0 ]
409+ fence_len = marker_len
410+ elif marker [0 ] == fence and marker_len >= fence_len :
411+ fence = None
412+ fence_len = 0
413+ running += line_len
414+ return False
415+
416+
387417def _remove_spaces_from_empty_lines (text ):
388418 return '\n ' .join ([re .sub (r'^( {1,}|\t{1,})$' , '\n ' , line ) for line in text .splitlines ()])
389419
0 commit comments