Sources/OrgCore/Parser/Lines.swift

265b9d63623b99c4c2b8e8c4d104c57fec553586
orgstar/Sources/OrgCore/Parser/Lines.swift history · blame · raw

178 lines · 7093 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    case footnoteDefinition
 56    case clock
 57    case planning
 58    case listItem
 59    case plain
 60}
 61
 62struct ClassifiedLine {
 63    let cls: LineClass
 64    /// Column of the first non-blank character, with tabs advancing to the next multiple of 8.
 65    let indent: Int
 66}
 67
 68func classifyLine(_ line: Substring, alphabetical: Bool = false) -> ClassifiedLine {
 69    var column = 0
 70    var rest = line
 71    while let c = rest.first, c == " " || c == "\t" {
 72        column = c == "\t" ? (column / 8 + 1) * 8 : column + 1
 73        rest = rest.dropFirst()
 74    }
 75    if rest.isEmpty { return ClassifiedLine(cls: .blank, indent: column) }
 76    return ClassifiedLine(cls: lineClass(rest, columnZero: column == 0, alphabetical: alphabetical), indent: column)
 77}
 78
 79/// `org-inlinetask-min-level`.
 80let inlineTaskLevel = 15
 81
 82private func lineClass(_ rest: Substring, columnZero: Bool, alphabetical: Bool) -> LineClass {
 83    let trimmed = rest.trimmingTrailingWhitespace
 84
 85    // As org's `org-outline-regexp`: stars and then a space. A lone `*`, or stars before a tab,
 86    // is not a heading.
 87    if columnZero, rest.first == "*" {
 88        let stars = rest.prefix { $0 == "*" }
 89        if rest.dropFirst(stars.count).first == " " {
 90            guard stars.count >= inlineTaskLevel else { return .heading(level: stars.count) }
 91            return trimmed.dropFirst(stars.count).trimmingCharacters(in: .whitespaces) == "END" ? .inlineTaskEnd : .inlineTask(level: stars.count)
 92        }
 93    }
 94
 95    if rest.hasPrefix("#+") {
 96        let lower = trimmed.lowercased()
 97        if lower.hasPrefix("#+begin_") {
 98            let name = lower.dropFirst(8).prefix { !$0.isWhitespace }
 99            if !name.isEmpty { return .blockBegin(name: String(name)) }
100        }
101        if lower.hasPrefix("#+end_") {
102            let name = lower.dropFirst(6)
103            if !name.isEmpty, !name.contains(where: \.isWhitespace) { return .blockEnd(name: String(name)) }
104        }
105        if lower.hasPrefix("#+begin:") { return .dynamicBegin }
106        if lower == "#+end:" { return .dynamicEnd }
107        if let colon = rest.firstIndex(of: ":") {
108            let key = rest[rest.index(rest.startIndex, offsetBy: 2)..<colon]
109            if !key.isEmpty, !key.contains(where: \.isWhitespace) { return .keyword(key: key.uppercased()) }
110        }
111    }
112
113    if trimmed == "#" || rest.hasPrefix("# ") || rest.hasPrefix("#\t") { return .comment }
114
115    if rest.hasPrefix("\\begin{") || rest.hasPrefix("\\end{") {
116        let begin = rest.hasPrefix("\\begin{")
117        let after = rest.dropFirst(begin ? 7 : 5)
118        let name = after.prefix { $0.isLetter || $0.isNumber || $0 == "*" }
119        if !name.isEmpty, after.dropFirst(name.count).first == "}" {
120            // The end line has nothing after it.
121            let tail = after.dropFirst(name.count + 1)
122            if begin { return .latexBegin(name: String(name)) }
123            if tail.trimmingCharacters(in: .whitespaces).isEmpty { return .latexEnd(name: String(name)) }
124        }
125    }
126
127    if rest.first == ":" {
128        if trimmed == ":" || rest.hasPrefix(": ") || rest.hasPrefix(":\t") { return .fixedWidth }
129        if trimmed.uppercased() == ":END:" { return .drawerEnd }
130        if trimmed.count >= 3, trimmed.last == ":" {
131            let name = trimmed.dropFirst().dropLast()
132            if name.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "_" || $0 == "-" }) {
133                return .drawerBegin(name: String(name))
134            }
135        }
136    }
137
138    if rest.first == "|" { return .tableRow }
139    if trimmed.count >= 5, trimmed.allSatisfy({ $0 == "-" }) { return .horizontalRule }
140
141    if columnZero, rest.hasPrefix("[fn:"), let close = rest.firstIndex(of: "]"),
142       close > rest.index(rest.startIndex, offsetBy: 4) {
143        return .footnoteDefinition
144    }
145
146    if rest.hasPrefix("CLOCK:") { return .clock }
147    if rest.hasPrefix("SCHEDULED:") || rest.hasPrefix("DEADLINE:") || rest.hasPrefix("CLOSED:") { return .planning }
148    if isListBullet(rest, indented: !columnZero, alphabetical: alphabetical) { return .listItem }
149    return .plain
150}
151
152/// `-`, `+`, `*` (indented only), `1.` or `1)`, and with `org-list-allow-alphabetical` `a.` or
153/// `A)`, followed by whitespace or end of line.
154private func isListBullet(_ rest: Substring, indented: Bool, alphabetical: Bool) -> Bool {
155    guard let first = rest.first else { return false }
156    let afterBullet: Substring
157    if first == "-" || first == "+" || (first == "*" && indented) {
158        afterBullet = rest.dropFirst()
159    } else if alphabetical, first.isASCII, first.isLetter, let separator = rest.dropFirst().first, separator == "." || separator == ")" {
160        afterBullet = rest.dropFirst(2)
161    } else if first.isASCII, first.isNumber {
162        let digits = rest.prefix { $0.isASCII && $0.isNumber }
163        let tail = rest.dropFirst(digits.count)
164        guard let separator = tail.first, separator == "." || separator == ")" else { return false }
165        afterBullet = tail.dropFirst()
166    } else {
167        return false
168    }
169    return afterBullet.isEmpty || afterBullet.first == " " || afterBullet.first == "\t"
170}
171
172extension Substring {
173    var trimmingTrailingWhitespace: Substring {
174        var s = self
175        while let last = s.last, last == " " || last == "\t" { s = s.dropLast() }
176        return s
177    }
178}