Sources/OrgCore/Parser/Parser.swift

53903567a65c44ccdf4ba4ff6ffa6d04721efea1
orgstar/Sources/OrgCore/Parser/Parser.swift

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