using System.Globalization; using System.Net; using System.Text; using System.Text.RegularExpressions; namespace Khaemhat.Web.Help; /// Where the links and images of a wiki page point inside the application. /// The address of another wiki page (Anagrafiche, Anagrafiche#clienti). /// The local address of an image, or to keep the original one. public sealed record WikiLinks(Func Page, Func Media); /// /// Turns the Markdown of docs/wiki/ into HTML for the help (SPEC §17, mockup 011), written in house (no external /// libraries, ADR 0002). It covers what the wiki uses: headings with anchors, paragraphs, bold, italic, code, links, /// images, nested lists, tables, quotes, code blocks and rules. Every piece of text is encoded and only http, https, /// anchors and wiki pages become links, so a page cannot inject markup or scripts. /// public static partial class WikiMarkdown { /// Converts a page. /// The Markdown. /// Where links and images go. /// The HTML. public static string ToHtml(string markdown, WikiLinks links) { ArgumentNullException.ThrowIfNull(markdown); ArgumentNullException.ThrowIfNull(links); var lines = markdown.Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n').Split('\n'); var html = new StringBuilder(); new Parser(lines, links, html).Blocks(0, lines.Length); return html.ToString(); } /// The anchor of a heading, as the wiki makes it: lower case, words joined by dashes. /// The heading text (Markdown). /// The anchor. public static string Slug(string text) { ArgumentNullException.ThrowIfNull(text); var plain = PlainText(text).ToLower(CultureInfo.InvariantCulture); var slug = new StringBuilder(); foreach (var c in plain) { if (char.IsLetterOrDigit(c) || c is '-' or '_') { slug.Append(c); } else if (c == ' ') { slug.Append('-'); } } return slug.ToString(); } /// The text of a line of Markdown without its marks. /// The Markdown. /// The text. public static string PlainText(string text) { ArgumentNullException.ThrowIfNull(text); var plain = LinkPattern().Replace(text, "$1"); return plain.Replace("**", string.Empty, StringComparison.Ordinal).Replace("`", string.Empty, StringComparison.Ordinal) .Replace("*", string.Empty, StringComparison.Ordinal).Trim(); } [GeneratedRegex(@"!?\[([^\]]*)\]\([^)]*\)")] private static partial Regex LinkPattern(); [GeneratedRegex(@"^(\s*)([-*+]|\d+[.)])\s+(.*)$")] private static partial Regex ListItemPattern(); [GeneratedRegex(@"^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?\s*$")] private static partial Regex TableRulePattern(); [GeneratedRegex(@"^(#{1,6})\s+(.*?)\s*#*\s*$")] private static partial Regex HeadingPattern(); [GeneratedRegex(@"^[A-Za-z0-9][A-Za-z0-9-]*(#[A-Za-z0-9_\-\p{L}]*)?$")] private static partial Regex PagePattern(); private sealed class Parser(string[] lines, WikiLinks links, StringBuilder html) { public void Blocks(int start, int end) { var i = start; while (i < end) { var line = lines[i]; var trimmed = line.Trim(); if (trimmed.Length == 0) { i++; } else if (trimmed.StartsWith("```", StringComparison.Ordinal)) { i = Fence(i, end); } else if (HeadingPattern().Match(trimmed) is { Success: true } heading) { var level = heading.Groups[1].Length; var text = heading.Groups[2].Value; html.Append(CultureInfo.InvariantCulture, $"").Append(Inline(text)).Append(CultureInfo.InvariantCulture, $"\n"); i++; } else if (trimmed is "---" or "***" or "___") { html.Append("
\n"); i++; } else if (trimmed.StartsWith('>')) { i = Quote(i, end); } else if (trimmed.StartsWith('|') && i + 1 < end && TableRulePattern().IsMatch(lines[i + 1])) { i = Table(i, end); } else if (ListItemPattern().Match(line) is { Success: true } item) { i = List(i, end, item.Groups[1].Value.Length); } else { i = Paragraph(i, end); } } } private int Fence(int i, int end) { var body = new List(); var j = i + 1; while (j < end && !lines[j].Trim().StartsWith("```", StringComparison.Ordinal)) { body.Add(lines[j]); j++; } html.Append("
").Append(Encode(string.Join('\n', body))).Append("
\n"); return Math.Min(j + 1, end); } private int Quote(int i, int end) { var inner = new List(); var j = i; while (j < end && lines[j].TrimStart().StartsWith('>')) { var text = lines[j].TrimStart()[1..]; inner.Add(text.StartsWith(' ') ? text[1..] : text); j++; } // "> **Stato:** bozza · ..." at the top of every page is the page state, not a note. var meta = inner.Count > 0 && inner[0].StartsWith("**Stato:**", StringComparison.Ordinal); html.Append(meta ? "
" : "
"); // Each line of the page state is a fact of its own: keep them on separate lines. var nested = new Parser(meta ? [.. inner.Select((l, n) => n < inner.Count - 1 ? l.TrimEnd() + " " : l)] : [.. inner], links, html); nested.Blocks(0, inner.Count); html.Append(meta ? "
\n" : "
\n"); return j; } private int Table(int i, int end) { var header = Cells(lines[i]); html.Append("
"); foreach (var cell in header) { html.Append(""); } html.Append(""); var j = i + 2; while (j < end && lines[j].Trim().StartsWith('|')) { html.Append(""); var cells = Cells(lines[j]); for (var c = 0; c < header.Count; c++) { html.Append(""); } html.Append(""); j++; } html.Append("
").Append(Inline(cell)).Append("
").Append(c < cells.Count ? Inline(cells[c]) : string.Empty).Append("
\n"); return j; } private static List Cells(string line) { var text = line.Trim(); if (text.StartsWith('|')) { text = text[1..]; } if (text.EndsWith('|') && !text.EndsWith("\\|", StringComparison.Ordinal)) { text = text[..^1]; } var cells = new List(); var current = new StringBuilder(); var inCode = false; for (var k = 0; k < text.Length; k++) { var c = text[k]; if (c == '\\' && k + 1 < text.Length && text[k + 1] == '|') { current.Append('|'); k++; } else if (c == '`') { inCode = !inCode; current.Append(c); } else if (c == '|' && !inCode) { cells.Add(current.ToString().Trim()); current.Clear(); } else { current.Append(c); } } cells.Add(current.ToString().Trim()); return cells; } private int List(int i, int end, int indent) { var ordered = char.IsDigit(ListItemPattern().Match(lines[i]).Groups[2].Value[0]); html.Append(ordered ? "
    " : "
      "); var j = i; while (j < end) { var match = ListItemPattern().Match(lines[j]); if (!match.Success || match.Groups[1].Value.Length != indent) { break; } var text = new StringBuilder(match.Groups[3].Value); j++; var nested = new StringBuilder(); while (j < end) { var line = lines[j]; var lead = line.Length - line.TrimStart().Length; if (line.Trim().Length == 0) { // A blank line ends the item unless the list goes on after it. var next = j + 1; if (next < end && lines[next].Trim().Length > 0 && (lines[next].Length - lines[next].TrimStart().Length) > indent) { j++; continue; } break; } if (ListItemPattern().Match(line) is { Success: true } sub) { if (sub.Groups[1].Value.Length > indent) { var inner = new StringBuilder(); j = new Parser(lines, links, inner).List(j, end, sub.Groups[1].Value.Length); nested.Append(inner); continue; } break; } if (lead <= indent || IsBlockStart(line)) { break; } text.Append(' ').Append(line.Trim()); j++; } html.Append("
    • ").Append(Inline(text.ToString())).Append(nested).Append("
    • "); if (j < end && lines[j].Trim().Length == 0 && j + 1 < end && ListItemPattern().Match(lines[j + 1]) is { Success: true } after && after.Groups[1].Value.Length == indent) { j++; } } html.Append(ordered ? "
