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 `( '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).. 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() } }