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