Sources/OrgCore/Parser/Parser.swift

6c7e17cffd372d46e92a8c9dccad1de263844541
orgstar/Sources/OrgCore/Parser/Parser.swift

466 lines · 17626 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) }
 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) }
 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            parseContent(limit: lines.count)
 91            builder.finish()
 92        }
 93        while i < lines.count, case .heading(let level) = info[i].cls {
 94            parseSection(level: level)
 95        }
 96        builder.finish()
 97        return OrgTree(green: builder.build(), settings: settings)
 98    }
 99
100    func isHeading(_ k: Int) -> Bool {
101        if case .heading = info[k].cls { return true }
102        return false
103    }
104
105    mutating func parseSection(level: Int) {
106        builder.start(.section)
107        headingLine(lines[i])
108        i += 1
109        if i < lines.count, info[i].cls == .planning {
110            single(.planning)
111        }
112        if i < lines.count, case .drawerBegin(let name) = info[i].cls, name.uppercased() == "PROPERTIES",
113           let end = blockEnds[i] {
114            propertyDrawer(end: end)
115        }
116        parseContent(limit: lines.count)
117        while i < lines.count, case .heading(let child) = info[i].cls, child > level {
118            parseSection(level: child)
119        }
120        builder.finish()
121    }
122
123    mutating func propertyDrawer(end: Int) {
124        builder.start(.propertyDrawer)
125        line(i)
126        i += 1
127        while i < end {
128            if info[i].cls == .blank {
129                line(i)
130            } else {
131                builder.start(.nodeProperty)
132                line(i)
133                builder.finish()
134            }
135            i += 1
136        }
137        line(i)
138        i += 1
139        builder.finish()
140    }
141
142    /// Elements until `limit` or the next heading.
143    mutating func parseContent(limit: Int) {
144        while i < limit, !isHeading(i) {
145            element(limit: limit, floor: nil)
146        }
147    }
148
149    static let affiliatedKeys: Set<String> = ["NAME", "CAPTION", "RESULTS", "HEADER", "PLOT"]
150
151    /// One element starting at `i`. `floor` is the indent of the enclosing list item, if any:
152    /// non-blank lines at or left of it end the element.
153    mutating func element(limit: Int, floor: Int?) {
154        switch info[i].cls {
155        case .blank:
156            line(i)
157            i += 1
158        case .blockBegin, .dynamicBegin, .latexBegin:
159            if let end = blockEnds[i], end < limit {
160                let kind: SyntaxKind = switch info[i].cls {
161                case .dynamicBegin: .dynamicBlock
162                case .latexBegin: .latexEnvironment
163                default: .block
164                }
165                builder.start(kind)
166                while i <= end {
167                    line(i)
168                    i += 1
169                }
170                builder.finish()
171            } else {
172                paragraph(limit: limit, floor: floor)
173            }
174        case .drawerBegin:
175            if let end = blockEnds[i], end < limit {
176                builder.start(.drawer)
177                line(i)
178                i += 1
179                parseContent(limit: end)
180                line(i)
181                i += 1
182                builder.finish()
183            } else {
184                paragraph(limit: limit, floor: floor)
185            }
186        case .keyword(let key):
187            let affiliated = Self.affiliatedKeys.contains(key) || key.hasPrefix("ATTR_")
188            single(affiliated ? .affiliatedKeyword : .keyword)
189        case .comment:
190            consecutive(.comment, limit: limit, floor: floor) { $0 == .comment }
191        case .fixedWidth:
192            consecutive(.fixedWidth, limit: limit, floor: floor) { $0 == .fixedWidth }
193        case .horizontalRule:
194            single(.horizontalRule)
195        case .clock:
196            single(.clock)
197        case .tableRow:
198            table(limit: limit, floor: floor)
199        case .footnoteDefinition:
200            footnoteDefinition(limit: limit)
201        case .listItem:
202            list(limit: limit, floor: floor)
203        default:
204            paragraph(limit: limit, floor: floor)
205        }
206    }
207
208    /// Kinds whose single line holds inline objects (timestamps on planning and clock lines).
209    static let inlineLineKinds: Set<SyntaxKind> = [.planning, .clock]
210
211    mutating func single(_ kind: SyntaxKind) {
212        builder.start(kind)
213        if Self.inlineLineKinds.contains(kind) {
214            let rest = whitespace(lines[i].content)
215            inline(rest)
216            builder.token(.newline, lines[i].ending)
217        } else {
218            line(i)
219        }
220        i += 1
221        builder.finish()
222    }
223
224    /// Source text from `start` through the end of line `last`, including its line ending.
225    func span(from start: Substring.Index, through last: Int) -> Substring {
226        let base = lines[last].ending.base
227        return base[start..<lines[last].ending.endIndex]
228    }
229
230    mutating func consecutive(_ kind: SyntaxKind, limit: Int, floor: Int?, matching: (LineClass) -> Bool) {
231        builder.start(kind)
232        repeat {
233            line(i)
234            i += 1
235        } while i < limit && matching(info[i].cls) && within(floor, i)
236        builder.finish()
237    }
238
239    mutating func table(limit: Int, floor: Int?) {
240        builder.start(.table)
241        while i < limit, info[i].cls == .tableRow, within(floor, i) {
242            tableRow()
243        }
244        while i < limit, info[i].cls == .keyword(key: "TBLFM"), within(floor, i) {
245            single(.tableFormula)
246        }
247        builder.finish()
248    }
249
250    /// A rule row (`|---+---|`) is one text token. Other rows alternate `|` markers and cells;
251    /// every pair of pipes gets a cell, even an empty one, so columns line up.
252    mutating func tableRow() {
253        if !reusableRows.isEmpty {
254            let content = lines[i].content
255            if let row = reusableRows[content.base[content.startIndex..<lines[i].ending.endIndex]] {
256                builder.node(row)
257                i += 1
258                return
259            }
260        }
261        builder.start(.tableRow)
262        let rest = whitespace(lines[i].content)
263        if rest.hasPrefix("|-") {
264            builder.token(.text, rest)
265        } else {
266            var cellStart = rest.startIndex
267            var index = rest.startIndex
268            while index < rest.endIndex {
269                if rest[index] == "|" {
270                    if index > rest.startIndex { tableCell(rest[cellStart..<index]) }
271                    builder.token(.marker, "|")
272                    cellStart = rest.index(after: index)
273                }
274                index = rest.index(after: index)
275            }
276            if cellStart < rest.endIndex { tableCell(rest[cellStart...]) }
277        }
278        builder.token(.newline, lines[i].ending)
279        builder.finish()
280        i += 1
281    }
282
283    mutating func tableCell(_ text: Substring) {
284        builder.start(.tableCell)
285        inline(text)
286        builder.finish()
287    }
288
289    mutating func footnoteDefinition(limit: Int) {
290        var end = i + 1
291        while end < limit, info[end].cls == .plain { end += 1 }
292        let content = lines[i].content
293        let close = content.firstIndex(of: "]")!
294        builder.start(.footnoteDefinition)
295        builder.token(.marker, content[...close])
296        inline(span(from: content.index(after: close), through: end - 1))
297        builder.finish()
298        i = end
299    }
300
301    mutating func list(limit: Int, floor: Int?) {
302        let base = info[i].indent
303        builder.start(.plainList)
304        while i < limit, info[i].cls == .listItem, info[i].indent == base, within(floor, i) {
305            item(base: base, limit: limit)
306        }
307        builder.finish()
308    }
309
310    /// An item's first line, then everything indented past its bullet. One blank line stays
311    /// inside the item when the item or list continues after it; two end the list.
312    mutating func item(base: Int, limit: Int) {
313        builder.start(.item)
314        var rest = whitespace(lines[i].content)
315        let bullet = rest.prefix { $0 != " " && $0 != "\t" }
316        builder.token(.bullet, bullet)
317        rest = whitespace(rest.dropFirst(bullet.count))
318        if let box = checkbox(rest) {
319            builder.token(.checkbox, box)
320            rest = whitespace(rest.dropFirst(box.count))
321        }
322        // The rest of the bullet line and its continuation lines are the item's first paragraph.
323        var end = i + 1
324        while end < limit, within(base, end), continuesParagraph(end) { end += 1 }
325        if rest.isEmpty, end == i + 1 {
326            builder.token(.newline, lines[i].ending)
327        } else {
328            builder.start(.paragraph)
329            inline(span(from: rest.startIndex, through: end - 1))
330            builder.finish()
331        }
332        i = end
333        while i < limit, !isHeading(i) {
334            if info[i].cls == .blank {
335                var j = i
336                while j < limit, info[j].cls == .blank { j += 1 }
337                guard j - i < 2, j < limit else { break }
338                let continuesItem = info[j].indent > base
339                let nextSibling = info[j].cls == .listItem && info[j].indent == base
340                guard continuesItem || nextSibling else { break }
341                line(i)
342                i += 1
343                if nextSibling { break }
344                continue
345            }
346            guard info[i].indent > base else { break }
347            element(limit: limit, floor: base)
348        }
349        builder.finish()
350    }
351
352    /// `[ ]`, `[X]`, `[x]` or `[-]`, followed by whitespace or end of line.
353    func checkbox(_ s: Substring) -> Substring? {
354        guard s.count >= 3, s.first == "[", "Xx -".contains(s.dropFirst().first!),
355              s.dropFirst(2).first == "]" else { return nil }
356        let after = s.dropFirst(3)
357        guard after.isEmpty || after.first == " " || after.first == "\t" else { return nil }
358        return s.prefix(3)
359    }
360
361    /// The paragraph's lines are one inline run, so emphasis and links can cross a line break.
362    mutating func paragraph(limit: Int, floor: Int?) {
363        var end = i + 1
364        while end < limit, within(floor, end), continuesParagraph(end) { end += 1 }
365        builder.start(.paragraph)
366        inline(span(from: lines[i].content.startIndex, through: end - 1))
367        builder.finish()
368        i = end
369    }
370
371    /// Lines that don't start an element of their own.
372    func continuesParagraph(_ k: Int) -> Bool {
373        switch info[k].cls {
374        case .plain, .planning, .blockEnd, .dynamicEnd, .drawerEnd, .latexEnd:
375            return true
376        case .blockBegin, .dynamicBegin, .drawerBegin, .latexBegin:
377            return blockEnds[k] == nil
378        default:
379            return false
380        }
381    }
382
383    func within(_ floor: Int?, _ k: Int) -> Bool {
384        guard let floor else { return true }
385        return info[k].indent > floor
386    }
387
388    // MARK: - Tokens
389
390    /// A whole line as leading whitespace, content and line ending.
391    mutating func line(_ k: Int) {
392        let rest = whitespace(lines[k].content)
393        builder.token(.text, rest)
394        builder.token(.newline, lines[k].ending)
395    }
396
397    mutating func whitespace(_ s: Substring) -> Substring {
398        let ws = s.prefix { $0 == " " || $0 == "\t" }
399        builder.token(.whitespace, ws)
400        return s.dropFirst(ws.count)
401    }
402
403    mutating func headingLine(_ raw: RawLine) {
404        builder.start(.heading)
405        var rest = raw.content
406        let stars = rest.prefix { $0 == "*" }
407        builder.token(.stars, stars)
408        rest = whitespace(rest.dropFirst(stars.count))
409
410        // As org: a keyword counts only before a space or the end of the line, not a tab.
411        let word = rest.prefix { $0 != " " && $0 != "\t" }
412        let afterWord = rest.dropFirst(word.count).first
413        if !word.isEmpty, afterWord == nil || afterWord == " ", settings.todoKeywordNames.contains(String(word)) {
414            builder.token(.todoKeyword, word)
415            rest = whitespace(rest.dropFirst(word.count))
416        }
417
418        if let cookie = priorityCookie(rest) {
419            builder.token(.priority, cookie)
420            rest = whitespace(rest.dropFirst(cookie.count))
421        }
422
423        let parts = splitTags(rest)
424        if !parts.title.isEmpty {
425            builder.start(.title)
426            inline(parts.title)
427            builder.finish()
428        }
429        builder.token(.whitespace, parts.gap)
430        builder.token(.tags, parts.tags)
431        builder.token(.whitespace, parts.trailing)
432        builder.token(.newline, raw.ending)
433        builder.finish()
434    }
435
436    /// `[#A]` or `[#10]`, followed by whitespace or end of line.
437    func priorityCookie(_ s: Substring) -> Substring? {
438        guard s.hasPrefix("[#"), let close = s.firstIndex(of: "]") else { return nil }
439        let value = s[s.index(s.startIndex, offsetBy: 2)..<close]
440        let valid = (value.count == 1 && value.first!.isLetter && value.first!.isUppercase)
441            || (!value.isEmpty && value.allSatisfy { $0.isASCII && $0.isNumber })
442        guard valid else { return nil }
443        let after = s[s.index(after: close)...]
444        guard after.isEmpty || after.first == " " || after.first == "\t" else { return nil }
445        return s[...close]
446    }
447
448    func splitTags(_ s: Substring) -> (title: Substring, gap: Substring, tags: Substring, trailing: Substring) {
449        let trimmed = s.trimmingTrailingWhitespace
450        let trailing = s[trimmed.endIndex...]
451        let none = (title: trimmed, gap: Substring(), tags: Substring(), trailing: trailing)
452        guard trimmed.last == ":" else { return none }
453        let tagStart = trimmed.lastIndex { $0 == " " || $0 == "\t" }.map { trimmed.index(after: $0) } ?? trimmed.startIndex
454        let tags = trimmed[tagStart...]
455        guard tags.count >= 3, tags.first == ":", isTagString(tags) else { return none }
456        let before = trimmed[..<tagStart]
457        let title = before.trimmingTrailingWhitespace
458        return (title, before[title.endIndex...], tags, trailing)
459    }
460
461    func isTagString(_ tags: Substring) -> Bool {
462        tags.dropFirst().dropLast().split(separator: ":", omittingEmptySubsequences: false).allSatisfy { tag in
463            !tag.isEmpty && tag.allSatisfy { $0.isLetter || $0.isNumber || "_@#%".contains($0) }
464        }
465    }
466}
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