Sources/OrgCore/Commands/EmacsBuffer.swift

520c19a5a032aba7670f66906b721f4333a160b3
orgstar/Sources/OrgCore/Commands/EmacsBuffer.swift history · blame · raw

460 lines · 17974 bytes

  1import Foundation
  2
  3/// A whole-text buffer with Emacs's point and marker rules, for porting org commands that
  4/// edit several lines. Offsets are UTF-16, as everywhere in `OrgCore`.
  5///
  6/// Inserting at point moves point past the text; a marker at the insertion point stays before
  7/// it unless the insertion is `insertBeforeMarkers`. Deleting a range moves positions inside
  8/// it to its start. `saveExcursion` restores point from a marker, as Emacs does.
  9final class EmacsBuffer {
 10    final class Marker {
 11        var position: Int
 12        init(_ position: Int) { self.position = position }
 13    }
 14
 15    struct UserError: Error {
 16        let message: String
 17    }
 18
 19    private(set) var text: NSMutableString
 20    var point: Int
 21    private var markers: [Marker] = []
 22    let settings: OrgSettings
 23    /// Groups of the last successful match, as Emacs's match data.
 24    var lastMatch: [Range<Int>?] = []
 25
 26    init(_ text: String, point: Int, settings: OrgSettings = .default) {
 27        self.text = NSMutableString(string: text)
 28        self.point = point
 29        self.settings = settings
 30        unchangedPrefix = self.text.length
 31        unchangedSuffix = self.text.length
 32    }
 33
 34    /// Lengths of the start and end of the text no edit has touched, so the result's diff can
 35    /// look only between them.
 36    private(set) var unchangedPrefix: Int
 37    private(set) var unchangedSuffix: Int
 38
 39    private func touched(_ range: Range<Int>) {
 40        unchangedPrefix = min(unchangedPrefix, range.lowerBound)
 41        unchangedSuffix = min(unchangedSuffix, length - range.upperBound)
 42    }
 43
 44    /// The text as a `String` backed by an immutable `NSString`, copied once per change rather
 45    /// than per regexp search; regexps read it without converting.
 46    var string: String {
 47        if let cachedString { return cachedString as String }
 48        let copy = text.copy() as! NSString
 49        cachedString = copy
 50        return copy as String
 51    }
 52
 53    private var cachedString: NSString?
 54    var length: Int { text.length }
 55
 56    func character(at offset: Int) -> unichar? {
 57        offset >= 0 && offset < length ? text.character(at: offset) : nil
 58    }
 59
 60    static let newline = unichar(10)
 61
 62    // MARK: - Markers
 63
 64    func marker(_ position: Int) -> Marker {
 65        let marker = Marker(position)
 66        markers.append(marker)
 67        return marker
 68    }
 69
 70    func release(_ marker: Marker) {
 71        markers.removeAll { $0 === marker }
 72    }
 73
 74    /// Runs `body` and puts point back where it was, following edits as a marker does.
 75    @discardableResult
 76    func saveExcursion<T>(_ body: () throws -> T) rethrows -> T {
 77        let saved = marker(point)
 78        defer {
 79            point = saved.position
 80            release(saved)
 81        }
 82        return try body()
 83    }
 84
 85    // MARK: - Editing
 86
 87    /// `insert` at point.
 88    func insert(_ string: String) {
 89        let count = (string as NSString).length
 90        guard count > 0 else { return }
 91        touched(point..<point)
 92        text.insert(string, at: point)
 93        cachedString = nil
 94        for marker in markers where marker.position > point { marker.position += count }
 95        point += count
 96    }
 97
 98    /// `insert-before-markers` at point: markers at point move past the text too.
 99    func insertBeforeMarkers(_ string: String) {
100        let count = (string as NSString).length
101        guard count > 0 else { return }
102        touched(point..<point)
103        text.insert(string, at: point)
104        cachedString = nil
105        for marker in markers where marker.position >= point { marker.position += count }
106        point += count
107    }
108
109    func deleteRegion(_ start: Int, _ end: Int) {
110        let (lower, upper) = (min(start, end), max(start, end))
111        guard upper > lower else { return }
112        touched(lower..<upper)
113        text.deleteCharacters(in: NSRange(lower..<upper))
114        cachedString = nil
115        func map(_ position: Int) -> Int {
116            position <= lower ? position : position >= upper ? position - (upper - lower) : lower
117        }
118        point = map(point)
119        for marker in markers { marker.position = map(marker.position) }
120    }
121
122    func substring(_ start: Int, _ end: Int) -> String {
123        text.substring(with: NSRange(min(start, end)..<max(start, end)))
124    }
125
126    /// `replace-match` over `range`: positions strictly inside go to its start, positions at
127    /// or after its end shift with the text.
128    func replace(_ range: Range<Int>, with replacement: String) {
129        let delta = (replacement as NSString).length - range.count
130        touched(range)
131        text.replaceCharacters(in: NSRange(range), with: replacement)
132        cachedString = nil
133        func map(_ position: Int) -> Int {
134            if position >= range.upperBound, position > range.lowerBound { return position + delta }
135            return position > range.lowerBound ? range.lowerBound : position
136        }
137        point = map(point)
138        for marker in markers { marker.position = map(marker.position) }
139    }
140
141    // MARK: - Motion
142
143    var bolp: Bool { point == 0 || character(at: point - 1) == Self.newline }
144    var eolp: Bool { point == length || character(at: point) == Self.newline }
145    var bobp: Bool { point == 0 }
146    var eobp: Bool { point == length }
147
148    func lineStart(_ offset: Int) -> Int {
149        var at = min(offset, length)
150        while at > 0, character(at: at - 1) != Self.newline { at -= 1 }
151        return at
152    }
153
154    func lineEnd(_ offset: Int) -> Int {
155        var at = max(offset, 0)
156        while at < length, character(at: at) != Self.newline { at += 1 }
157        return at
158    }
159
160    func beginningOfLine() { point = lineStart(point) }
161    func endOfLine() { point = lineEnd(point) }
162
163    /// `forward-line`: to the start of the line `n` lines away, stopping at the buffer ends.
164    @discardableResult
165    func forwardLine(_ n: Int) -> Int {
166        point = lineStart(point)
167        var remaining = n
168        while remaining > 0 {
169            let end = lineEnd(point)
170            if end == length {
171                point = length
172                return remaining
173            }
174            point = end + 1
175            remaining -= 1
176        }
177        while remaining < 0 {
178            if point == 0 { return remaining }
179            point = lineStart(point - 1)
180            remaining += 1
181        }
182        return 0
183    }
184
185    func skipForward(_ set: Set<unichar>) {
186        while let c = character(at: point), set.contains(c) { point += 1 }
187    }
188
189    func skipBackward(_ set: Set<unichar>) {
190        while let c = character(at: point - 1), set.contains(c) { point -= 1 }
191    }
192
193    static let blanks: Set<unichar> = [32, 9]
194    static let whitespace: Set<unichar> = [32, 9, 10, 13]
195
196    var currentColumn: Int { column(of: substring(lineStart(point), point)) }
197
198    /// `move-to-column`: as far as `target` on this line, or the line's end. With `force`, a
199    /// tab spanning `target` becomes spaces (`indent-tabs-mode` nil) so point lands on it.
200    func moveToColumn(_ target: Int, force: Bool = false) {
201        let start = lineStart(point)
202        let line = LineBuffer(substring(start, lineEnd(point)), caret: nil)
203        point = start + line.offset(ofColumn: target)
204        guard force, currentColumn > target, character(at: point - 1) == 9 else { return }
205        let tabEnd = currentColumn
206        point -= 1
207        let tabStart = currentColumn
208        deleteRegion(point, point + 1)
209        insert(String(repeating: " ", count: tabEnd - tabStart))
210        point -= tabEnd - target
211    }
212
213    // MARK: - Outline
214
215    /// Stars of a heading line starting at `lineStart`, or nil.
216    func headingLevel(atLine lineStart: Int) -> Int? {
217        var at = lineStart
218        while character(at: at) == 42 { at += 1 }
219        return at > lineStart && character(at: at) == 32 ? at - lineStart : nil
220    }
221
222    var atHeading: Bool { headingLevel(atLine: lineStart(point)) != nil }
223
224    /// Start of the first heading line after `offset`'s line, or nil.
225    func nextHeadingStart(after offset: Int) -> Int? {
226        var line = lineEnd(offset)
227        while line < length {
228            line += 1
229            if headingLevel(atLine: line) != nil { return line }
230            line = lineEnd(line)
231        }
232        return nil
233    }
234
235    /// Start of the last heading line before `offset`'s line, or nil.
236    func previousHeadingStart(before offset: Int) -> Int? {
237        var line = lineStart(offset)
238        while line > 0 {
239            line = lineStart(line - 1)
240            if headingLevel(atLine: line) != nil { return line }
241        }
242        return nil
243    }
244
245    /// `org-outline-level`: the level of the heading at or before point's line, or 0.
246    var outlineLevel: Int {
247        let start = lineStart(point)
248        if let level = headingLevel(atLine: start) { return level }
249        return previousHeadingStart(before: start).flatMap { headingLevel(atLine: $0) } ?? 0
250    }
251
252    var currentLevel: Int? { outlineLevel > 0 ? outlineLevel : nil }
253
254    var beforeFirstHeading: Bool { outlineLevel == 0 }
255
256    /// `org-back-to-heading`.
257    @discardableResult
258    func backToHeading() throws -> Int {
259        let start = lineStart(point)
260        if headingLevel(atLine: start) != nil {
261            point = start
262        } else if let previous = previousHeadingStart(before: start) {
263            point = previous
264        } else {
265            throw UserError(message: "Before first headline at position \(point + 1) in buffer")
266        }
267        return point
268    }
269
270    /// `outline-next-heading`: the next heading line, or the buffer end. True when found.
271    @discardableResult
272    func outlineNextHeading() -> Bool {
273        if bolp, !eobp { point += 1 }
274        // A heading line starting at point counts, as `re-search-forward "^\\*+ "` would.
275        if bolp, headingLevel(atLine: point) != nil { return true }
276        guard let next = nextHeadingStart(after: point) else {
277            point = length
278            return false
279        }
280        point = next
281        return true
282    }
283
284    /// `outline-previous-heading`: the previous heading line, or the buffer start.
285    func outlinePreviousHeading() {
286        // `re-search-backward` matches must end by point: a heading on this line counts once
287        // point is past its stars and space.
288        let start = lineStart(point)
289        if let level = headingLevel(atLine: start), point >= start + level + 1 {
290            point = start
291            return
292        }
293        point = previousHeadingStart(before: point) ?? 0
294    }
295
296    /// `org-end-of-subtree`.
297    @discardableResult
298    func endOfSubtree(toHeading: Bool = false) -> Int {
299        if beforeFirstHeading {
300            point = length
301        } else {
302            let start = try! backToHeading()
303            let level = headingLevel(atLine: start)!
304            var next = nextHeadingStart(after: start)
305            while let candidate = next, headingLevel(atLine: candidate)! > level {
306                next = nextHeadingStart(after: candidate)
307            }
308            point = next ?? length
309        }
310        if !toHeading, let c = character(at: point - 1), c == 10 || c == 13 {
311            point -= 1
312            skipBackward([10, 13, 9, 32])
313        }
314        return point
315    }
316
317    /// `org-get-next-sibling`.
318    func nextSibling() -> Int? {
319        let level = outlineLevel
320        outlineNextHeading()
321        while !eobp, outlineLevel > level { outlineNextHeading() }
322        return eobp || outlineLevel < level ? nil : point
323    }
324
325    /// `org-get-previous-sibling`.
326    func previousSibling() -> Int? {
327        let start = point
328        let level = outlineLevel
329        outlinePreviousHeading()
330        guard point != start, atHeading else { return nil }
331        while outlineLevel > level, !bobp { outlinePreviousHeading() }
332        return outlineLevel < level ? nil : point
333    }
334
335    /// `org--line-empty-p -1`.
336    var previousLineEmpty: Bool {
337        guard !bobp else { return false }
338        return saveExcursion {
339            forwardLine(-1)
340            skipForward(Self.blanks)
341            return eolp
342        }
343    }
344
345    // MARK: - Regular expressions
346
347    static let lookingOptions: NSRegularExpression.MatchingOptions = [.anchored, .withoutAnchoringBounds, .withTransparentBounds]
348    static let searchOptions: NSRegularExpression.MatchingOptions = [.withoutAnchoringBounds, .withTransparentBounds]
349    nonisolated(unsafe) private static var cache: [String: NSRegularExpression] = [:]
350    private static let cacheLock = NSLock()
351
352    /// A compiled Emacs-style pattern: `^` and `$` match at line boundaries, and a leading `^`
353    /// also matches at the end of a buffer that ends with a newline, as in Emacs.
354    static func regex(_ pattern: String, caseInsensitive: Bool) -> NSRegularExpression {
355        let key = (caseInsensitive ? "i" : "c") + pattern
356        return cacheLock.withLock {
357            if let cached = cache[key] { return cached }
358            let source = pattern.hasPrefix("^") ? "(?:(?<=\\n)|(?<![\\s\\S]))" + pattern.dropFirst() : pattern
359            let compiled = try! NSRegularExpression(pattern: source, options: caseInsensitive ? [.anchorsMatchLines, .caseInsensitive] : [.anchorsMatchLines])
360            cache[key] = compiled
361            return compiled
362        }
363    }
364
365    /// `looking-at`: the groups of `pattern` matched at point (`^` and `$` match at lines),
366    /// or nil. Unmatched groups are nil.
367    func lookingAt(_ pattern: String) -> [Range<Int>?]? {
368        let regex = Self.regex(pattern, caseInsensitive: false)
369        guard let match = regex.firstMatch(in: string, options: Self.lookingOptions, range: NSRange(point..<length)) else { return nil }
370        lastMatch = (0..<match.numberOfRanges).map { i in
371            let range = match.range(at: i)
372            return range.location == NSNotFound ? nil : range.location..<NSMaxRange(range)
373        }
374        return lastMatch
375    }
376
377    /// `org-complex-heading-regexp`: 1 stars, 2 keyword, 3 priority, 4 title, 5 tags.
378    var complexHeadingPattern: String {
379        "^(\\*+)(?: +(\(keywordAlternation)))?(?: +(\\[#(?:[A-Z]|[0-9]|[1-5][0-9]|6[0-4])\\]))?(?: +(.*?))??(?:[ \t]+(:[[:alnum:]_@#%:]+:))?[ \t]*$"
380    }
381
382    /// `org-todo-line-regexp`: 1 stars, 2 keyword, 3 title.
383    var todoLinePattern: String {
384        "^(\\*+)(?: +(\(keywordAlternation)))?(?: +(.*?))?[ \t]*$"
385    }
386
387    private var keywordAlternation: String {
388        keywordsInOrder.map { NSRegularExpression.escapedPattern(for: $0) }.joined(separator: "|")
389    }
390
391    /// `org-todo-keywords-1`.
392    var keywordsInOrder: [String] {
393        settings.todoSequences.flatMap { ($0.active + $0.done).map(\.name) }
394    }
395
396    // MARK: - Tags
397
398    /// `org-align-tags` on the line at `offset`, moving point and markers on the line as the
399    /// tag alignment rules say.
400    func alignTags(onLineAt offset: Int) {
401        let start = lineStart(offset)
402        let end = lineEnd(offset)
403        let line = substring(start, end)
404        var plain = LineBuffer(line, caret: nil)
405        OrgCore.alignTags(&plain)
406        guard plain.string != line else { return }
407        func map(_ position: Int) -> Int {
408            guard position >= start, position <= end else {
409                return position > end ? position + (plain.string as NSString).length - (line as NSString).length : position
410            }
411            var buffer = LineBuffer(line, caret: position - start)
412            OrgCore.alignTags(&buffer)
413            return start + buffer.caret!
414        }
415        let newPoint = map(point)
416        let newMarkers = markers.map { map($0.position) }
417        touched(start..<end)
418        text.replaceCharacters(in: NSRange(start..<end), with: plain.string)
419        cachedString = nil
420        point = newPoint
421        for (marker, position) in zip(markers, newMarkers) { marker.position = position }
422    }
423}
424
425/// Runs a buffer-editing body against a context and turns the result into one minimal edit
426/// and the new caret. A user error becomes `.failed`.
427func commitBuffer(_ context: EditContext, _ body: (EmacsBuffer) throws -> Void) -> CommandStep {
428    let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings)
429    do {
430        try body(buffer)
431    } catch let error as EmacsBuffer.UserError {
432        return .failed(error.message)
433    } catch {
434        return .failed("\(error)")
435    }
436    // Only the span between the untouched start and end can differ.
437    let oldText = context.text.utf16
438    let oldCount = oldText.count
439    let newCount = buffer.length
440    let lower = min(buffer.unchangedPrefix, oldCount, newCount)
441    let window = max(0, min(buffer.unchangedSuffix, oldCount - lower, newCount - lower))
442    let old = Array(oldText[oldText.index(oldText.startIndex, offsetBy: lower)..<oldText.index(oldText.startIndex, offsetBy: oldCount - window)])
443    var newBuffer = [unichar](repeating: 0, count: newCount - window - lower)
444    buffer.text.getCharacters(&newBuffer, range: NSRange(lower..<(newCount - window)))
445    let new = newBuffer
446    var prefix = 0
447    let shorter = min(old.count, new.count)
448    while prefix < shorter, old[prefix] == new[prefix] { prefix += 1 }
449    var suffix = 0
450    while suffix < shorter - prefix, old[old.count - 1 - suffix] == new[new.count - 1 - suffix] { suffix += 1 }
451    // Keep surrogate pairs whole.
452    while prefix > 0, prefix < old.count, UTF16.isTrailSurrogate(old[prefix]) { prefix -= 1 }
453    while suffix > 0, UTF16.isTrailSurrogate(old[old.count - suffix]) { suffix -= 1 }
454    let caret = buffer.point
455    guard old.count != new.count || prefix != old.count else {
456        return .commit(EditResult(baseRevision: context.revision, edits: [], selection: [caret..<caret]))
457    }
458    let edit = TextEdit(range: (lower + prefix)..<(lower + old.count - suffix), replacement: String(decoding: new[prefix..<(new.count - suffix)], as: UTF16.self))
459    return .commit(EditResult(baseRevision: context.revision, edits: [edit], selection: [caret..<caret]))
460}