Sources/OrgCore/Commands/EmacsBuffer.swift

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

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