Can I process link targets before they're written? #620

Closed
opened 2026-01-29 14:41:20 +00:00 by claunia · 2 comments
Owner

Originally created by @deanebarker on GitHub (Aug 22, 2023).

I would like to do some logical processing on the HREF value of a link. So, if the editor enters something like:

My name is [Deane](@deane).

I would like to capture the @deane value and do some processing on that value before it's written as the HREF attribute. I'd like to replace the value with another value.

Is there a mechanism for this? I couldn't find an event. Or do I need to replace the link parser/rendering completely?

Originally created by @deanebarker on GitHub (Aug 22, 2023). I would like to do some logical processing on the `HREF` value of a link. So, if the editor enters something like: ``` My name is [Deane](@deane). ``` I would like to capture the `@deane` value and do some processing on that value before it's written as the `HREF` attribute. I'd like to replace the value with another value. Is there a mechanism for this? I couldn't find an event. Or do I need to replace the link parser/rendering completely?
claunia added the question label 2026-01-29 14:41:20 +00:00
Author
Owner

@MihaZupan commented on GitHub (Aug 22, 2023):

You can post-process the document and modify the URLs

MarkdownDocument document = Markdown.Parse(markdown, pipeline);

foreach (LinkInline link in document.Descendants<LinkInline>())
{
    if (link.Url.StartsWith('@'))
    {
        link.Url = $"https://github.com/{link.Url.AsSpan(1)}";
    }
}

string html = document.ToHtml(pipeline);

Or if you're creating HtmlRenderers manually, you can set the LinkRewriter callback

renderer.LinkRewriter = url =>
    url.StartsWith('@') ? $"https://github.com/{url.AsSpan(1)}" : url;
@MihaZupan commented on GitHub (Aug 22, 2023): You can post-process the document and modify the URLs ```c# MarkdownDocument document = Markdown.Parse(markdown, pipeline); foreach (LinkInline link in document.Descendants<LinkInline>()) { if (link.Url.StartsWith('@')) { link.Url = $"https://github.com/{link.Url.AsSpan(1)}"; } } string html = document.ToHtml(pipeline); ``` Or if you're creating `HtmlRenderer`s manually, you can set the `LinkRewriter` callback ```c# renderer.LinkRewriter = url => url.StartsWith('@') ? $"https://github.com/{url.AsSpan(1)}" : url; ```
Author
Owner

@deanebarker commented on GitHub (Aug 22, 2023):

Works beautifully, thank you.

@deanebarker commented on GitHub (Aug 22, 2023): Works beautifully, thank you.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/markdig#620