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