Skip to content

Proper broken link handler #385

Closed
Closed

Description

@lucascool12

Context

It would be nice if there was an easy way to have a function resolve link references that haven't been registered (similar to pulldown-cmark https://docs.rs/pulldown-cmark/0.13.1/pulldown_cmark/struct.Parser.html#method.new_with_broken_link_callback).
So we can programmatically decide the href of something like this:

[broken_link]

I didn't find anything in the documentation describing how to properly do this, and the only work around I found was to copy and paste the link function in rules_inline (

def link(state: StateInline, silent: bool) -> bool:
) and whenever false is returned when parseReference is true to put some custom logic to try to resolve the reference.
And then register this rule with:

md = markdown_it.MarkdownIt()
def custom_link(state, silent):
    ....
md.inline.ruler.disable("link")
md.inline.ruler.push("custom_link",  custom_link)

It would be very nice if there was some blessed route to be able to do this.

Proposal

No response

Tasks and updates

No response

Activity

  1. chrisjsewell commented on Nov 10, 2026

    @chrisjsewell
    Member

    Thanks for the request. There's no built-in callback (upstream markdown-it has none either), but you don't need to copy the link rule. Add a small inline rule before it that fills in missing references and lets the normal rule do the rest:

    from markdown_it.common.utils import normalizeReference
    
    def broken_link_plugin(md, resolve):
        def rule(state, silent):
            if state.src[state.pos] != '[':
                return False
            end = state.md.helpers.parseLinkLabel(state, state.pos, False)
            if end < 0 or state.src[end + 1:end + 2] == '(':
                return False
            label = state.src[state.pos + 1:end]
            key = normalizeReference(label)
            refs = state.env.setdefault('references', {})
            if key and key not in refs and (href := resolve(label)) is not None:
                refs[key] = {'href': href, 'title': ''}
            return False
        md.inline.ruler.before('link', 'broken_link', rule)
    
    md = MarkdownIt().use(broken_link_plugin, lambda label: f'/wiki/{label}')

    (Handle [text][label] by reading the second label the same way.) Closing as answered; feel free to reopen if that doesn't fit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions