Sources/OrgCore/MarkdownImport/MarkdownBlocks.swift

4d8e517de5aef10e915fb482735feba5435a4a21
orgstar/Sources/OrgCore/MarkdownImport/MarkdownBlocks.swift

573 lines · 25739 bytes

  1import Foundation
  2
  3/// A Markdown document's blocks, as `MarkdownBlocks.parse` reads them: CommonMark's block
  4/// structure plus GFM tables, task items and footnotes, and Obsidian's callouts and `%%`
  5/// comments when `obsidian` is set.
  6indirect enum MarkdownBlock: Equatable, Sendable {
  7    /// An ATX or setext heading; `text` is the raw inline text.
  8    case heading(level: Int, text: String)
  9    /// Raw lines, inline markup unconverted.
 10    case paragraph([String])
 11    /// A fenced block (`lang` from its info string) or an indented one (`fenced` false).
 12    case code(lang: String, lines: [String], fenced: Bool)
 13    /// `$$ … $$` on lines of their own.
 14    case math([String])
 15    /// `%% … %%` (Obsidian) or `<!-- … -->` on lines of their own.
 16    case comment([String])
 17    case html([String])
 18    case quote([MarkdownBlock])
 19    /// `> [!type] title`; `type` lowercased.
 20    case callout(type: String, title: String, blocks: [MarkdownBlock])
 21    case list(ordered: Bool, start: Int, items: [MarkdownItem])
 22    case table(header: [String], rows: [[String]])
 23    case rule
 24}
 25
 26struct MarkdownItem: Equatable, Sendable {
 27    /// The character between a task item's brackets, `nil` for a plain item.
 28    var task: Character?
 29    var blocks: [MarkdownBlock]
 30}
 31
 32/// What a parse found besides blocks: footnote definitions and link reference definitions.
 33struct MarkdownDefinitions {
 34    var footnotes: [(label: String, blocks: [MarkdownBlock])] = []
 35    /// Lowercased, whitespace-collapsed label to destination.
 36    var links: [String: String] = [:]
 37}
 38
 39struct MarkdownBlocks {
 40    let obsidian: Bool
 41    var definitions = MarkdownDefinitions()
 42
 43    init(obsidian: Bool) { self.obsidian = obsidian }
 44
 45    static func parse(_ text: String, obsidian: Bool) -> (blocks: [MarkdownBlock], definitions: MarkdownDefinitions) {
 46        var parser = MarkdownBlocks(obsidian: obsidian)
 47        let lines = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")
 48            .split(separator: "\n", omittingEmptySubsequences: false).map { expandTabs(String($0)) }
 49        let blocks = parser.blocks(lines)
 50        return (blocks, parser.definitions)
 51    }
 52
 53    /// Tabs to spaces at four-column stops, in the leading whitespace only.
 54    static func expandTabs(_ line: String) -> String {
 55        guard line.contains("\t") else { return line }
 56        var out = ""
 57        var column = 0
 58        var leading = true
 59        for char in line {
 60            if leading, char == "\t" {
 61                let width = 4 - column % 4
 62                out += String(repeating: " ", count: width)
 63                column += width
 64            } else {
 65                if char != " " { leading = false }
 66                out.append(char)
 67                column += 1
 68            }
 69        }
 70        return out
 71    }
 72
 73    // MARK: - Line tests
 74
 75    static func indent(_ line: String) -> Int { line.prefix { $0 == " " }.count }
 76    static func isBlank(_ line: String) -> Bool { line.allSatisfy { $0 == " " } }
 77
 78    static func fence(_ line: String) -> (char: Character, count: Int, indent: Int, info: String)? {
 79        let indent = indent(line)
 80        guard indent <= 3 else { return nil }
 81        let rest = line.dropFirst(indent)
 82        guard let char = rest.first, char == "`" || char == "~" else { return nil }
 83        let count = rest.prefix { $0 == char }.count
 84        guard count >= 3 else { return nil }
 85        let info = rest.dropFirst(count).trimmingCharacters(in: .whitespaces)
 86        if char == "`", info.contains("`") { return nil }
 87        return (char, count, indent, info)
 88    }
 89
 90    static func atxHeading(_ line: String) -> (level: Int, text: String)? {
 91        let indent = indent(line)
 92        guard indent <= 3 else { return nil }
 93        let rest = line.dropFirst(indent)
 94        let level = rest.prefix { $0 == "#" }.count
 95        guard (1...6).contains(level) else { return nil }
 96        let after = rest.dropFirst(level)
 97        guard after.isEmpty || after.first == " " else { return nil }
 98        var text = after.trimmingCharacters(in: .whitespaces)
 99        // A closing sequence of #s preceded by a space.
100        if let closing = text.lastIndex(where: { $0 != "#" }) {
101            let tail = text[text.index(after: closing)...]
102            if !tail.isEmpty, text[closing] == " " { text = String(text[...closing]).trimmingCharacters(in: .whitespaces) }
103        } else {
104            text = ""
105        }
106        return (level, text)
107    }
108
109    static func isRule(_ line: String) -> Bool {
110        guard indent(line) <= 3 else { return false }
111        let chars = line.filter { $0 != " " }
112        guard chars.count >= 3, let first = chars.first, "-*_".contains(first) else { return false }
113        return chars.allSatisfy { $0 == first }
114    }
115
116    static func setextLevel(_ line: String) -> Int? {
117        guard indent(line) <= 3 else { return nil }
118        let trimmed = line.trimmingCharacters(in: .whitespaces)
119        guard let first = trimmed.first, first == "=" || first == "-", trimmed.allSatisfy({ $0 == first }) else { return nil }
120        return first == "=" ? 1 : 2
121    }
122
123    struct ListMarker {
124        var ordered: Bool
125        /// `-`, `+`, `*`, `.` or `)`.
126        var delimiter: Character
127        var start: Int
128        var indent: Int
129        /// Columns from the line's start to the item's content.
130        var contentIndent: Int
131        var empty: Bool
132    }
133
134    static func listMarker(_ line: String) -> ListMarker? {
135        let indent = indent(line)
136        let rest = Array(line.dropFirst(indent))
137        guard let first = rest.first else { return nil }
138        var width: Int
139        var marker: ListMarker
140        if "-+*".contains(first) {
141            width = 1
142            marker = ListMarker(ordered: false, delimiter: first, start: 1, indent: indent, contentIndent: 0, empty: false)
143        } else {
144            let digits = rest.prefix { $0.isASCII && $0.isNumber }
145            guard (1...9).contains(digits.count), digits.count < rest.count else { return nil }
146            let delimiter = rest[digits.count]
147            guard delimiter == "." || delimiter == ")" else { return nil }
148            width = digits.count + 1
149            marker = ListMarker(ordered: true, delimiter: delimiter, start: Int(String(digits)) ?? 1, indent: indent, contentIndent: 0, empty: false)
150        }
151        let after = rest.dropFirst(width)
152        if after.isEmpty {
153            marker.empty = true
154            marker.contentIndent = indent + width + 1
155            return marker
156        }
157        guard after.first == " " else { return nil }
158        let spaces = after.prefix { $0 == " " }.count
159        if spaces == after.count {
160            marker.empty = true
161            marker.contentIndent = indent + width + 1
162        } else {
163            marker.contentIndent = indent + width + (spaces > 4 ? 1 : spaces)
164        }
165        return marker
166    }
167
168    static func isQuote(_ line: String) -> Bool {
169        indent(line) <= 3 && line.drop { $0 == " " }.first == ">"
170    }
171
172    static func stripQuote(_ line: String) -> String {
173        var rest = line.drop { $0 == " " }.dropFirst()
174        if rest.first == " " { rest = rest.dropFirst() }
175        return String(rest)
176    }
177
178    static func tableCells(_ line: String) -> [String] {
179        var text = line.trimmingCharacters(in: .whitespaces)
180        if text.hasPrefix("|") { text.removeFirst() }
181        if text.hasSuffix("|"), !text.hasSuffix("\\|") { text.removeLast() }
182        var cells: [String] = []
183        var current = ""
184        var inCode = false
185        var escaped = false
186        for char in text {
187            if escaped {
188                if char == "|" {
189                    current.append("\u{1}")
190                } else {
191                    current.append("\\")
192                    current.append(char)
193                }
194                escaped = false
195                continue
196            }
197            switch char {
198            case "\\": escaped = true
199            case "`":
200                inCode.toggle()
201                current.append(char)
202            case "|" where !inCode:
203                cells.append(current.trimmingCharacters(in: .whitespaces))
204                current = ""
205            default: current.append(char)
206            }
207        }
208        if escaped { current.append("\\") }
209        cells.append(current.trimmingCharacters(in: .whitespaces))
210        return cells
211    }
212
213    static func isDelimiterRow(_ line: String) -> Bool {
214        guard line.contains("-") else { return false }
215        let cells = tableCells(line)
216        return !cells.isEmpty && cells.allSatisfy { cell in
217            var body = Substring(cell)
218            if body.hasPrefix(":") { body = body.dropFirst() }
219            if body.hasSuffix(":") { body = body.dropLast() }
220            return !body.isEmpty && body.allSatisfy { $0 == "-" }
221        }
222    }
223
224    static func tableStarts(_ lines: [String], at i: Int) -> Bool {
225        i + 1 < lines.count && indent(lines[i]) <= 3 && lines[i].contains("|") && isDelimiterRow(lines[i + 1])
226            && tableCells(lines[i]).count == tableCells(lines[i + 1]).count
227    }
228
229    static let htmlBlockTags: Set<String> = [
230        "address", "article", "aside", "blockquote", "center", "details", "dialog", "div", "dl", "fieldset", "figcaption", "figure",
231        "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hr", "iframe", "li", "main", "nav", "ol", "p", "pre",
232        "section", "summary", "table", "tbody", "td", "th", "thead", "tr", "ul", "video", "audio", "picture", "script", "style", "br", "img"
233    ]
234
235    static func htmlBlockStart(_ line: String) -> Bool {
236        guard indent(line) <= 3 else { return false }
237        let rest = line.drop { $0 == " " }
238        guard rest.hasPrefix("<") else { return false }
239        if rest.hasPrefix("<!--") { return true }
240        let name = rest.dropFirst().drop { $0 == "/" }.prefix { $0.isLetter || $0.isNumber || $0 == "-" }.lowercased()
241        guard !name.isEmpty else { return false }
242        if htmlBlockTags.contains(name) { return true }
243        // Any other tag alone on its line.
244        let trimmed = rest.trimmingCharacters(in: .whitespaces)
245        return trimmed.hasSuffix(">") && !trimmed.dropFirst().contains("<")
246    }
247
248    static func footnoteDefinition(_ line: String) -> (label: String, rest: String)? {
249        guard indent(line) <= 3 else { return nil }
250        let rest = line.drop { $0 == " " }
251        guard rest.hasPrefix("[^"), let close = rest.firstIndex(of: "]") else { return nil }
252        let label = rest[rest.index(rest.startIndex, offsetBy: 2)..<close]
253        let after = rest[rest.index(after: close)...]
254        guard !label.isEmpty, !label.contains(" "), after.hasPrefix(":") else { return nil }
255        return (String(label), after.dropFirst().trimmingCharacters(in: .whitespaces))
256    }
257
258    static func linkDefinition(_ line: String) -> (label: String, destination: String)? {
259        guard indent(line) <= 3 else { return nil }
260        let rest = line.drop { $0 == " " }
261        guard rest.hasPrefix("["), !rest.hasPrefix("[^"), let close = rest.firstIndex(of: "]") else { return nil }
262        let label = rest[rest.index(after: rest.startIndex)..<close]
263        let after = rest[rest.index(after: close)...]
264        guard !label.trimmingCharacters(in: .whitespaces).isEmpty, after.hasPrefix(":") else { return nil }
265        let body = after.dropFirst().trimmingCharacters(in: .whitespaces)
266        guard !body.isEmpty else { return nil }
267        var destination: String
268        var remainder: Substring
269        if body.hasPrefix("<"), let end = body.firstIndex(of: ">") {
270            destination = String(body[body.index(after: body.startIndex)..<end])
271            remainder = body[body.index(after: end)...]
272        } else {
273            destination = String(body.prefix { $0 != " " })
274            remainder = body.dropFirst(destination.count)
275        }
276        let title = remainder.trimmingCharacters(in: .whitespaces)
277        guard title.isEmpty || title.first == "\"" || title.first == "'" || title.first == "(" else { return nil }
278        if destination.isEmpty { destination = "" }
279        return (normalizeLabel(String(label)), destination)
280    }
281
282    static func normalizeLabel(_ label: String) -> String {
283        label.lowercased().split(whereSeparator: { $0 == " " || $0 == "\n" }).joined(separator: " ")
284    }
285
286    /// Whether `line` starts a block that ends a paragraph above it.
287    func interruptsParagraph(_ lines: [String], at i: Int) -> Bool {
288        let line = lines[i]
289        if Self.atxHeading(line) != nil || Self.fence(line) != nil || Self.isQuote(line) || Self.isRule(line) || Self.htmlBlockStart(line) {
290            return true
291        }
292        if let marker = Self.listMarker(line), !marker.empty, marker.indent <= 3, !marker.ordered || marker.start == 1 { return true }
293        if Self.tableStarts(lines, at: i) { return true }
294        if line.trimmingCharacters(in: .whitespaces).hasPrefix("$$") { return true }
295        return false
296    }
297
298    // MARK: - Blocks
299
300    mutating func blocks(_ lines: [String]) -> [MarkdownBlock] {
301        var out: [MarkdownBlock] = []
302        var i = 0
303        while i < lines.count {
304            let line = lines[i]
305            if Self.isBlank(line) {
306                i += 1
307                continue
308            }
309            if let fence = Self.fence(line) {
310                var body: [String] = []
311                i += 1
312                while i < lines.count {
313                    if let close = Self.fence(lines[i]), close.char == fence.char, close.count >= fence.count, close.info.isEmpty { break }
314                    let content = lines[i]
315                    body.append(String(content.dropFirst(min(fence.indent, Self.indent(content)))))
316                    i += 1
317                }
318                i += 1
319                let lang = fence.info.split(separator: " ").first.map { String($0).trimmingCharacters(in: CharacterSet(charactersIn: "{}.")) } ?? ""
320                out.append(.code(lang: lang, lines: body, fenced: true))
321                continue
322            }
323            let trimmed = line.trimmingCharacters(in: .whitespaces)
324            if trimmed.hasPrefix("$$") {
325                var body: [String] = []
326                var first = String(trimmed.dropFirst(2))
327                if first.hasSuffix("$$"), first.count >= 2 {
328                    first.removeLast(2)
329                    out.append(.math([first.trimmingCharacters(in: .whitespaces)].filter { !$0.isEmpty }))
330                    i += 1
331                    continue
332                }
333                if !first.trimmingCharacters(in: .whitespaces).isEmpty { body.append(first) }
334                i += 1
335                while i < lines.count {
336                    let current = lines[i].trimmingCharacters(in: .whitespaces)
337                    if current.hasSuffix("$$") {
338                        let last = String(current.dropLast(2))
339                        if !last.trimmingCharacters(in: .whitespaces).isEmpty { body.append(last) }
340                        break
341                    }
342                    body.append(lines[i])
343                    i += 1
344                }
345                i += 1
346                out.append(.math(body))
347                continue
348            }
349            if obsidian, trimmed.hasPrefix("%%") {
350                var body: [String] = []
351                var first = String(trimmed.dropFirst(2))
352                if first.hasSuffix("%%") {
353                    first.removeLast(2)
354                    out.append(.comment([first.trimmingCharacters(in: .whitespaces)]))
355                    i += 1
356                    continue
357                }
358                if !first.isEmpty { body.append(first) }
359                i += 1
360                while i < lines.count {
361                    let current = lines[i].trimmingCharacters(in: .whitespaces)
362                    if current.hasSuffix("%%") {
363                        let last = String(current.dropLast(2))
364                        if !last.isEmpty { body.append(last) }
365                        break
366                    }
367                    body.append(lines[i])
368                    i += 1
369                }
370                i += 1
371                out.append(.comment(body))
372                continue
373            }
374            if trimmed.hasPrefix("<!--") {
375                var body: [String] = []
376                while i < lines.count {
377                    body.append(lines[i])
378                    i += 1
379                    if body.last!.contains("-->") { break }
380                }
381                var text = body.joined(separator: "\n").trimmingCharacters(in: .whitespaces)
382                if text.hasSuffix("-->"), text.hasPrefix("<!--") {
383                    text = String(text.dropFirst(4).dropLast(3))
384                    out.append(.comment(text.split(separator: "\n", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) }
385                        .drop { $0.isEmpty }.reversed().drop { $0.isEmpty }.reversed()))
386                } else {
387                    out.append(.html(body))
388                }
389                continue
390            }
391            if let heading = Self.atxHeading(line) {
392                out.append(.heading(level: heading.level, text: heading.text))
393                i += 1
394                continue
395            }
396            if Self.isRule(line) {
397                out.append(.rule)
398                i += 1
399                continue
400            }
401            if Self.isQuote(line) {
402                var inner: [String] = []
403                while i < lines.count {
404                    let current = lines[i]
405                    if Self.isQuote(current) {
406                        inner.append(Self.stripQuote(current))
407                    } else if !Self.isBlank(current), let last = inner.last, !Self.isBlank(last), !interruptsParagraph(lines, at: i) {
408                        inner.append(current)
409                    } else {
410                        break
411                    }
412                    i += 1
413                }
414                out.append(quote(inner))
415                continue
416            }
417            if let marker = Self.listMarker(line), marker.indent <= 3 {
418                out.append(list(lines, at: &i, first: marker))
419                continue
420            }
421            if Self.htmlBlockStart(line) {
422                var body: [String] = []
423                while i < lines.count, !Self.isBlank(lines[i]) {
424                    body.append(lines[i])
425                    i += 1
426                }
427                out.append(.html(body))
428                continue
429            }
430            if Self.indent(line) >= 4 {
431                var body: [String] = []
432                while i < lines.count, Self.isBlank(lines[i]) || Self.indent(lines[i]) >= 4 {
433                    body.append(String(lines[i].dropFirst(min(4, Self.indent(lines[i])))))
434                    i += 1
435                }
436                while body.last.map(Self.isBlank) == true { body.removeLast() }
437                out.append(.code(lang: "", lines: body, fenced: false))
438                continue
439            }
440            if let footnote = Self.footnoteDefinition(line) {
441                var inner = [footnote.rest]
442                i += 1
443                while i < lines.count {
444                    let current = lines[i]
445                    if Self.isBlank(current) {
446                        if i + 1 < lines.count, Self.indent(lines[i + 1]) >= 4 {
447                            inner.append("")
448                            i += 1
449                            continue
450                        }
451                        break
452                    }
453                    if Self.indent(current) >= 4 {
454                        inner.append(String(current.dropFirst(4)))
455                    } else if Self.footnoteDefinition(current) == nil, !interruptsParagraph(lines, at: i) {
456                        inner.append(current)
457                    } else {
458                        break
459                    }
460                    i += 1
461                }
462                definitions.footnotes.append((footnote.label, blocks(inner)))
463                continue
464            }
465            if Self.tableStarts(lines, at: i) {
466                let header = Self.tableCells(line)
467                var rows: [[String]] = []
468                i += 2
469                while i < lines.count, !Self.isBlank(lines[i]), lines[i].contains("|") || !interruptsParagraph(lines, at: i) {
470                    if interruptsParagraph(lines, at: i), !lines[i].contains("|") { break }
471                    var cells = Self.tableCells(lines[i])
472                    if cells.count < header.count { cells += Array(repeating: "", count: header.count - cells.count) }
473                    rows.append(Array(cells.prefix(header.count)))
474                    i += 1
475                }
476                out.append(.table(header: header, rows: rows))
477                continue
478            }
479            // A paragraph, after any link reference definitions at its start.
480            var paragraph: [String] = []
481            while i < lines.count, !Self.isBlank(lines[i]) {
482                if paragraph.isEmpty, let definition = Self.linkDefinition(lines[i]) {
483                    if definitions.links[definition.label] == nil { definitions.links[definition.label] = definition.destination }
484                    i += 1
485                    continue
486                }
487                if !paragraph.isEmpty {
488                    if let level = Self.setextLevel(lines[i]) {
489                        out.append(.heading(level: level, text: paragraph.map { $0.trimmingCharacters(in: .whitespaces) }.joined(separator: " ")))
490                        paragraph = []
491                        i += 1
492                        break
493                    }
494                    if interruptsParagraph(lines, at: i) { break }
495                } else if Self.footnoteDefinition(lines[i]) != nil {
496                    break
497                }
498                paragraph.append(String(lines[i].drop { $0 == " " }))
499                i += 1
500            }
501            if !paragraph.isEmpty { out.append(.paragraph(paragraph)) }
502        }
503        return out
504    }
505
506    private mutating func quote(_ inner: [String]) -> MarkdownBlock {
507        if obsidian, let first = inner.first?.trimmingCharacters(in: .whitespaces), first.hasPrefix("[!"), let close = first.firstIndex(of: "]") {
508            let type = first[first.index(first.startIndex, offsetBy: 2)..<close]
509            if !type.isEmpty, type.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "-" || $0 == "_" }) {
510                var title = first[first.index(after: close)...]
511                if title.first == "+" || title.first == "-" { title = title.dropFirst() }
512                return .callout(type: type.lowercased(), title: title.trimmingCharacters(in: .whitespaces), blocks: blocks(Array(inner.dropFirst())))
513            }
514        }
515        return .quote(blocks(inner))
516    }
517
518    /// A list starting at `i` with `first`'s marker; its items continue while lines are
519    /// indented to an item's content, or start another item with the same kind of marker.
520    private mutating func list(_ lines: [String], at i: inout Int, first: ListMarker) -> MarkdownBlock {
521        var items: [MarkdownItem] = []
522        var marker = first
523        while true {
524            let line = lines[i]
525            var content: [String] = [marker.empty ? "" : String(line.dropFirst(marker.contentIndent))]
526            i += 1
527            while i < lines.count {
528                let current = lines[i]
529                if Self.isBlank(current) {
530                    // A blank line continues the item when an indented line follows.
531                    var j = i
532                    while j < lines.count, Self.isBlank(lines[j]) { j += 1 }
533                    if j < lines.count, Self.indent(lines[j]) >= marker.contentIndent {
534                        content += Array(repeating: "", count: j - i)
535                        i = j
536                        continue
537                    }
538                    break
539                }
540                if Self.indent(current) >= marker.contentIndent {
541                    content.append(String(current.dropFirst(marker.contentIndent)))
542                    i += 1
543                    continue
544                }
545                if Self.listMarker(current) != nil || interruptsParagraph(lines, at: i) { break }
546                // A lazy continuation line of the item's paragraph.
547                if let last = content.last, !Self.isBlank(last), Self.fence(content.first ?? "") == nil {
548                    content.append(String(current.drop { $0 == " " }))
549                    i += 1
550                    continue
551                }
552                break
553            }
554            var task: Character?
555            if let head = content.first {
556                let chars = Array(head)
557                if chars.count >= 3, chars[0] == "[", chars[2] == "]", chars.count == 3 || chars[3] == " " {
558                    task = chars[1]
559                    content[0] = String(head.dropFirst(min(4, chars.count)))
560                }
561            }
562            items.append(MarkdownItem(task: task, blocks: blocks(content)))
563            // A blank line between items is allowed.
564            var j = i
565            while j < lines.count, Self.isBlank(lines[j]) { j += 1 }
566            guard j < lines.count, let next = Self.listMarker(lines[j]), next.ordered == first.ordered, next.delimiter == first.delimiter,
567                  next.indent <= 3, next.indent < first.contentIndent else { break }
568            i = j
569            marker = next
570        }
571        return .list(ordered: first.ordered, start: first.start, items: items)
572    }
573}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form