restores Helder in all its glory

This commit is contained in:
2026-09-28 11:34:49 +02:00
parent c2b38b853c
commit 1d29d0952d
280 changed files with 29205 additions and 7 deletions
@@ -0,0 +1,94 @@
import Foundation
/// The inline pass: a fixed order of rewrite rules that build nodes.
///
/// Each rule swaps its match for a placeholder that points at the node it built, so a later
/// rule can wrap earlier nodes (`**[a](b)**`) but never re-reads their text.
enum MarkdownInlineParser {
private static let open: Character = "\u{E000}"
private static let close: Character = "\u{E001}"
static func parse(_ source: String, baseDir: String) -> [MarkdownInline] {
var held: [MarkdownInline] = []
func hold(_ node: MarkdownInline) -> String {
held.append(node)
return "\(open)\(held.count - 1)\(close)"
}
func expand(_ text: Substring) -> [MarkdownInline] {
expandPlaceholders(text, held)
}
var s = source.replacing(/`([^`]+)`/) { hold(.code(String($0.1))) }
s = s.replacing(/!\[([^\]]*)\]\(([^)]*)\)/) { match in
let alt = plainText(expand(match.1))
let (url, title) = destination(match.2)
guard let safe = MarkdownParser.safeURL(url), !safe.isEmpty else { return alt }
let source: ImageSource
if MarkdownParser.isLocalURL(safe) {
source = .local(path: MarkdownParser.resolveRelative(baseDir: baseDir, url: safe))
} else if let remote = URL(string: safe) {
source = .remote(remote)
} else {
return alt
}
return hold(.image(alt: alt, source: source, title: title))
}
s = s.replacing(/\[([^\]]+)\]\(([^)]*)\)/) { match in
let (url, title) = destination(match.2)
guard let safe = MarkdownParser.safeURL(url), !safe.isEmpty else { return String(match.1) }
return hold(.link(text: expand(match.1), url: safe, title: title))
}
s = s.replacing(/\*\*([^*]+)\*\*/) { hold(.strong(expand($0.1))) }
s = s.replacing(/__([^_]+)__/) { hold(.strong(expand($0.1))) }
s = s.replacing(/\*([^*]+)\*/) { hold(.emphasis(expand($0.1))) }
s = s.replacing(/(^|[^a-zA-Z0-9_])_([^_]+)_(?=[^a-zA-Z0-9_]|$)/) { String($0.1) + hold(.emphasis(expand($0.2))) }
s = s.replacing(/~~([^~]+)~~/) { hold(.strikethrough(expand($0.1))) }
return expand(Substring(s))
}
/// Splits `(url)`, `(url "title")` or `(<url> 'title')` into the URL and the optional title.
static func destination(_ raw: Substring) -> (url: String, title: String?) {
guard let match = raw.wholeMatch(of: /\s*(?:<([^>]*)>|([^\s)]*))(?:\s+["'(]([^"')]*)["')])?\s*/) else {
return (raw.trimmingCharacters(in: .whitespaces), nil)
}
let url = (match.1 ?? match.2 ?? "").trimmingCharacters(in: .whitespaces)
let title = match.3.map(String.init).flatMap { $0.isEmpty ? nil : $0 }
return (url, title)
}
/// Text with placeholders turned back into the nodes they stand for.
private static func expandPlaceholders(_ text: Substring, _ held: [MarkdownInline]) -> [MarkdownInline] {
var nodes: [MarkdownInline] = []
var plain = ""
var index = text.startIndex
while index < text.endIndex {
let c = text[index]
if c == open, let end = text[index...].firstIndex(of: close),
let slot = Int(text[text.index(after: index)..<end]), held.indices.contains(slot) {
if !plain.isEmpty {
nodes.append(.text(plain))
plain = ""
}
nodes.append(held[slot])
index = text.index(after: end)
continue
}
plain.append(c)
index = text.index(after: index)
}
if !plain.isEmpty { nodes.append(.text(plain)) }
return nodes
}
/// The visible text of nodes, for an image's alt text.
static func plainText(_ nodes: [MarkdownInline]) -> String {
nodes.map { node in
switch node {
case let .text(text), let .code(text): text
case let .strong(children), let .emphasis(children), let .strikethrough(children): plainText(children)
case let .link(children, _, _): plainText(children)
case let .image(alt, _, _): alt
}
}.joined()
}
}
@@ -0,0 +1,33 @@
import Foundation
public enum TableAlignment: String, Sendable, Equatable {
case left, center, right
}
public enum ImageSource: Sendable, Equatable {
/// A project-relative file, read through FileServicing.
case local(path: String)
case remote(URL)
}
public indirect enum MarkdownInline: Sendable, Equatable {
case text(String)
case code(String)
case strong([MarkdownInline])
case emphasis([MarkdownInline])
case strikethrough([MarkdownInline])
case link(text: [MarkdownInline], url: String, title: String?)
case image(alt: String, source: ImageSource, title: String?)
}
public indirect enum MarkdownBlock: Sendable, Equatable {
case heading(level: Int, content: [MarkdownInline])
case paragraph([MarkdownInline])
/// A fenced block; `language` is nil when the info string is unknown.
case code(language: Language?, text: String)
case quote([MarkdownBlock])
case list(ordered: Bool, items: [[MarkdownInline]])
/// Header cells, per-column alignment, then body rows padded to the header width.
case table(header: [[MarkdownInline]], alignments: [TableAlignment?], rows: [[[MarkdownInline]]])
case rule
}
@@ -0,0 +1,215 @@
import Foundation
public enum MarkdownParser {
/// Parses a subset of Markdown: ATX headings, fenced code, rules, GFM
/// tables, block quotes (recursive), bullet and ordered lists, paragraphs, and inline
/// code, images, links, strong, emphasis and strikethrough.
///
/// Code spans are protected before any other inline rule runs. `baseDir` is the
/// document's folder, used to resolve local image paths. Unsafe URL schemes are dropped.
public static func parse(_ text: String, baseDir: String = "") -> [MarkdownBlock] {
let normalized = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")
let lines = normalized.components(separatedBy: "\n")
var blocks: [MarkdownBlock] = []
var paragraph: [String] = []
func flushParagraph() {
guard !paragraph.isEmpty else { return }
blocks.append(.paragraph(MarkdownInlineParser.parse(paragraph.joined(separator: " "), baseDir: baseDir)))
paragraph = []
}
func inline(_ text: String) -> [MarkdownInline] {
MarkdownInlineParser.parse(text, baseDir: baseDir)
}
var i = 0
while i < lines.count {
let line = lines[i]
if let fence = line.wholeMatch(of: /```\s*([\w+-]*)\s*/) {
flushParagraph()
var code: [String] = []
i += 1
while i < lines.count && lines[i].wholeMatch(of: /```\s*/) == nil {
code.append(lines[i])
i += 1
}
i += 1
blocks.append(.code(language: fenceLanguage(String(fence.1)), text: code.joined(separator: "\n")))
continue
}
if isBlank(line) {
flushParagraph()
i += 1
continue
}
if let heading = line.wholeMatch(of: /(#{1,6})\s+(.*)/) {
flushParagraph()
blocks.append(.heading(level: heading.1.count, content: inline(trimmed(heading.2))))
i += 1
continue
}
if isRule(line) {
flushParagraph()
blocks.append(.rule)
i += 1
continue
}
if line.contains("|") && i + 1 < lines.count {
let header = splitRow(line)
if let alignments = tableAlignments(lines[i + 1]), alignments.count == header.count {
flushParagraph()
i += 2
var rows: [[[MarkdownInline]]] = []
while i < lines.count && lines[i].contains("|") && !isBlank(lines[i]) {
let cells = splitRow(lines[i])
rows.append(header.indices.map { inline($0 < cells.count ? cells[$0] : "") })
i += 1
}
blocks.append(.table(header: header.map(inline), alignments: alignments, rows: rows))
continue
}
}
if line.prefixMatch(of: /\s*>/) != nil {
flushParagraph()
var quoted: [String] = []
while i < lines.count, let marker = lines[i].prefixMatch(of: /\s*>\s?/) {
quoted.append(String(lines[i][marker.range.upperBound...]))
i += 1
}
blocks.append(.quote(parse(quoted.joined(separator: "\n"), baseDir: baseDir)))
continue
}
if let items = listItems(lines, &i, marker: /\s*[-*+]\s+/) {
flushParagraph()
blocks.append(.list(ordered: false, items: items.map(inline)))
continue
}
if let items = listItems(lines, &i, marker: /\s*\d+[.)]\s+/) {
flushParagraph()
blocks.append(.list(ordered: true, items: items.map(inline)))
continue
}
paragraph.append(trimmed(line))
i += 1
}
flushParagraph()
return blocks
}
/// The consecutive lines that start with `marker`, stripped of it; nil when line `i` does not.
private static func listItems(_ lines: [String], _ i: inout Int, marker: Regex<Substring>) -> [String]? {
var items: [String] = []
while i < lines.count, let match = lines[i].prefixMatch(of: marker) {
items.append(String(lines[i][match.range.upperBound...]))
i += 1
}
return items.isEmpty ? nil : items
}
private static func isBlank(_ line: String) -> Bool {
line.allSatisfy(\.isWhitespace)
}
private static func trimmed<S: StringProtocol>(_ text: S) -> String {
text.trimmingCharacters(in: .whitespacesAndNewlines)
}
/// Three or more of one of `-`, `*`, `_`, spaces allowed between them.
private static func isRule(_ line: String) -> Bool {
let marks = line.filter { !$0.isWhitespace }
guard marks.count >= 3, let first = marks.first, "-*_".contains(first) else { return false }
return marks.allSatisfy { $0 == first }
}
/// One GFM table row split into trimmed cells; `\\|` is a literal pipe, not a divider.
static func splitRow(_ line: String) -> [String] {
var row = Substring(trimmed(line))
if row.hasPrefix("|") { row = row.dropFirst() }
if row.hasSuffix("|") && !row.dropLast().hasSuffix("\\") { row = row.dropLast() }
var cells: [String] = []
var current = ""
var index = row.startIndex
while index < row.endIndex {
let c = row[index]
let next = row.index(after: index)
if c == "\\" && next < row.endIndex && row[next] == "|" {
current.append("|")
index = row.index(after: next)
continue
}
if c == "|" {
cells.append(current)
current = ""
} else {
current.append(c)
}
index = next
}
cells.append(current)
return cells.map { trimmed($0) }
}
/// The `---`/`:---:` row under a table header, as per-column alignments; nil when the line is not one.
static func tableAlignments(_ line: String) -> [TableAlignment?]? {
if !line.contains("|") && line.wholeMatch(of: /\s*:?-+:?\s*/) == nil { return nil }
var alignments: [TableAlignment?] = []
for cell in splitRow(line) {
guard cell.wholeMatch(of: /:?-+:?/) != nil else { return nil }
let left = cell.hasPrefix(":"), right = cell.hasSuffix(":")
alignments.append(left && right ? .center : right ? .right : left ? .left : nil)
}
return alignments
}
private static let fenceLanguages: [String: Language] = [
"php": .php, "js": .javascript, "javascript": .javascript, "mjs": .javascript,
"jsx": .jsx, "ts": .typescript, "typescript": .typescript, "tsx": .tsx,
"py": .python, "python": .python, "html": .markup, "xml": .markup, "vue": .markup,
"css": .css, "scss": .css, "json": .json, "sh": .bash, "bash": .bash, "shell": .bash,
"yml": .yaml, "yaml": .yaml, "md": .markdown, "markdown": .markdown,
]
/// The highlighter grammar for a fence info string.
public static func fenceLanguage(_ info: String) -> Language? {
fenceLanguages[info.lowercased()]
}
/// Keeps http(s), mailto, anchors and relative paths; returns nil for any other scheme (e.g. `javascript:`).
public static func safeURL(_ url: String) -> String? {
let u = url.trimmingCharacters(in: .whitespaces)
if u.range(of: "^(https?:|mailto:|#|\\.?\\.?/)", options: [.regularExpression, .caseInsensitive]) != nil { return u }
if u.range(of: "^[a-z][a-z0-9+.-]*:", options: [.regularExpression, .caseInsensitive]) != nil { return nil }
return u
}
/// True when a URL names a file next to the document rather than a remote resource.
public static func isLocalURL(_ url: String) -> Bool {
url.range(of: "^(https?:|data:|mailto:|#)", options: [.regularExpression, .caseInsensitive]) == nil
}
/// Resolves a document link to a project-relative path; a leading `/` means the project root.
public static func resolveRelative(baseDir: String, url: String) -> String {
var u = String(url.split(separator: "#", omittingEmptySubsequences: false).first ?? "")
u = String(u.split(separator: "?", omittingEmptySubsequences: false).first ?? "")
u = u.removingPercentEncoding ?? u
let joined = u.hasPrefix("/") ? u : baseDir + "/" + u
var out: [Substring] = []
for segment in joined.split(separator: "/", omittingEmptySubsequences: true) {
if segment == "." { continue }
if segment == ".." {
_ = out.popLast()
continue
}
out.append(segment)
}
return out.joined(separator: "/")
}
}