restores Helder in all its glory
This commit is contained in:
@@ -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: "/")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user