import Foundation /// A Markdown document's blocks, as `MarkdownBlocks.parse` reads them: CommonMark's block /// structure plus GFM tables, task items and footnotes, and Obsidian's callouts and `%%` /// comments when `obsidian` is set. indirect enum MarkdownBlock: Equatable, Sendable { /// An ATX or setext heading; `text` is the raw inline text. case heading(level: Int, text: String) /// Raw lines, inline markup unconverted. case paragraph([String]) /// A fenced block (`lang` from its info string) or an indented one (`fenced` false). case code(lang: String, lines: [String], fenced: Bool) /// `$$ … $$` on lines of their own. case math([String]) /// `%% … %%` (Obsidian) or `` on lines of their own. case comment([String]) case html([String]) case quote([MarkdownBlock]) /// `> [!type] title`; `type` lowercased. case callout(type: String, title: String, blocks: [MarkdownBlock]) case list(ordered: Bool, start: Int, items: [MarkdownItem]) case table(header: [String], rows: [[String]]) case rule } struct MarkdownItem: Equatable, Sendable { /// The character between a task item's brackets, `nil` for a plain item. var task: Character? var blocks: [MarkdownBlock] } /// What a parse found besides blocks: footnote definitions and link reference definitions. struct MarkdownDefinitions { var footnotes: [(label: String, blocks: [MarkdownBlock])] = [] /// Lowercased, whitespace-collapsed label to destination. var links: [String: String] = [:] } struct MarkdownBlocks { let obsidian: Bool var definitions = MarkdownDefinitions() init(obsidian: Bool) { self.obsidian = obsidian } static func parse(_ text: String, obsidian: Bool) -> (blocks: [MarkdownBlock], definitions: MarkdownDefinitions) { var parser = MarkdownBlocks(obsidian: obsidian) let lines = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n") .split(separator: "\n", omittingEmptySubsequences: false).map { expandTabs(String($0)) } let blocks = parser.blocks(lines) return (blocks, parser.definitions) } /// Tabs to spaces at four-column stops, in the leading whitespace only. static func expandTabs(_ line: String) -> String { guard line.contains("\t") else { return line } var out = "" var column = 0 var leading = true for char in line { if leading, char == "\t" { let width = 4 - column % 4 out += String(repeating: " ", count: width) column += width } else { if char != " " { leading = false } out.append(char) column += 1 } } return out } // MARK: - Line tests static func indent(_ line: String) -> Int { line.prefix { $0 == " " }.count } static func isBlank(_ line: String) -> Bool { line.allSatisfy { $0 == " " } } static func fence(_ line: String) -> (char: Character, count: Int, indent: Int, info: String)? { let indent = indent(line) guard indent <= 3 else { return nil } let rest = line.dropFirst(indent) guard let char = rest.first, char == "`" || char == "~" else { return nil } let count = rest.prefix { $0 == char }.count guard count >= 3 else { return nil } let info = rest.dropFirst(count).trimmingCharacters(in: .whitespaces) if char == "`", info.contains("`") { return nil } return (char, count, indent, info) } static func atxHeading(_ line: String) -> (level: Int, text: String)? { let indent = indent(line) guard indent <= 3 else { return nil } let rest = line.dropFirst(indent) let level = rest.prefix { $0 == "#" }.count guard (1...6).contains(level) else { return nil } let after = rest.dropFirst(level) guard after.isEmpty || after.first == " " else { return nil } var text = after.trimmingCharacters(in: .whitespaces) // A closing sequence of #s preceded by a space. if let closing = text.lastIndex(where: { $0 != "#" }) { let tail = text[text.index(after: closing)...] if !tail.isEmpty, text[closing] == " " { text = String(text[...closing]).trimmingCharacters(in: .whitespaces) } } else { text = "" } return (level, text) } static func isRule(_ line: String) -> Bool { guard indent(line) <= 3 else { return false } let chars = line.filter { $0 != " " } guard chars.count >= 3, let first = chars.first, "-*_".contains(first) else { return false } return chars.allSatisfy { $0 == first } } static func setextLevel(_ line: String) -> Int? { guard indent(line) <= 3 else { return nil } let trimmed = line.trimmingCharacters(in: .whitespaces) guard let first = trimmed.first, first == "=" || first == "-", trimmed.allSatisfy({ $0 == first }) else { return nil } return first == "=" ? 1 : 2 } struct ListMarker { var ordered: Bool /// `-`, `+`, `*`, `.` or `)`. var delimiter: Character var start: Int var indent: Int /// Columns from the line's start to the item's content. var contentIndent: Int var empty: Bool } static func listMarker(_ line: String) -> ListMarker? { let indent = indent(line) let rest = Array(line.dropFirst(indent)) guard let first = rest.first else { return nil } var width: Int var marker: ListMarker if "-+*".contains(first) { width = 1 marker = ListMarker(ordered: false, delimiter: first, start: 1, indent: indent, contentIndent: 0, empty: false) } else { let digits = rest.prefix { $0.isASCII && $0.isNumber } guard (1...9).contains(digits.count), digits.count < rest.count else { return nil } let delimiter = rest[digits.count] guard delimiter == "." || delimiter == ")" else { return nil } width = digits.count + 1 marker = ListMarker(ordered: true, delimiter: delimiter, start: Int(String(digits)) ?? 1, indent: indent, contentIndent: 0, empty: false) } let after = rest.dropFirst(width) if after.isEmpty { marker.empty = true marker.contentIndent = indent + width + 1 return marker } guard after.first == " " else { return nil } let spaces = after.prefix { $0 == " " }.count if spaces == after.count { marker.empty = true marker.contentIndent = indent + width + 1 } else { marker.contentIndent = indent + width + (spaces > 4 ? 1 : spaces) } return marker } static func isQuote(_ line: String) -> Bool { indent(line) <= 3 && line.drop { $0 == " " }.first == ">" } static func stripQuote(_ line: String) -> String { var rest = line.drop { $0 == " " }.dropFirst() if rest.first == " " { rest = rest.dropFirst() } return String(rest) } static func tableCells(_ line: String) -> [String] { var text = line.trimmingCharacters(in: .whitespaces) if text.hasPrefix("|") { text.removeFirst() } if text.hasSuffix("|"), !text.hasSuffix("\\|") { text.removeLast() } var cells: [String] = [] var current = "" var inCode = false var escaped = false for char in text { if escaped { if char == "|" { current.append("\u{1}") } else { current.append("\\") current.append(char) } escaped = false continue } switch char { case "\\": escaped = true case "`": inCode.toggle() current.append(char) case "|" where !inCode: cells.append(current.trimmingCharacters(in: .whitespaces)) current = "" default: current.append(char) } } if escaped { current.append("\\") } cells.append(current.trimmingCharacters(in: .whitespaces)) return cells } static func isDelimiterRow(_ line: String) -> Bool { guard line.contains("-") else { return false } let cells = tableCells(line) return !cells.isEmpty && cells.allSatisfy { cell in var body = Substring(cell) if body.hasPrefix(":") { body = body.dropFirst() } if body.hasSuffix(":") { body = body.dropLast() } return !body.isEmpty && body.allSatisfy { $0 == "-" } } } static func tableStarts(_ lines: [String], at i: Int) -> Bool { i + 1 < lines.count && indent(lines[i]) <= 3 && lines[i].contains("|") && isDelimiterRow(lines[i + 1]) && tableCells(lines[i]).count == tableCells(lines[i + 1]).count } static let htmlBlockTags: Set = [ "address", "article", "aside", "blockquote", "center", "details", "dialog", "div", "dl", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hr", "iframe", "li", "main", "nav", "ol", "p", "pre", "section", "summary", "table", "tbody", "td", "th", "thead", "tr", "ul", "video", "audio", "picture", "script", "style", "br", "img" ] static func htmlBlockStart(_ line: String) -> Bool { guard indent(line) <= 3 else { return false } let rest = line.drop { $0 == " " } guard rest.hasPrefix("<") else { return false } if rest.hasPrefix("") { break } } var text = body.joined(separator: "\n").trimmingCharacters(in: .whitespaces) if text.hasSuffix("-->"), text.hasPrefix("