Skip to content

Extensions

Porohkun edited this page Oct 22, 2026 · 15 revisions

English | Русский

An extension teaches the viewer your own syntax: it adds a construct to the Markdig parser, turns the parsed nodes into models of your own and gives those models templates. Such a model with its template is a widget. Built-in syntax can be taken over the same way.

An inline widget and a block widget

Anatomy

An extension derives from MdExtension and overrides what it needs:

Member What it does
SetupPipeline(builder) adds Markdig extensions and parsers for your syntax
ConvertBlock(block, context) turns a Markdig block into your block model; null — not yours
ConvertBlocks(block, context) turns a Markdig block into several block models; an empty list hides the block; null — not yours
ConvertInline(inline, context) turns a Markdig inline into your inline model; null — not yours
ConvertInlines(inline, context) turns a Markdig inline into several inline models — text, styled text, widgets; null — not yours
SelectTemplate(item, container) returns the template of your model; null — not yours
CreateState(node) creates the state of a widget that outlives its control; null — no state
EditSource(node, state, context) what to write into the source when your widget is pressed or its state changes; null — nothing
DescribeSource(node, look) how your widget looks in the source of the editor, over the default look

The viewer asks its extensions in order, before its own conversion and before the style provider, so the first extension that answers wins. MdConvertContext converts the content of your node like the rest of the document: ConvertChildren for nested blocks, ConvertInlines for inline content; GetSource and GetSpan give the source text and position of a node.

Models derive from BlockVm or InlineVm. Those are records, so your models are immutable records too.

A block widget

A note: a custom container :::note Title with Markdown inside. Custom containers are already in the default pipeline, so the extension only converts them.

Any .md file:

:::note Your own block
A container with **markdown inside**.
:::

NoteVm.cs:

using Beresta.Markdown.Wpf.Selection;
using Beresta.Markdown.Wpf.ViewModels;

public sealed record NoteVm(string Title, IReadOnlyList<BlockVm> Blocks) : BlockVm, IMdTextSource
{
    public void WriteText(MdTextWriter writer)
    {
        writer.Text(Title);
        writer.Text("\n");
        writer.Blocks(Blocks);
    }
}

NoteExtension.cs:

using System.Windows;
using Markdig.Extensions.CustomContainers;
using Markdig.Syntax;
using Beresta.Markdown.Wpf.Extensions;
using Beresta.Markdown.Wpf.ViewModels;

public sealed class NoteExtension : MdExtension
{
    public DataTemplate? Template { get; set; }

    public override BlockVm? ConvertBlock(Block block, MdConvertContext context)
        => block is CustomContainer { Info: "note" } container
            ? new NoteVm(container.Arguments ?? string.Empty, context.ConvertChildren(container))
            : null;

    public override DataTemplate? SelectTemplate(object item, DependencyObject container)
        => item is NoteVm ? Template : null;
}

MainWindow.xaml, the viewer:

<md:MarkdownViewer Markdown="{Binding Text}">
    <md:MarkdownViewer.Extensions>
        <local:NoteExtension>
            <local:NoteExtension.Template>
                <DataTemplate>
                    <Border Margin="0,4,0,8" Padding="12,8" CornerRadius="4" BorderThickness="4,0,0,0"
                            BorderBrush="#326CF3" Background="#F0F4FD">
                        <StackPanel>
                            <TextBlock Text="{Binding Title}" FontWeight="SemiBold" Margin="0,0,0,4" />
                            <md:MdBlocksPresenter Blocks="{Binding Blocks}" />
                        </StackPanel>
                    </Border>
                </DataTemplate>
            </local:NoteExtension.Template>
        </local:NoteExtension>
    </md:MarkdownViewer.Extensions>
</md:MarkdownViewer>

md:MdBlocksPresenter draws the nested blocks with the same templates and virtualization as the document. A container that no extension takes is drawn as its content.

An inline widget with its own syntax

A mention @name. Markdig does not know this syntax, so the extension adds an inline parser to the pipeline. The parser is plain Markdig: see the Markdig documentation for parsers of other kinds.

Mentions.cs:

using System.Windows;
using Markdig;
using Markdig.Helpers;
using Markdig.Parsers;
using Markdig.Renderers;
using Markdig.Syntax.Inlines;
using Beresta.Markdown.Wpf.Extensions;
using Beresta.Markdown.Wpf.Selection;
using Beresta.Markdown.Wpf.ViewModels;

public sealed class MentionInline : LeafInline
{
    public required string Name { get; init; }
}

public sealed class MentionParser : InlineParser
{
    public MentionParser()
    {
        OpeningCharacters = ['@'];
    }

    public override bool Match(InlineProcessor processor, ref StringSlice slice)
    {
        var start = slice.Start;
        var length = 0;
        while (char.IsLetterOrDigit(slice.PeekChar(length + 1)))
        {
            length++;
        }

        if (length == 0)
        {
            return false;
        }

        var position = processor.GetSourcePosition(start, out var line, out var column);
        processor.Inline = new MentionInline
        {
            Name = slice.Text.Substring(start + 1, length),
            Span = new(position, position + length),
            Line = line,
            Column = column
        };

        slice.Start += length + 1;
        return true;
    }
}

public sealed class MentionMarkdigExtension : IMarkdownExtension
{
    public void Setup(MarkdownPipelineBuilder pipeline)
    {
        if (!pipeline.InlineParsers.Contains<MentionParser>())
        {
            pipeline.InlineParsers.Insert(0, new MentionParser());
        }
    }

    public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)
    {
    }
}

public sealed record MentionVm(string Name) : InlineVm, IMdCopyText
{
    public string CopyText => "@" + Name;
}

public sealed class MentionExtension : MdExtension
{
    public DataTemplate? Template { get; set; }

    public override void SetupPipeline(MarkdownPipelineBuilder pipeline)
        => pipeline.Extensions.AddIfNotAlready<MentionMarkdigExtension>();

    public override InlineVm? ConvertInline(Inline inline, MdConvertContext context)
        => inline is MentionInline mention ? new MentionVm(mention.Name) : null;

    public override DataTemplate? SelectTemplate(object item, DependencyObject container)
        => item is MentionVm ? Template : null;
}

MainWindow.xaml, inside <md:MarkdownViewer.Extensions>:

<local:MentionExtension>
    <local:MentionExtension.Template>
        <DataTemplate>
            <Border Padding="6,0" CornerRadius="8" Background="#326CF3">
                <TextBlock Text="{Binding Name, StringFormat='@{0}'}" Foreground="White" />
            </Border>
        </DataTemplate>
    </local:MentionExtension.Template>
</local:MentionExtension>

An inline widget stands in the line like one character: it is selected as a whole and pasted as its CopyText.

Text of a widget

How a widget takes part in selection and copying depends on its model:

The model implements In the text map Plain text copy
IMdTextSource its text and nested blocks, written by WriteText; nested blocks are selected like ordinary ones that text
IMdCopyText one character CopyText
neither one character nothing

When a widget is selected as a whole, «Copy as Markdown» writes its source text. An inline widget that is only a helper — buttons next to a piece of text made from the same node — implements IMdMarkdownText with an empty MarkdownText, so the source of the node is not written twice.

Widget state

A widget's control is short-lived: it disappears when its block scrolls out of view and may be re-created by a new text. State that must survive — collapsed or not, a selected tab — goes into an object created by CreateState. The viewer keeps it by the identity of the model while the model lives in the document, and the template reads it through the inherited attached property md:MdWidget.State.

NoteState.cs:

using System.ComponentModel;

public sealed class NoteState : INotifyPropertyChanged
{
    private bool _isExpanded = true;

    public event PropertyChangedEventHandler? PropertyChanged;

    public bool IsExpanded
    {
        get => _isExpanded;
        set
        {
            _isExpanded = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsExpanded)));
        }
    }
}

NoteExtension.cs, one more override:

public override object? CreateState(NodeVm node) => node is NoteVm ? new NoteState() : null;

MainWindow.xaml, the note template; BooleanToVisibility is a BooleanToVisibilityConverter in the window resources:

<DataTemplate>
    <StackPanel Margin="0,4,0,8">
        <ToggleButton Content="{Binding Title}"
                      HorizontalAlignment="Left"
                      IsChecked="{Binding (md:MdWidget.State).IsExpanded, RelativeSource={RelativeSource Self}}" />
        <md:MdBlocksPresenter Blocks="{Binding Blocks}"
                             Visibility="{Binding (md:MdWidget.State).IsExpanded, RelativeSource={RelativeSource Self}, Converter={StaticResource BooleanToVisibility}}" />
    </StackPanel>
</DataTemplate>

Built-in blocks for your syntax

An extension does not need a template of its own when a built-in block fits: it returns a callout CalloutVm or a collapsible block DetailsVm, and the viewer draws it with the theme and keeps whether it is folded by itself.

SpoilerExtension.cs:

using Markdig.Extensions.CustomContainers;
using Markdig.Syntax;
using Beresta.Markdown.Wpf.Extensions;
using Beresta.Markdown.Wpf.ViewModels;

public sealed class SpoilerExtension : MdExtension
{
    public override BlockVm? ConvertBlock(Block block, MdConvertContext context)
        => block is CustomContainer { Info: "spoiler" } container
            ? new DetailsVm([new RunVm(container.Arguments ?? "Spoiler")], context.ConvertChildren(container))
            : null;
}

Any .md file, with the extension connected:

:::spoiler The ending
The butler did it.
:::

A foldable callout is a CalloutVm with IsFoldable = true; IsFolded = true makes it start folded.

Writing to the source

While controls edit the source — AreControlsEditable, see Ticking tasks — a widget may change its own piece of the source. The viewer asks the extension that made the model: EditSource(node, state, context) returns an MdSourceEdit — the start and length of the replaced piece and the new text — or null. state is the new state when a state from CreateState, or the fold of a built-in block, reports a change through INotifyPropertyChanged, and null when the widget is pressed. context.Text is the shown source text, node.Source — the place of the node in it. The edit goes through SourceEditRequested like a ticked task.

The spoiler from the section above remembers in the source whether it is expanded: :::spoiler+.

SpoilerExtension.cs:

using Markdig.Extensions.CustomContainers;
using Markdig.Syntax;
using Beresta.Markdown.Wpf;
using Beresta.Markdown.Wpf.Extensions;
using Beresta.Markdown.Wpf.ViewModels;

public sealed class SpoilerExtension : MdExtension
{
    public override BlockVm? ConvertBlock(Block block, MdConvertContext context)
        => block is CustomContainer { Info: "spoiler" or "spoiler+" } container
            ? new DetailsVm([new RunVm(container.Arguments ?? "Spoiler")], context.ConvertChildren(container))
            {
                IsOpen = container.Info == "spoiler+"
            }
            : null;

    public override MdSourceEdit? EditSource(NodeVm node, object? state, MdSourceContext context)
    {
        if (node is not DetailsVm details || state is not MdFoldState fold)
        {
            return null;
        }

        var mark = context.Text.IndexOf("spoiler", details.Source.Start, StringComparison.Ordinal) + "spoiler".Length;
        var open = mark < context.Text.Length && context.Text[mark] == '+';
        return open == fold.IsExpanded ? null : new MdSourceEdit(mark, open ? 1 : 0, open ? "" : "+");
    }
}

A control of your template is pressed with the command MarkdownViewer.ActivateWidgetCommand and the model as its parameter; while controls do not edit the source, the command is unavailable.

MainWindow.xaml, in the template of your widget:

<Button Content="Done"
        Command="{x:Static md:MarkdownViewer.ActivateWidgetCommand}"
        CommandParameter="{Binding}" />

The look in the source

