mistune icon indicating copy to clipboard operation
mistune copied to clipboard

Confusing rule priority about ref_link

Open m00nlygreat opened this issue 9 months ago • 1 comments

Hey there,

I’m working on a custom plugin for Mistune v3 to use comment blocks like [layout]: # (example). It's initially parsed as paragraphs, so I registered my rule to run before the paragraph rule. However, I found out that the real culprit is the ref_link rule—my comment blocks were actually getting swallowed by it!

To make things work, I had to register my custom rule to run before ref_link:

def plugin_comment_block(md):
    pattern = r'^\[(?P<key>[^\]]+)\]:\s*#\s*\((?P<value>[^)]+)\)\s*$'
    
    def parse_comment_block(self, m, state):
        token = {
            'type': 'comment_block',
            'key': m.group('key'),
            'value': m.group('value'),
            'raw': m.group(0)
        }
        state.append_token(token)
        return m.end()
    
    # Using before='ref_link' works, not before 'paragraph'
    md.block.register('comment_block', pattern, parse_comment_block, before='ref_link')
    return md

It would be super helpful if the docs could clarify that even though it might seem natural to register before paragraph, you actually need to register before ref_link to catch these cases.

Thanks for all your work on Mistune!

Cheers, moon

ps. this issue is created by ChatGPT. Sorry if there's misunderstanding

m00nlygreat avatar Mar 16 '25 04:03 m00nlygreat

This is because the pattern is a subset of ref_link's regex pattern. As you can see, the footnote plugin is also registered before ref_link:

https://github.com/lepture/mistune/blob/master/src/mistune/plugins/footnotes.py#L162-L167

lepture avatar Mar 16 '25 07:03 lepture