Sources/OrgCore/Parser/Lines.swift

198 lines · 8131 bytes

  1/// One line of source: its content and its terminator ("", "\n" or "\r\n"), both as slices of
  2/// the original text.
  3struct RawLine {
  4    let content: Substring
  5    let ending: Substring
  6}
  7
  8/// Splits on "\n" without normalizing anything. Works on unicode scalars, because String
  9/// treats "\r\n" as a single Character.
 10func splitRawLines(_ text: String) -> [RawLine] {
 11    var lines: [RawLine] = []
 12    let scalars = text.unicodeScalars
 13    var lineStart = scalars.startIndex
 14    var i = lineStart
 15    while i != scalars.endIndex {
 16        if scalars[i] == "\n" {
 17            var contentEnd = i
 18            if contentEnd > lineStart, scalars[scalars.index(before: i)] == "\r" {
 19                contentEnd = scalars.index(before: i)
 20            }
 21            let next = scalars.index(after: i)
 22            lines.append(RawLine(content: text[lineStart..<contentEnd], ending: text[contentEnd..<next]))
 23            lineStart = next
 24            i = next
 25        } else {
 26            i = scalars.index(after: i)
 27        }
 28    }
 29    if lineStart != scalars.endIndex {
 30        lines.append(RawLine(content: text[lineStart...], ending: text[text.endIndex...]))
 31    }
 32    return lines
 33}
 34
 35enum LineClass: Equatable {
 36    case blank
 37    case heading(level: Int)
 38    /// Fifteen stars or more (`org-inlinetask-min-level`): an inline task, not a heading.
 39    case inlineTask(level: Int)
 40    case inlineTaskEnd
 41    case blockBegin(name: String)
 42    case blockEnd(name: String)
 43    case dynamicBegin
 44    case dynamicEnd
 45    case drawerBegin(name: String)
 46    case drawerEnd
 47    /// `\begin{NAME}` and `\end{NAME}` of a LaTeX environment.
 48    case latexBegin(name: String)
 49    case latexEnd(name: String)
 50    case keyword(key: String)
 51    case comment
 52    case fixedWidth
 53    case horizontalRule
 54    case tableRow
 55    /// `+--+--+`, which may start a table.el table.
 56    case tableElRule
 57    /// `%%(…)` at the start of a line.
 58    case diarySexp
 59    case footnoteDefinition
 60    case clock
 61    case planning
 62    case listItem
 63    case plain
 64}
 65
 66struct ClassifiedLine {
 67    let cls: LineClass
 68    /// Column of the first non-blank character, with tabs advancing to the next multiple of 8.
 69    let indent: Int
 70}
 71
 72func classifyLine(_ line: Substring, alphabetical: Bool = false) -> ClassifiedLine {
 73    var column = 0
 74    var rest = line
 75    while let c = rest.first, c == " " || c == "\t" {
 76        column = c == "\t" ? (column / 8 + 1) * 8 : column + 1
 77        rest = rest.dropFirst()
 78    }
 79    if rest.isEmpty { return ClassifiedLine(cls: .blank, indent: column) }
 80    return ClassifiedLine(cls: lineClass(rest, columnZero: column == 0, alphabetical: alphabetical), indent: column)
 81}
 82
 83/// `org-inlinetask-min-level`.
 84let inlineTaskLevel = 15
 85
 86private func lineClass(_ rest: Substring, columnZero: Bool, alphabetical: Bool) -> LineClass {
 87    lazy var trimmed = rest.trimmingTrailingWhitespace
 88    // Every test below needs a particular first character; the first byte rules most out.
 89    let first = rest.utf8.first
 90
 91    // As org's `org-outline-regexp`: stars and then a space. A lone `*`, or stars before a tab,
 92    // is not a heading.
 93    if columnZero, rest.first == "*" {
 94        let stars = rest.prefix { $0 == "*" }
 95        if rest.dropFirst(stars.count).first == " " {
 96            guard stars.count >= inlineTaskLevel else { return .heading(level: stars.count) }
 97            return trimmed.dropFirst(stars.count).trimmingCharacters(in: .whitespaces) == "END" ? .inlineTaskEnd : .inlineTask(level: stars.count)
 98        }
 99    }
100
101    if first == UInt8(ascii: "#"), rest.hasPrefix("#+") {
102        let lower = trimmed.lowercased()
103        if lower.hasPrefix("#+begin_") {
104            let name = lower.dropFirst(8).prefix { !$0.isWhitespace }
105            if !name.isEmpty { return .blockBegin(name: String(name)) }
106        }
107        if lower.hasPrefix("#+end_") {
108            let name = lower.dropFirst(6)
109            if !name.isEmpty, !name.contains(where: \.isWhitespace) { return .blockEnd(name: String(name)) }
110        }
111        if lower.hasPrefix("#+begin:") { return .dynamicBegin }
112        if lower == "#+end:" { return .dynamicEnd }
113        if let colon = rest.firstIndex(of: ":") {
114            let key = rest[rest.index(rest.startIndex, offsetBy: 2)..<colon]
115            if !key.isEmpty, !key.contains(where: \.isWhitespace) { return .keyword(key: key.uppercased()) }
116        }
117    }
118
119    if first == UInt8(ascii: "#"), trimmed == "#" || rest.hasPrefix("# ") || rest.hasPrefix("#\t") { return .comment }
120
121    if first == UInt8(ascii: "\\"), rest.hasPrefix("\\begin{") || rest.hasPrefix("\\end{") {
122        let begin = rest.hasPrefix("\\begin{")
123        let after = rest.dropFirst(begin ? 7 : 5)
124        let name = after.prefix { $0.isLetter || $0.isNumber || $0 == "*" }
125        if !name.isEmpty, after.dropFirst(name.count).first == "}" {
126            // The end line has nothing after it.
127            let tail = after.dropFirst(name.count + 1)
128            if begin { return .latexBegin(name: String(name)) }
129            if tail.trimmingCharacters(in: .whitespaces).isEmpty { return .latexEnd(name: String(name)) }
130        }
131    }
132
133    if rest.first == ":" {
134        if trimmed == ":" || rest.hasPrefix(": ") || rest.hasPrefix(":\t") { return .fixedWidth }
135        if trimmed.uppercased() == ":END:" { return .drawerEnd }
136        if trimmed.count >= 3, trimmed.last == ":" {
137            let name = trimmed.dropFirst().dropLast()
138            if name.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "_" || $0 == "-" }) {
139                return .drawerBegin(name: String(name))
140            }
141        }
142    }
143
144    if rest.first == "|" { return .tableRow }
145    if rest.first == "+", trimmed.wholeMatch(of: /\+(?:-+\+)+/) != nil { return .tableElRule }
146    if columnZero, first == UInt8(ascii: "%"), rest.hasPrefix("%%(") { return .diarySexp }
147    if rest.first == "-", trimmed.count >= 5, trimmed.allSatisfy({ $0 == "-" }) { return .horizontalRule }
148
149    if columnZero, first == UInt8(ascii: "["), rest.hasPrefix("[fn:"), let close = rest.firstIndex(of: "]"),
150       close > rest.index(rest.startIndex, offsetBy: 4) {
151        return .footnoteDefinition
152    }
153
154    if first == UInt8(ascii: "C"), rest.hasPrefix("CLOCK:") { return .clock }
155    if first == UInt8(ascii: "S") || first == UInt8(ascii: "D") || first == UInt8(ascii: "C"),
156       rest.hasPrefix("SCHEDULED:") || rest.hasPrefix("DEADLINE:") || rest.hasPrefix("CLOSED:") { return .planning }
157    if isListBullet(rest, indented: !columnZero, alphabetical: alphabetical) { return .listItem }
158    return .plain
159}
160
161/// `-`, `+`, `*` (indented only), `1.` or `1)`, and with `org-list-allow-alphabetical` `a.` or
162/// `A)`, followed by whitespace or end of line.
163private func isListBullet(_ rest: Substring, indented: Bool, alphabetical: Bool) -> Bool {
164    guard let first = rest.first else { return false }
165    let afterBullet: Substring
166    if first == "-" || first == "+" || (first == "*" && indented) {
167        afterBullet = rest.dropFirst()
168    } else if alphabetical, first.isASCII, first.isLetter, let separator = rest.dropFirst().first, separator == "." || separator == ")" {
169        afterBullet = rest.dropFirst(2)
170    } else if first.isASCII, first.isNumber {
171        let digits = rest.prefix { $0.isASCII && $0.isNumber }
172        let tail = rest.dropFirst(digits.count)
173        guard let separator = tail.first, separator == "." || separator == ")" else { return false }
174        afterBullet = tail.dropFirst()
175    } else {
176        return false
177    }
178    return afterBullet.isEmpty || afterBullet.first == " " || afterBullet.first == "\t"
179}
180
181/// Whether `bytes` holds a run of `count` copies of `byte`. A cheap test before a search by
182/// Character.
183func containsBytes(_ bytes: Substring.UTF8View, _ byte: UInt8, count: Int) -> Bool {
184    var run = 0
185    for b in bytes {
186        run = b == byte ? run + 1 : 0
187        if run == count { return true }
188    }
189    return false
190}
191
192extension Substring {
193    var trimmingTrailingWhitespace: Substring {
194        var s = self
195        while let last = s.last, last == " " || last == "\t" { s = s.dropLast() }
196        return s
197    }
198}