In the editor the edited blocks show their source, drawn with the keys of the theme. A built-in model your extension makes is drawn like a built-in one. A model of your own is drawn by what it writes into the text map — see Text of a widget: the inlines and blocks it writes look as everywhere in the document, and the text around them is markup; a model that writes neither is plain text. Over that, your extension describes its widget in DescribeSource(node, look) with looks by name: look.Mark(start, length, name) for a piece of the source, look.MarkLines(firstLine, lastLine, name) for source lines counting from zero. A later mark is drawn over an earlier one, and the marks of extensions over the built-in ones. look.MarkIndent(line, length) marks the first characters of a line as its marker: the wrapped lines of this line start after it — list items and quotes mark their markers themselves. look.MarkColumns(rows, alignments) marks a table whose columns the editor lines up: the rows are source lines with the places of the separators that end their cells. look.Text is the shown source the places are in: the extension finds its marks in it.

A look named X takes the theme keys Md.X.*:

Keys What they give
Md.X.Foreground, Md.X.Background, Md.X.FontFamily, Md.X.FontWeight, Md.X.FontStyle, Md.X.FontSize the text color, the background and the font of a piece
Md.X.Background, Md.X.BorderBrush, Md.X.BorderThickness the background of lines across the width and the bar on their left: its color and its left thickness
Md.X.Margin lines: the top margin before the first line and the bottom one after the last — the height the block has in the drawing
Md.X.Height lines: the height of a blank line — an empty line of the look or a line of spaces takes it

A property without its own key comes from the setter of the style Md.X.Style, if there is one: Foreground, Background, FontFamily, FontWeight, FontStyle, FontSize and TextDecorations.

The built-in names are Heading1–Heading6, InlineCode, CodeBlock, Quote, Callout.<Kind> for callouts, BlankLine for blank lines between blocks, Code.<Look> for highlighted code and Source.Markup for markup — see Editor; Bold, Italic, Strike and Link have no keys of their own: they are bold, italic, struck out and the color Md.Paragraph.LinkForeground.

The note from A block widget writes its nested blocks into the text map, so in the source they look as everywhere, and its :::note lines are markup. The extension adds a background and a bar.

NoteExtension.cs, in the extension:

public override void DescribeSource(NodeVm node, MdSourceLook look)
{
    if (node is NoteVm note)
    {
        look.MarkLines(note.Source.StartLine, note.Source.EndLine, "Note");
    }
}

App.xaml, after the theme of the editor:

<SolidColorBrush x:Key="Md.Note.Background" Color="#F0F4FD" />
<SolidColorBrush x:Key="Md.Note.BorderBrush" Color="#326CF3" />
<Thickness x:Key="Md.Note.BorderThickness">4,0,0,0</Thickness>

Overriding built-in syntax

Extensions see the Markdig nodes before the viewer, so they can take over any built-in construct.

Footnotes as tooltips

The viewer draws a footnote definition where it is written. To show it at the reference instead, the extension turns each reference into a widget with the footnote text in a tooltip, and each definition into an empty block.

FootnoteTips.cs:

using System.Windows;
using Markdig.Extensions.Footnotes;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;
using Beresta.Markdown.Wpf.Extensions;
using Beresta.Markdown.Wpf.Selection;
using Beresta.Markdown.Wpf.ViewModels;

public sealed record FootnoteTipVm(int Order, string Markdown) : InlineVm, IMdCopyText
{
    public string CopyText => $"[{Order}]";
}

public sealed record HiddenBlockVm : BlockVm, IMdTextSource
{
    public void WriteText(MdTextWriter writer)
    {
    }
}

public sealed class FootnoteTipExtension : MdExtension
{
    private static readonly DataTemplate Nothing = new();

    public DataTemplate? TipTemplate { get; set; }

    public override InlineVm? ConvertInline(Inline inline, MdConvertContext context)
        => inline is FootnoteLink { IsBackLink: false } link
            ? new FootnoteTipVm(link.Footnote.Order, string.Join("\n\n", link.Footnote.Select(context.GetSource)))
            : null;

    public override BlockVm? ConvertBlock(Block block, MdConvertContext context)
        => block is Footnote ? new HiddenBlockVm() : null;

    public override DataTemplate? SelectTemplate(object item, DependencyObject container)
        => item switch
        {
            FootnoteTipVm => TipTemplate,
            HiddenBlockVm => Nothing,
            _ => null
        };
}

MainWindow.xaml, the viewer; the tooltip shows the footnote with one more viewer:

<md:MarkdownViewer Markdown="{Binding Text}">
    <md:MarkdownViewer.Extensions>
        <local:FootnoteTipExtension>
            <local:FootnoteTipExtension.TipTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Order, StringFormat='[{0}]'}" Foreground="#326CF3" Cursor="Help">
                        <TextBlock.ToolTip>
                            <ToolTip MaxWidth="400">
                                <md:MarkdownViewer Markdown="{Binding Markdown}" />
                            </ToolTip>
                        </TextBlock.ToolTip>
                    </TextBlock>
                </DataTemplate>
            </local:FootnoteTipExtension.TipTemplate>
        </local:FootnoteTipExtension>
    </md:MarkdownViewer.Extensions>
</md:MarkdownViewer>

The blank lines around a definition stay as space. The same comes ready-made with a template of the theme: FootnoteTips.

A code block of one language

The same way, blocks of one language become a widget — for example, diagrams drawn by your own control:

public sealed record DiagramVm(string Code) : BlockVm;

public override BlockVm? ConvertBlock(Block block, MdConvertContext context)
    => block is FencedCodeBlock { Info: "mermaid" } code ? new DiagramVm(code.Lines.ToString()) : null;

Links from a widget

A button or any other control of your widget follows a link the way a link in the text does: the MarkdownLink.Navigate handlers of the application first, then an anchor of the document, then the link opener — see Application Links. In a template, use the command MarkdownLink.ActivateCommand with the link as its parameter — here it is Url of the widget's model.

MainWindow.xaml, in the template of your widget:

<Button Content="Open the plan"
        Command="{x:Static md:MarkdownLink.ActivateCommand}"
        CommandParameter="{Binding Url}" />

From code, MarkdownLink.Activate(element, href) does the same; element is the control of your widget.

Styled text

Not every syntax of yours needs a widget: a piece of text with a look of its own — a chip, an insertion or a deletion of a review — can stay text. Then it is selected by pieces, found by search and wrapped like the rest of the text. A text piece RunVm carries the name of its look in StyleName and is drawn with the Span style under the theme key Md.<StyleName>.Style; Markup is the frame it gets in «Copy as Markdown». In the source of the editor the piece has the look of its StyleName, and the frame is markup where the source starts and ends with it — see The look in the source.

One Markdig node often gives several pieces — plain and bold text in one chip — so return them from ConvertInlines. An empty list hides the node. A piece of text made from scratch takes the formatting of its place — bold, italic, the link around it — from context.CreateRun(text). When the frame writes the link of the piece itself, as [[Page]] does, ReplacesLink = true keeps the Markdown link syntax off it.

A piece of styled text has a state too: CreateState gets its RunVm, the Span style reads the state through md:MdWidget.State, and a state that implements IMdClickableState gets a click on the piece that selected nothing — that is how a spoiler opens.

ChipExtension.cs, for ::text::, Markdig's inline custom container:

using Markdig.Extensions.CustomContainers;
using Markdig.Syntax.Inlines;
using Beresta.Markdown.Wpf.Extensions;
using Beresta.Markdown.Wpf.ViewModels;

public sealed class ChipExtension : MdExtension
{
    public override IReadOnlyList<InlineVm>? ConvertInlines(Inline inline, MdConvertContext context)
        => inline is CustomContainerInline chip
            ? context.ConvertInlines(chip)
                .Select(converted => converted is RunVm run ? run with { StyleName = "Chip", Markup = new("::", "::") } : converted)
                .ToList()
            : null;
}

App.xaml, the application resources:

<Style x:Key="Md.Chip.Style" TargetType="Span">
    <Setter Property="Background" Value="#DDF4FF" />
    <Setter Property="Foreground" Value="#0969DA" />
