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