\n" : "\n"); return j; } private int Paragraph(int i, int end) { var text = new StringBuilder(); var j = i; while (j < end && lines[j].Trim().Length > 0 && (j == i || !IsBlockStart(lines[j]))) { // Two spaces at the end of a line are a line break, as in the wiki. var line = lines[j]; text.Append(Inline(line.Trim())).Append(line.EndsWith(" ", StringComparison.Ordinal) ? "
" : " "); j++; } html.Append("

").Append(text.ToString().TrimEnd()).Append("

\n"); return j; } private static bool IsBlockStart(string line) { var trimmed = line.Trim(); return trimmed.StartsWith("```", StringComparison.Ordinal) || trimmed.StartsWith('>') || trimmed.StartsWith('|') || HeadingPattern().IsMatch(trimmed) || ListItemPattern().IsMatch(line) || trimmed is "---" or "***" or "___"; } private string Inline(string text) { var output = new StringBuilder(); var i = 0; while (i < text.Length) { var c = text[i]; if (c == '\\' && i + 1 < text.Length && char.IsPunctuation(text[i + 1]) || c == '\\' && i + 1 < text.Length && char.IsSymbol(text[i + 1])) { output.Append(Encode(text[i + 1].ToString())); i += 2; } else if (c == '`' && text.IndexOf('`', i + 1) is var close && close > i) { output.Append("").Append(Encode(text[(i + 1)..close])).Append(""); i = close + 1; } else if (c == '!' && i + 1 < text.Length && text[i + 1] == '[' && TryLink(text, i + 1, out var alt, out var src, out var after)) { var local = links.Media(src); var url = local ?? (IsWeb(src) ? src : null); output.Append(url is null ? Encode(alt) : $"\"{Attr(PlainText(alt))}\""); i = after; } else if (c == '[' && TryLink(text, i, out var label, out var href, out var next)) { output.Append(Anchor(label, href)); i = next; } else if (c == '*' && i + 1 < text.Length && text[i + 1] == '*' && text.IndexOf("**", i + 2, StringComparison.Ordinal) is var bold && bold > i + 2) { output.Append("").Append(Inline(text[(i + 2)..bold])).Append(""); i = bold + 2; } else if (c is '*' or '_' && i + 1 < text.Length && !char.IsWhiteSpace(text[i + 1]) && (c == '*' || i == 0 || !char.IsLetterOrDigit(text[i - 1])) && Closing(text, i + 1, c) is var em && em > i + 1) { output.Append("").Append(Inline(text[(i + 1)..em])).Append(""); i = em + 1; } else if (c == '<' && text.AsSpan(i).StartsWith("', i) is var gt && gt > i) { output.Append("
"); i = gt + 1; } else { output.Append(Encode(c.ToString())); i++; } } return output.ToString(); } private static int Closing(string text, int from, char mark) { for (var k = from; k < text.Length; k++) { if (text[k] == mark && !char.IsWhiteSpace(text[k - 1]) && (k + 1 >= text.Length || text[k + 1] != mark) && (mark == '*' || k + 1 >= text.Length || !char.IsLetterOrDigit(text[k + 1]))) { return k; } } return -1; } private static bool TryLink(string text, int open, out string label, out string href, out int after) { label = href = string.Empty; after = open; var depth = 0; var k = open; for (; k < text.Length; k++) { if (text[k] == '[') { depth++; } else if (text[k] == ']' && --depth == 0) { break; } } if (k + 1 >= text.Length || text[k + 1] != '(') { return false; } var closeParen = text.IndexOf(')', k + 2); if (closeParen < 0) { return false; } label = text[(open + 1)..k]; href = text[(k + 2)..closeParen].Trim(); var space = href.IndexOf(' ', StringComparison.Ordinal); if (space > 0) { href = href[..space]; } after = closeParen + 1; return true; } private string Anchor(string label, string href) { var inner = Inline(label); if (IsWeb(href)) { return $"{inner}"; } if (href.StartsWith('#')) { return $"{inner}"; } return PagePattern().IsMatch(href) ? $"{inner}" : inner; } private static bool IsWeb(string url) => url.StartsWith("https://", StringComparison.OrdinalIgnoreCase) || url.StartsWith("http://", StringComparison.OrdinalIgnoreCase); private static string Encode(string text) => WebUtility.HtmlEncode(text); private static string Attr(string text) => WebUtility.HtmlEncode(text); } }