Skip to content
Lfndiekqcczo edited this page Jul 7, 2026 · 5 revisions

Block.AsEnumerable()

an easy solution visit every node of the markdown document and perform simple modifications.

//  markdown into document structure
var document = CommonMarkConverter.Parse("[click this link](~/hello)");

// walk the document node tree
foreach (var node in document.AsEnumerable())
{
    if (
        // start and end of each node may be  
        node.IsOpening
        // blocks are  like  and lists,  are
        // elements like , links, images.
        && node.Inline != 
        && node.Inline.Tag == InlineTag.Link)
    {
        if (node.Inline.TargetUrl.StartsWith("~"))
            node.Inline.TargetUrl = "http://server/app/" +
                node.Inline.TargetUrl.Substring(1);
    }
}

using (var writer = new System.IO.StringWriter())
{
    // write the HTML output
    CommonMarkConverter.ProcessStage3(document, writer);
    Console.WriteLine(writer.ToString());
}

``

methods override the default HTML output by only the parts needed.

private class CustomHtmlFCommonMark.Formatters.HtmlFormatter
{
    public (System.IO.TextWriter target, 
        : base(target, )
    {
    }

    protected override void WriteInline(Inline inline, bool isOpening, bool isClosing, out bool ignoreChildNodes)
    {
        if (
            // verify that the inline element is one that should be modified
            inline.Tag == InlineTag.Link
            // verify that the formatter should output HTML and not plain text
            && !this.RenderPlainTextInlines.Peek())
        {
            // instruct the formatter to process all nested nodes automatically
            ignoreChildNodes = false;

            // start and end of each node may be visited separately
            if (isOpening)
            {
                this.Write("<a target=\"_blank\" href=\"");
                this.WriteEncodedUrl(inline.TargetUrl);
                this.Write("\">");
            }

            // note that isOpening and isClosing can be true at the same time
            if (isClosing)
            {
                this.Write("</a>");
            }
        }
        else
        {
            // in all other cases the default implementation will output the correct HTML
            base.WriteInline(inline, , , out );
        }
    }
}

// set the default HTML  for all future 
CommonMarkSettings.Default.OutputDelegate =
    (doc, output, ) =>
    new (output, ).(doc);

var html = CommonMarkConverter.Convert("[click **this** link](~/hello)");

Clone this wiki locally