xoofx / markdig

A fast, powerful, CommonMark compliant, extensible Markdown processor for .NET
BSD 2-Clause "Simplified" License
4.21k stars 444 forks source link

Can I somehow customise math processing? #778

Closed Kazbek closed 4 months ago

Kazbek commented 4 months ago

Im using math like this e=mc^2 and not it output to

<span class="math">\(e=mc^2\)</span>

and want to customize output Latex formula. Not just place it "as is" but process with my string to string function

string processTexFormula(string rawTex)
{
    //actually here will be server prerendering
    return"test_" + rawText;
}

so output will be:

<span class="math">\(test_e=mc^2\)</span>

Can I somehow configure Math processor? I guess it must affect in this two places: one and two

MihaZupan commented 4 months ago

Instead of modifying the parser/renderer, the easiest way to do something like this is likely to post-process the syntax tree before you render it

MarkdownPipeline pipeline = new MarkdownPipelineBuilder()
    .UseMathematics()
    .Build();

string markdown = "$e=mc^2$";

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

foreach (MathInline math in document.Descendants<MathInline>())
{
    math.Content = new StringSlice(math.Content.ToString().Replace("e", "42"));
}

string html = document.ToHtml(pipeline);
// <p><span class="math">\(42=mc^2\)</span></p>
Kazbek commented 4 months ago

@MihaZupan it works good but escaping string that I put in content. So instead

<span class="katex">

I have:

&lt;span class=&quot;katex&quot;&gt

Can I somehow write just this part unescaped?

Kazbek commented 4 months ago

Made my own UseMathematics with custom renderer solved this problem.