Sources/OrgCore/Parser/Parser.swift

524b5afe95ec3f3e3d1daba761a9e181f09cf88a
orgstar/Sources/OrgCore/Parser/Parser.swift history · blame · raw

583 lines · 23083 bytes

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