Sources/OrgCore/Parser/Lines.swift

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

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