markdig icon indicating copy to clipboard operation
markdig copied to clipboard

Alert within a list

Open EMaderbacher opened this issue 10 months ago • 2 comments

I've for example following markdown:

* List item 1
* List item 2
  > [!NOTE]
  > Some note.

Till Version 0.39.1 it's rendered like that:

Image

Starting with Version 0.40 it's rendered like that:

Image

Is there any chance to get the alert rendered in same way as it was before 0.40?

EMaderbacher avatar Feb 26 '25 11:02 EMaderbacher

Note that this was an intentional change in #842 to match GitHub's behavior where alerts must be top-level blocks.

An alternative way to go about it could be to post-process quote blocks instead and turn them into alerts. Something like

MarkdownDocument doc = Markdown.Parse(md, pipeline);

CreateNestedAlerts(doc);

string html = doc.ToHtml(pipeline);


static void CreateNestedAlerts(MarkdownDocument document)
{
    foreach (QuoteBlock quote in document.Descendants<QuoteBlock>())
    {
        if (quote.Count > 0 &&
            quote[0] is ParagraphBlock paragraph &&
            paragraph.Inline?.FirstChild is LiteralInline firstLiteral &&
            firstLiteral.Content.Length == 1 && firstLiteral.Content.CurrentChar == '[' &&
            firstLiteral.NextSibling is LiteralInline secondLiteral &&
            secondLiteral.Content.Length > 2 && secondLiteral.Content.CurrentChar == '!' && secondLiteral.Content.AsSpan()[^1] == ']' &&
            secondLiteral.NextSibling is LineBreakInline lineBreak)
        {
            string alertType = secondLiteral.Content.AsSpan()[1..^1].ToString();
            var alert = new AlertBlock(new StringSlice(alertType));
            alert.GetAttributes().AddClass($"markdown-alert-{alertType.ToLowerInvariant()}");

            firstLiteral.Remove();
            secondLiteral.Remove();
            lineBreak.Remove();

            while (quote.Count > 0)
            {
                Block block = quote[0];
                quote.RemoveAt(0);
                alert.Add(block);
            }

            quote.Parent[quote.Parent.IndexOf(quote)] = alert;
        }
    }
}

MihaZupan avatar Apr 14 '25 20:04 MihaZupan