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