Sources/OrgCore/Parser/Parser.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgCore/Parser/Parser.swift history · blame · raw

588 lines · 23474 bytes

36 symbols in this file
  1public enum OrgParser {
  2    public static func parse(_ text: String, defaults: OrgSettings = .default) -> OrgTree {
  3        var parser = Parser(text: text, defaults: defaults)
  4        let tree = parser.run()
  5        return OrgTree(green: tree.green, settings: tree.settings, text: text)
  6    }
  7}
  8
  9struct Parser {
 10    let lines: [RawLine]
 11    let info: [ClassifiedLine]
 12    /// Begin line → end line, for blocks, dynamic blocks and drawers that are closed before the
 13    /// next heading.
 14    let blockEnds: [Int: Int]
 15    let settings: OrgSettings
 16    var builder = GreenBuilder()
 17    var i = 0
 18    /// Table rows from a previous version, by their line text. A row parses from its own line
 19    /// alone, so a row with the same text can be reused instead of scanned again.
 20    var reusableRows: [Substring: GreenNode] = [:]
 21
 22    init(text: String, defaults: OrgSettings) {
 23        let lines = splitRawLines(text)
 24        let info = lines.map { classifyLine($0.content, alphabetical: defaults.listAllowAlphabetical) }
 25        let ends = Parser.matchEnds(info, lines)
 26        let settings = SettingsScanner.scan(lines: lines, info: info, blockEnds: ends, defaults: defaults)
 27        self.init(lines: lines, info: info, blockEnds: ends, settings: settings)
 28    }
 29
 30    /// Parses part of a document with the settings already read from the whole file.
 31    init(text: String, settings: OrgSettings) {
 32        let lines = splitRawLines(text)
 33        let info = lines.map { classifyLine($0.content, alphabetical: settings.listAllowAlphabetical) }
 34        self.init(lines: lines, info: info, blockEnds: Parser.matchEnds(info, lines), settings: settings)
 35    }
 36
 37    private init(lines: [RawLine], info: [ClassifiedLine], blockEnds: [Int: Int], settings: OrgSettings) {
 38        self.lines = lines
 39        self.info = info
 40        self.blockEnds = blockEnds
 41        self.settings = settings
 42    }
 43
 44    static func matchEnds(_ info: [ClassifiedLine], _ lines: [RawLine]) -> [Int: Int] {
 45        var ends: [Int: Int] = [:]
 46        var k = 0
 47        while k < info.count {
 48            let isEnd: ((LineClass) -> Bool)?
 49            switch info[k].cls {
 50            case .blockBegin(let name): isEnd = { $0 == .blockEnd(name: name) }
 51            case .latexBegin(let name):
 52                // `\end{NAME}` ending a line, the first line's own included.
 53                let closer = "\\end{" + name + "}"
 54                var j = k
 55                while j < info.count {
 56                    if j > k, case .heading = info[j].cls { break }
 57                    let content = lines[j].content.trimmingTrailingWhitespace
 58                    if content.hasSuffix(closer), j > k || content.count > closer.count + 7 + name.count { ends[k] = j; break }
 59                    j += 1
 60                }
 61                k += 1
 62                continue
 63            case .dynamicBegin: isEnd = { $0 == .dynamicEnd }
 64            case .drawerBegin: isEnd = { $0 == .drawerEnd }
 65            default: isEnd = nil
 66            }
 67            if let isEnd {
 68                var j = k + 1
 69                while j < info.count {
 70                    if case .heading = info[j].cls { break }
 71                    if isEnd(info[j].cls) { ends[k] = j; break }
 72                    j += 1
 73                }
 74                // Block contents are verbatim, so nothing inside starts another element.
 75                if let end = ends[k], !isDrawer(info[k].cls) { k = end }
 76            }
 77            k += 1
 78        }
 79        return ends
 80    }
 81
 82    static func isDrawer(_ cls: LineClass) -> Bool {
 83        if case .drawerBegin = cls { return true }
 84        return false
 85    }
 86
 87    mutating func run() -> OrgTree {
 88        builder.start(.document)
 89        if !lines.isEmpty, !isHeading(0) {
 90            builder.start(.zerothSection)
 91            // A property drawer first in the file, after comments and blank lines, holds the
 92            // file's properties.
 93            while i < lines.count, info[i].cls == .blank || info[i].cls == .comment {
 94                if info[i].cls == .blank { line(i); i += 1 } else { consecutive(.comment, limit: lines.count, floor: nil) { $0 == .comment } }
 95            }
 96            if i < lines.count, case .drawerBegin(let name) = info[i].cls, name.uppercased() == "PROPERTIES", let end = blockEnds[i] {
 97                propertyDrawer(end: end)
 98            }
 99            parseContent(limit: lines.count)
100            builder.finish()
101        }
102        while i < lines.count, case .heading(let level) = info[i].cls {
103            parseSection(level: level)
104        }
105        builder.finish()
106        return OrgTree(green: builder.build(), settings: settings)
107    }
108
109    func isHeading(_ k: Int) -> Bool {
110        if case .heading = info[k].cls { return true }
111        return false
112    }
113
114    mutating func parseSection(level: Int) {
115        builder.start(.section)
116        headingLine(lines[i])
117        i += 1
118        if i < lines.count, info[i].cls == .planning {
119            single(.planning)
120        }
121        if i < lines.count, case .drawerBegin(let name) = info[i].cls, name.uppercased() == "PROPERTIES",
122           let end = blockEnds[i] {
123            propertyDrawer(end: end)
124        }
125        parseContent(limit: lines.count)
126        while i < lines.count, case .heading(let child) = info[i].cls, child > level {
127            parseSection(level: child)
128        }
129        builder.finish()
130    }
131
132    mutating func propertyDrawer(end: Int) {
133        builder.start(.propertyDrawer)
134        line(i)
135        i += 1
136        while i < end {
137            if info[i].cls == .blank {
138                line(i)
139            } else {
140                builder.start(.nodeProperty)
141                line(i)
142                builder.finish()
143            }
144            i += 1
145        }
146        line(i)
147        i += 1
148        builder.finish()
149    }
150
151    /// Elements until `limit` or the next heading.
152    mutating func parseContent(limit: Int) {
153        while i < limit, !isHeading(i) {
154            element(limit: limit, floor: nil)
155        }
156    }
157
158    static let affiliatedKeys: Set<String> = ["NAME", "CAPTION", "RESULTS", "HEADER", "PLOT"]
159
160    /// One element starting at `i`. `floor` is the indent of the enclosing list item, if any:
161    /// non-blank lines at or left of it end the element.
162    mutating func element(limit: Int, floor: Int?) {
163        switch info[i].cls {
164        case .blank:
165            line(i)
166            i += 1
167        case .blockBegin, .dynamicBegin, .latexBegin:
168            if let end = blockEnds[i], end < limit {
169                let kind: SyntaxKind = switch info[i].cls {
170                case .dynamicBegin: .dynamicBlock
171                case .latexBegin: .latexEnvironment
172                default: .block
173                }
174                builder.start(kind)
175                while i <= end {
176                    line(i)
177                    i += 1
178                }
179                builder.finish()
180            } else {
181                paragraph(limit: limit, floor: floor)
182            }
183        case .drawerBegin:
184            if let end = blockEnds[i], end < limit {
185                builder.start(.drawer)
186                line(i)
187                i += 1
188                parseContent(limit: end)
189                line(i)
190                i += 1
191                builder.finish()
192            } else {
193                paragraph(limit: limit, floor: floor)
194            }
195        case .inlineTask:
196            inlineTask(limit: limit)
197        case .keyword(let key):
198            let affiliated = Self.affiliatedKeys.contains(key) || key.hasPrefix("ATTR_")
199            single(affiliated ? .affiliatedKeyword : .keyword)
200        case .comment:
201            consecutive(.comment, limit: limit, floor: floor) { $0 == .comment }
202        case .fixedWidth:
203            consecutive(.fixedWidth, limit: limit, floor: floor) { $0 == .fixedWidth }
204        case .horizontalRule:
205            single(.horizontalRule)
206        case .clock:
207            single(.clock)
208        case .tableRow:
209            table(limit: limit, floor: floor)
210        case .tableElRule:
211            if let end = tableElEnd(limit: limit, floor: floor) {
212                builder.start(.tableEl)
213                while i < end {
214                    line(i)
215                    i += 1
216                }
217                while i < limit, info[i].cls == .keyword(key: "TBLFM"), within(floor, i) {
218                    single(.tableFormula)
219                }
220                builder.finish()
221            } else {
222                paragraph(limit: limit, floor: floor)
223            }
224        case .diarySexp:
225            single(.diarySexp)
226        case .footnoteDefinition:
227            footnoteDefinition(limit: limit)
228        case .listItem:
229            list(limit: limit, floor: floor)
230        default:
231            paragraph(limit: limit, floor: floor)
232        }
233    }
234
235    /// An inline task: its heading line, and with an END line before the next heading, the
236    /// elements up to it and that line.
237    mutating func inlineTask(limit: Int) {
238        builder.start(.inlineTask)
239        headingLine(lines[i])
240        i += 1
241        var end: Int?
242        var k = i
243        while k < limit, !isHeading(k) {
244            if info[k].cls == .inlineTaskEnd { end = k; break }
245            if case .inlineTask = info[k].cls { break }
246            k += 1
247        }
248        if let end {
249            if i < end, info[i].cls == .planning { single(.planning) }
250            if i < end, case .drawerBegin(let name) = info[i].cls, name.uppercased() == "PROPERTIES", let drawerEnd = blockEnds[i], drawerEnd < end {
251                propertyDrawer(end: drawerEnd)
252            }
253            parseContent(limit: end)
254            headingLine(lines[i])
255            i += 1
256        }
257        builder.finish()
258    }
259
260    /// Kinds whose single line holds inline objects (timestamps on planning and clock lines).
261    static let inlineLineKinds: Set<SyntaxKind> = [.planning, .clock]
262
263    mutating func single(_ kind: SyntaxKind) {
264        builder.start(kind)
265        if Self.inlineLineKinds.contains(kind) {
266            let rest = whitespace(lines[i].content)
267            inline(rest)
268            builder.token(.newline, lines[i].ending)
269        } else {
270            line(i)
271        }
272        i += 1
273        builder.finish()
274    }
275
276    /// Source text from `start` through the end of line `last`, including its line ending.
277    func span(from start: Substring.Index, through last: Int) -> Substring {
278        let base = lines[last].ending.base
279        return base[start..<lines[last].ending.endIndex]
280    }
281
282    mutating func consecutive(_ kind: SyntaxKind, limit: Int, floor: Int?, matching: (LineClass) -> Bool) {
283        builder.start(kind)
284        repeat {
285            line(i)
286            i += 1
287        } while i < limit && matching(info[i].cls) && within(floor, i)
288        builder.finish()
289    }
290
291    mutating func table(limit: Int, floor: Int?) {
292        builder.start(.table)
293        while i < limit, info[i].cls == .tableRow, within(floor, i) {
294            tableRow()
295        }
296        while i < limit, info[i].cls == .keyword(key: "TBLFM"), within(floor, i) {
297            single(.tableFormula)
298        }
299        builder.finish()
300    }
301
302    /// Where the table.el table starting at line `i` ends, as `org-element--current-element`
303    /// decides: a full rule first and last, at least two lines, every line starting with `+`
304    /// or `|`. Nil for none.
305    func tableElEnd(limit: Int, floor: Int?) -> Int? {
306        guard i + 1 < limit else { return nil }
307        func isTableLine(_ k: Int) -> Bool {
308            guard within(floor, k) else { return false }
309            let first = lines[k].content.drop { $0 == " " || $0 == "\t" }.first
310            return first == "+" || first == "|"
311        }
312        var k = i + 1
313        while k < limit, isTableLine(k) { k += 1 }
314        if k == i + 1 { return nil }
315        return info[k - 1].cls == .tableElRule ? k : nil
316    }
317
318    /// A rule row (`|---+---|`) is one text token. Other rows alternate `|` markers and cells;
319    /// every pair of pipes gets a cell, even an empty one, so columns line up.
320    mutating func tableRow() {
321        if !reusableRows.isEmpty {
322            let content = lines[i].content
323            if let row = reusableRows[content.base[content.startIndex..<lines[i].ending.endIndex]] {
324                builder.node(row)
325                i += 1
326                return
327            }
328        }
329        builder.start(.tableRow)
330        let rest = whitespace(lines[i].content)
331        if rest.hasPrefix("|-") {
332            builder.token(.text, rest)
333        } else {
334            // Pipes are found by byte; one counts only where the Character there is a lone `|`,
335            // as a walk by Character would find it.
336            var cellStart = rest.startIndex
337            let bytes = rest.utf8
338            var index = bytes.startIndex
339            while index < bytes.endIndex {
340                if bytes[index] == UInt8(ascii: "|"), rest[index] == "|" {
341                    if index > rest.startIndex { tableCell(rest[cellStart..<index]) }
342                    builder.token(.marker, "|")
343                    cellStart = bytes.index(after: index)
344                }
345                index = bytes.index(after: index)
346            }
347            if cellStart < rest.endIndex { tableCell(rest[cellStart...]) }
348        }
349        builder.token(.newline, lines[i].ending)
350        builder.finish()
351        i += 1
352    }
353
354    mutating func tableCell(_ text: Substring) {
355        builder.start(.tableCell)
356        inline(text)
357        builder.finish()
358    }
359
360    mutating func footnoteDefinition(limit: Int) {
361        var end = i + 1
362        while end < limit, info[end].cls == .plain { end += 1 }
363        let content = lines[i].content
364        let close = content.firstIndex(of: "]")!
365        builder.start(.footnoteDefinition)
366        builder.token(.marker, content[...close])
367        inline(span(from: content.index(after: close), through: end - 1))
368        builder.finish()
369        i = end
370    }
371
372    mutating func list(limit: Int, floor: Int?) {
373        let base = info[i].indent
374        builder.start(.plainList)
375        while i < limit, info[i].cls == .listItem, info[i].indent == base, within(floor, i) {
376            item(base: base, limit: limit)
377        }
378        builder.finish()
379    }
380
381    /// An item's first line, then everything indented past its bullet. One blank line stays
382    /// inside the item when the item or list continues after it; two end the list.
383    mutating func item(base: Int, limit: Int) {
384        builder.start(.item)
385        var rest = whitespace(lines[i].content)
386        let bullet = rest.prefix { $0 != " " && $0 != "\t" }
387        builder.token(.bullet, bullet)
388        rest = whitespace(rest.dropFirst(bullet.count))
389        if let counter = Self.counter(rest) {
390            builder.token(.counter, counter)
391            rest = whitespace(rest[counter.endIndex...])
392        }
393        if let box = checkbox(rest) {
394            builder.token(.checkbox, box)
395            rest = whitespace(rest.dropFirst(box.count))
396        }
397        // A description item's tag: up to the last ` ::` on the line, for `-`, `+` and `*`.
398        if "-+*".contains(bullet), let (tag, separator) = Self.descriptionTag(rest) {
399            builder.start(.itemTag)
400            inline(tag)
401            builder.finish()
402            let blank = separator.prefix { $0 == " " || $0 == "\t" }
403            builder.token(.whitespace, blank)
404            builder.token(.marker, separator.dropFirst(blank.count))
405            rest = whitespace(rest[separator.endIndex...])
406        }
407        // The rest of the bullet line and its continuation lines are the item's first paragraph.
408        var end = i + 1
409        while end < limit, within(base, end), continuesParagraph(end) { end += 1 }
410        if rest.isEmpty, end == i + 1 {
411            builder.token(.newline, lines[i].ending)
412        } else {
413            builder.start(.paragraph)
414            inline(span(from: rest.startIndex, through: end - 1))
415            builder.finish()
416        }
417        i = end
418        while i < limit, !isHeading(i) {
419            if info[i].cls == .blank {
420                var j = i
421                while j < limit, info[j].cls == .blank { j += 1 }
422                guard j - i < 2, j < limit else { break }
423                let continuesItem = info[j].indent > base
424                let nextSibling = info[j].cls == .listItem && info[j].indent == base
425                guard continuesItem || nextSibling else { break }
426                line(i)
427                i += 1
428                if nextSibling { break }
429                continue
430            }
431            guard info[i].indent > base else { break }
432            element(limit: limit, floor: base)
433        }
434        builder.finish()
435    }
436
437    /// `[ ]`, `[X]`, `[x]` or `[-]`, followed by whitespace or end of line.
438    /// A counter cookie at the start of `s`: `[@3]`, `[@start:3]`, `[@b]`.
439    static func counter(_ s: Substring) -> Substring? {
440        guard s.hasPrefix("[@") else { return nil }
441        func value(from start: Substring.Index) -> Substring.Index? {
442            var j = start
443            while j < s.endIndex, s[j].isASCII, s[j].isNumber { j = s.index(after: j) }
444            if j == start {
445                guard j < s.endIndex, s[j].isASCII, s[j].isLetter else { return nil }
446                j = s.index(after: j)
447            }
448            return j < s.endIndex && s[j] == "]" ? s.index(after: j) : nil
449        }
450        let afterAt = s.index(s.startIndex, offsetBy: 2)
451        if s[afterAt...].hasPrefix("start:"), let end = value(from: s.index(afterAt, offsetBy: 6)) { return s[..<end] }
452        return value(from: afterAt).map { s[..<$0] }
453    }
454
455    /// A description item's tag and separator: the text before the last ` ::` on the line
456    /// that ends it or has blanks after it, and that blank with the `::`.
457    static func descriptionTag(_ s: Substring) -> (tag: Substring, separator: Substring)? {
458        guard containsBytes(s.utf8, UInt8(ascii: ":"), count: 2) else { return nil }
459        let line = s.prefix { $0 != "\n" && $0 != "\r" }
460        var k = line.endIndex
461        while k > line.startIndex {
462            k = line.index(before: k)
463            guard line[k] == ":", k > line.startIndex else { continue }
464            let colon = line.index(before: k)
465            guard line[colon] == ":", colon > line.startIndex else { continue }
466            let blank = line.index(before: colon)
467            guard line[blank] == " " || line[blank] == "\t" else { continue }
468            let after = line.index(after: k)
469            guard after == line.endIndex || line[after] == " " || line[after] == "\t" else { continue }
470            return (line[..<blank], line[blank...k])
471        }
472        return nil
473    }
474
475    func checkbox(_ s: Substring) -> Substring? {
476        guard s.count >= 3, s.first == "[", "Xx -".contains(s.dropFirst().first!),
477              s.dropFirst(2).first == "]" else { return nil }
478        let after = s.dropFirst(3)
479        guard after.isEmpty || after.first == " " || after.first == "\t" else { return nil }
480        return s.prefix(3)
481    }
482
483    /// The paragraph's lines are one inline run, so emphasis and links can cross a line break.
484    mutating func paragraph(limit: Int, floor: Int?) {
485        var end = i + 1
486        while end < limit, within(floor, end), continuesParagraph(end) { end += 1 }
487        builder.start(.paragraph)
488        inline(span(from: lines[i].content.startIndex, through: end - 1))
489        builder.finish()
490        i = end
491    }
492
493    /// Lines that don't start an element of their own.
494    func continuesParagraph(_ k: Int) -> Bool {
495        switch info[k].cls {
496        case .plain, .planning, .blockEnd, .dynamicEnd, .drawerEnd, .latexEnd:
497            return true
498        case .blockBegin, .dynamicBegin, .drawerBegin, .latexBegin:
499            return blockEnds[k] == nil
500        default:
501            return false
502        }
503    }
504
505    func within(_ floor: Int?, _ k: Int) -> Bool {
506        guard let floor else { return true }
507        return info[k].indent > floor
508    }
509
510    // MARK: - Tokens
511
512    /// A whole line as leading whitespace, content and line ending.
513    mutating func line(_ k: Int) {
514        let rest = whitespace(lines[k].content)
515        builder.token(.text, rest)
516        builder.token(.newline, lines[k].ending)
517    }
518
519    mutating func whitespace(_ s: Substring) -> Substring {
520        let ws = s.prefix { $0 == " " || $0 == "\t" }
521        builder.token(.whitespace, ws)
522        return s.dropFirst(ws.count)
523    }
524
525    mutating func headingLine(_ raw: RawLine) {
526        builder.start(.heading)
527        var rest = raw.content
528        let stars = rest.prefix { $0 == "*" }
529        builder.token(.stars, stars)
530        rest = whitespace(rest.dropFirst(stars.count))
531
532        // As org: a keyword counts only before a space or the end of the line, not a tab.
533        let word = rest.prefix { $0 != " " && $0 != "\t" }
534        let afterWord = rest.dropFirst(word.count).first
535        if !word.isEmpty, afterWord == nil || afterWord == " ", settings.todoKeywordNames.contains(String(word)) {
536            builder.token(.todoKeyword, word)
537            rest = whitespace(rest.dropFirst(word.count))
538        }
539
540        if let cookie = priorityCookie(rest) {
541            builder.token(.priority, cookie)
542            rest = whitespace(rest.dropFirst(cookie.count))
543        }
544
545        let parts = splitTags(rest)
546        if !parts.title.isEmpty {
547            builder.start(.title)
548            inline(parts.title)
549            builder.finish()
550        }
551        builder.token(.whitespace, parts.gap)
552        builder.token(.tags, parts.tags)
553        builder.token(.whitespace, parts.trailing)
554        builder.token(.newline, raw.ending)
555        builder.finish()
556    }
557
558    /// `[#A]` or `[#10]`, followed by whitespace or end of line.
559    func priorityCookie(_ s: Substring) -> Substring? {
560        guard s.hasPrefix("[#"), let close = s.firstIndex(of: "]") else { return nil }
561        let value = s[s.index(s.startIndex, offsetBy: 2)..<close]
562        let valid = (value.count == 1 && value.first!.isLetter && value.first!.isUppercase)
563            || (!value.isEmpty && value.allSatisfy { $0.isASCII && $0.isNumber })
564        guard valid else { return nil }
565        let after = s[s.index(after: close)...]
566        guard after.isEmpty || after.first == " " || after.first == "\t" else { return nil }
567        return s[...close]
568    }
569
570    func splitTags(_ s: Substring) -> (title: Substring, gap: Substring, tags: Substring, trailing: Substring) {
571        let trimmed = s.trimmingTrailingWhitespace
572        let trailing = s[trimmed.endIndex...]
573        let none = (title: trimmed, gap: Substring(), tags: Substring(), trailing: trailing)
574        guard trimmed.last == ":" else { return none }
575        let tagStart = trimmed.lastIndex { $0 == " " || $0 == "\t" }.map { trimmed.index(after: $0) } ?? trimmed.startIndex
576        let tags = trimmed[tagStart...]
577        guard tags.count >= 3, tags.first == ":", isTagString(tags) else { return none }
578        let before = trimmed[..<tagStart]
579        let title = before.trimmingTrailingWhitespace
580        return (title, before[title.endIndex...], tags, trailing)
581    }
582
583    func isTagString(_ tags: Substring) -> Bool {
584        tags.dropFirst().dropLast().split(separator: ":", omittingEmptySubsequences: false).allSatisfy { tag in
585            !tag.isEmpty && tag.allSatisfy { $0.isLetter || $0.isNumber || "_@#%".contains($0) }
586        }
587    }
588}