Skip to content

Markdown to HTML Converter — C# source

Render Markdown into clean, escaped HTML: headings, lists, links, images, code blocks and quotes. Every input is escaped first, so the output is always safe markup. Runs locally with a shareable link.

This is the C# implementation — the same logic the interactive tool runs, in a shareable, citable form.

// markdown-to-html — escape-first CommonMark subset → HTML renderer. C# port
// (canonical TS: src/lib/markdown-to-html.ts; Go twin: cli/markdown-to-html).
// Hand-rolled CommonMark SUBSET — everything is HTML-escaped before the inline
// rules run (raw HTML never passes through; security first), via the shared
// five-char escaper inlined here (`&` first so the entities we emit are never
// re-escaped). Supported blocks: #-headings (1-6), --- /***/ ___ rules, ```
// fenced code (markdown inert inside), > blockquotes (recursive), - * +
// unordered lists, N. ordered lists (source numbers stripped), paragraphs
// (soft line breaks joined with \n). Inline precedence: code spans first
// (placeholder-protected), then images, links, bold, italic, strikethrough —
// non-greedy pairs. Not supported (by design, documented): raw HTML, tables,
// setext headings, nested lists, footnotes, autolinks. Empty or whitespace-only
// input is NOT an error — the tool shows nothing. Never throws.
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

public static class MarkdownToHtml
{
    private static readonly Regex Heading = new Regex("^(#{1,6}) (.*)$");
    private static readonly Regex Hr = new Regex("^(---+|\\*\\*\\*+|___+)\\s*$");
    private static readonly Regex Ul = new Regex("^[-*+] ");
    private static readonly Regex Ol = new Regex("^\\d+\\. ");
    private static readonly Regex CodeSpan = new Regex("`([^`]+)`");
    private static readonly Regex Image = new Regex("!\\[([^\\]]*)\\]\\(([^)\\s]+)\\)");
    private static readonly Regex Link = new Regex("\\[([^\\]]+)\\]\\(([^)\\s]+)\\)");

    /// Result union mirror: Output + nullable Error (null on success).
    public sealed class Result
    {
        public string Output { get; set; } = "";
        public string Error { get; set; }
    }

    /// JS-style global replace: each match becomes a computed string (no
    /// replacement-template escapes, captured text is emitted verbatim).
    private static string ReplaceAll(string s, Regex re, Func<Match, string> f)
    {
        var outB = new StringBuilder();
        int last = 0;
        foreach (Match m in re.Matches(s))
        {
            outB.Append(s, last, m.Index - last).Append(f(m));
            last = m.Index + m.Length;
        }
        return outB.Append(s.Substring(last)).ToString();
    }

    /// Five-char escaper (from src/lib/htmlEntities.ts); `&` is replaced first
    /// so the entities we emit are never re-escaped.
    public static string EncodeHtml(string text) => text
        .Replace("&", "&amp;")
        .Replace("<", "&lt;")
        .Replace(">", "&gt;")
        .Replace("'", "&apos;")
        .Replace("\"", "&quot;");

    /// Inline pass: code spans first (placeholder-protected), then images,
    /// links, bold, italic, strikethrough — non-greedy pairs.
    private static string RenderInline(string s)
    {
        var codes = new List<string>();
        var text = ReplaceAll(s, CodeSpan, m =>
        {
            codes.Add("<code>" + EncodeHtml(m.Groups[1].Value) + "</code>");
            return "\u0000" + (codes.Count - 1) + "\u0000";
        });
        text = EncodeHtml(text);
        text = ReplaceAll(text, Image, m => "<img src=\"" + m.Groups[2].Value + "\" alt=\"" + m.Groups[1].Value + "\">");
        text = ReplaceAll(text, Link, m => "<a href=\"" + m.Groups[2].Value + "\">" + m.Groups[1].Value + "</a>");
        text = ReplaceAll(text, new Regex("\\*\\*([^*]+)\\*\\*"), m => "<strong>" + m.Groups[1].Value + "</strong>");
        text = ReplaceAll(text, new Regex("__([^_]+)__"), m => "<strong>" + m.Groups[1].Value + "</strong>");
        text = ReplaceAll(text, new Regex("\\*([^*]+)\\*"), m => "<em>" + m.Groups[1].Value + "</em>");
        text = ReplaceAll(text, new Regex("_([^_]+)_"), m => "<em>" + m.Groups[1].Value + "</em>");
        text = ReplaceAll(text, new Regex("~~([^~]+)~~"), m => "<del>" + m.Groups[1].Value + "</del>");
        return ReplaceAll(text, new Regex("\u0000(\\d+)\u0000"), m => codes[int.Parse(m.Groups[1].Value)]);
    }