</Style>

Extension sets

MdExtensionSet connects several extensions as one: the viewer asks the set, the set asks its extensions in order. A set goes into Extensions next to single extensions; assemble it before connecting.

MainWindow.xaml:

<md:MarkdownViewer Markdown="{Binding Text}">
    <md:MarkdownViewer.Extensions>
        <md:MdExtensionSet>
            <local:ChipExtension />
            <local:SpoilerExtension />
        </md:MdExtensionSet>
        <local:MentionExtension />
    </md:MarkdownViewer.Extensions>
</md:MarkdownViewer>

A set of your own derives from MdExtensionSet and fills Extensions in its constructor; then it is connected in one line.

ReviewSet.cs:

using Beresta.Markdown.Wpf.Extensions;

public sealed class ReviewSet : MdExtensionSet
{
    public ReviewSet()
    {
        Extensions.Add(new ChipExtension());
        Extensions.Add(new SpoilerExtension());
    }
}

MainWindow.xaml.cs, in the constructor:

Viewer.Extensions.Add(new ReviewSet());

Ready-made sets for the syntax of GitHub, Obsidian and other programs are in Sets.

Shared extensions for many viewers

SharedExtensions gives many viewers one collection. It is inherited: set on a window or a panel, it reaches every viewer inside; a style can set it too. A viewer asks its own Extensions first, then the shared ones.

App.xaml, the application resources, after the templates NoteTemplate and MentionTemplate:

<md:MdExtensionCollection x:Key="AppExtensions">
    <local:NoteExtension Template="{StaticResource NoteTemplate}" />
    <local:MentionExtension Template="{StaticResource MentionTemplate}" />
</md:MdExtensionCollection>

MainWindow.xaml, on the window:

<Window ...
        md:MarkdownViewer.SharedExtensions="{StaticResource AppExtensions}">

Or for every viewer of the application — App.xaml, after the collection:

<Style TargetType="md:MarkdownViewer">
    <Setter Property="SharedExtensions" Value="{StaticResource AppExtensions}" />
</Style>

An extension added to the shared collection or removed from it reaches every viewer that uses it. The collection does not keep viewers in memory.

When an extension throws

The viewer catches an exception of an extension, so that a mistake in it does not bring the window down:

  • a node whose ConvertBlock or ConvertInline threw goes to the next extension and then to the built-in parsing;
  • a SetupPipeline that threw leaves none of its Markdig extensions behind;
  • a SelectTemplate that threw gives way to the template of the theme, a CreateState — to the next extension;
  • an EditSource that threw leaves the source as it was;
  • a widget whose WriteText threw becomes indivisible; in copied Markdown a widget whose text threw is written as its source.

A text Markdig itself fails to parse is shown as its source lines. Every caught exception comes to RenderFailed together with the extension whose method or widget threw it.

MainWindow.xaml.cs, in the constructor after InitializeComponent() (using System.Diagnostics;):

Viewer.RenderFailed += (_, e) => Trace.TraceError($"{e.Extension?.GetType().Name ?? "Markdig"}: {e.Exception}");

The event comes on the interface thread once the document is shown. IsBackground marks an exception of a background parse after which the same text parsed without errors on the interface thread — see Live Preview.

Good to know

  • Return the same DataTemplate instance for the same kind of model, not a new one per call: then a widget keeps its control when the text changes around it.
  • A widget may change its height after it loads — an image, a diagram: the visible part of the document stays in place.
  • Adding or removing an extension parses the document again and re-creates its blocks.
  • A long text may be parsed on a background thread — see Live Preview. An extension that must run on the interface thread overrides AllowsBackgroundParse to return false.

Beresta.Markdown.Wpf

Basics

Working with Text

Appearance

Integration

Editing

Your Own Syntax

Ready-made Extensions


По-русски

Основы

Работа с текстом

Оформление

Встраивание в приложение

Правка

Свой синтаксис

Готовые расширения

Clone this wiki locally