    /// True when a line STARTS a new block — the paragraph terminator. Any new
    /// block type must register here and in the RenderBlock dispatch below.
    private static bool IsBlockStart(string line) =>
        Heading.IsMatch(line) || Hr.IsMatch(line) || line.StartsWith("```") ||
        line.StartsWith("> ") || Ul.IsMatch(line) || Ol.IsMatch(line);

    /// Render consecutive lines (one blank-line-separated chunk).
    private static void RenderBlock(List<string> lines, List<string> out)
    {
        int i = 0;
        while (i < lines.Count)
        {
            string line = lines[i];

            Match heading = Heading.Match(line);
            if (heading.Success)
            {
                int level = heading.Groups[1].Value.Length;
                out.Add("<h" + level + ">" + RenderInline(heading.Groups[2].Value.Trim()) + "</h" + level + ">");
                i++;
                continue;
            }

            if (Hr.IsMatch(line))
            {
                out.Add("<hr>");
                i++;
                continue;
            }

            if (line.StartsWith("```"))
            {
                string lang = line.Substring(3).Trim();
                var body = new List<string>();
                i++;
                while (i < lines.Count && !lines[i].StartsWith("```"))
                {
                    body.Add(lines[i]);
                    i++;
                }
                i++; // past the closing fence (or past the end of an unclosed fence)
                string cls = lang.Length == 0 ? "" : " class=\"language-" + EncodeHtml(lang) + "\"";
                out.Add("<pre><code" + cls + ">" + EncodeHtml(string.Join("\n", body)) + "</code></pre>");
                continue;
            }

            if (line.StartsWith("> "))
            {
                var quoted = new List<string>();
                while (i < lines.Count && lines[i].StartsWith("> "))
                {
                    quoted.Add(lines[i].Substring(2));
                    i++;
                }
                var inner = new List<string>();
                RenderBlock(quoted, inner);
                out.Add("<blockquote>\n" + string.Join("\n", inner) + "\n</blockquote>");
                continue;
            }

            if (Ul.IsMatch(line))
            {
                var items = new List<string>();
                while (i < lines.Count && Ul.IsMatch(lines[i]))
                {
                    items.Add("<li>" + RenderInline(lines[i].Substring(2)) + "</li>");
                    i++;
                }
                out.Add("<ul>\n" + string.Join("\n", items) + "\n</ul>");
                continue;
            }

            if (Ol.IsMatch(line))
            {
                var items = new List<string>();
                while (i < lines.Count && Ol.IsMatch(lines[i]))
                {
                    Match om = Ol.Match(lines[i]);
                    items.Add("<li>" + RenderInline(lines[i].Substring(om.Value.Length)) + "</li>");
                    i++;
                }
                out.Add("<ol>\n" + string.Join("\n", items) + "\n</ol>");
                continue;
            }

            var para = new List<string>();
            while (i < lines.Count && !IsBlockStart(lines[i]))
            {
                para.Add(RenderInline(lines[i].Trim()));
                i++;
            }
            out.Add("<p>" + string.Join("\n", para) + "</p>");
        }
    }

    /// Convert the supported Markdown subset to HTML. Never fails.
    public static Result ToHtml(string raw)
    {
        string text = Regex.Replace(raw ?? "", "\r\n?", "\n").Trim();
        if (text.Length == 0) return new Result(); // empty input is NOT an error
        var out = new List<string>();
        foreach (string block in Regex.Split(text, "\n{2,}"))
        {
            var lines = new List<string>();
            foreach (string l in block.Split('\n'))
            {
                if (l.Trim().Length != 0) lines.Add(l);
            }
            RenderBlock(lines, out);
        }
        return new Result { Output = string.Join("\n", out), Error = null };
    }
}

// Example:
// MarkdownToHtml.ToHtml("## Hello *world*").Output
// → "<h2>Hello <em>world</em></h2>"
// MarkdownToHtml.ToHtml("```js\nconst x = 1; // <b>\n```").Output
// → "<pre><code class=\"language-js\">const x = 1; // &lt;b&gt;</code></pre>"
// MarkdownToHtml.ToHtml("<script>alert(1)</script>").Output
// → "<p>&lt;script&gt;alert(1)&lt;/script&gt;</p>"

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →