Sources/OrgCore/Snippets/SnippetSession.swift
121 lines · 5453 bytes
1import Foundation
2
3/// An expanded snippet while its fields are filled in: TAB and S-TAB move between fields,
4/// typing in a field changes its mirrors, and leaving the last field, Escape, or an edit or
5/// caret outside the snippet ends it. Offsets are UTF-16 into the buffer.
6public struct SnippetSession: Sendable, Equatable {
7 public struct Field: Sendable, Equatable {
8 public let number: Int
9 /// The field first, then its mirrors.
10 public var ranges: [Range<Int>]
11 }
12
13 public private(set) var fields: [Field]
14 /// Where the caret goes when the last field is left.
15 public private(set) var exit: Range<Int>
16 /// From the start of the snippet to its end.
17 public private(set) var extent: Range<Int>
18 /// The field being filled in.
19 public private(set) var active = 0
20
21 /// The session for `expansion` inserted at `offset`; nil when it has no fields.
22 public init?(_ expansion: SnippetExpansion, at offset: Int) {
23 guard !expansion.fields.isEmpty else { return nil }
24 func shifted(_ range: Range<Int>) -> Range<Int> { (range.lowerBound + offset)..<(range.upperBound + offset) }
25 fields = expansion.fields.map { Field(number: $0.number, ranges: $0.ranges.map(shifted)) }
26 exit = shifted(expansion.exit)
27 extent = offset..<(offset + expansion.text.utf16.count)
28 }
29
30 /// The active field's text range, which is selected on entering it.
31 public var selection: Range<Int> { fields[active].ranges[0] }
32
33 public enum Step: Sendable, Equatable {
34 /// Select this field.
35 case field(Range<Int>)
36 /// The snippet is done; select `exit`.
37 case exit(Range<Int>)
38 }
39
40 /// TAB: the next field, or the exit after the last.
41 public mutating func next() -> Step {
42 guard active + 1 < fields.count else { return .exit(exit) }
43 active += 1
44 return .field(selection)
45 }
46
47 /// S-TAB: the field before, or the first again.
48 public mutating func previous() -> Range<Int> {
49 if active > 0 { active -= 1 }
50 return selection
51 }
52
53 /// Whether `offset` is in the snippet, its ends included.
54 public func contains(_ offset: Int) -> Bool { extent.lowerBound <= offset && offset <= extent.upperBound }
55
56 /// Follows `edit` of the buffer; false when the edit is outside the snippet, which ends it.
57 /// Text typed at either end of the active field goes into it, and an edit replacing a
58 /// mirror exactly becomes the mirror's text.
59 public mutating func map(_ edit: TextEdit) -> Bool {
60 let a = edit.range.lowerBound, b = edit.range.upperBound
61 let n = edit.replacement.utf16.count
62 let delta = n - (b - a)
63 let primary = fields[active].ranges[0]
64 let inActive = primary.lowerBound <= a && b <= primary.upperBound
65 guard inActive || (extent.lowerBound <= a && b <= extent.upperBound) else { return false }
66 // Replacing the whole snippet, as undoing its expansion does, ends it.
67 if !inActive, a == extent.lowerBound, b == extent.upperBound, !extent.isEmpty { return false }
68 /// A position; `right` keeps it after text inserted there.
69 func point(_ p: Int, right: Bool) -> Int {
70 if p < a { return p }
71 if p > b { return p + delta }
72 if a == b { return right ? p + n : p }
73 if p == a { return p }
74 if p == b { return p + delta }
75 return right ? a + n : a
76 }
77 func range(_ r: Range<Int>, grows: Bool) -> Range<Int> {
78 if grows { return point(r.lowerBound, right: false)..<point(r.upperBound, right: true) }
79 if r.isEmpty {
80 let p = point(r.lowerBound, right: true)
81 return p..<p
82 }
83 let lower = point(r.lowerBound, right: true), upper = point(r.upperBound, right: false)
84 return lower..<max(lower, upper)
85 }
86 var mirrorGrown = false
87 for f in fields.indices {
88 for r in fields[f].ranges.indices {
89 let old = fields[f].ranges[r]
90 var grows = false
91 if inActive {
92 grows = f == active && r == 0
93 } else if !mirrorGrown, r > 0, old == edit.range {
94 grows = true
95 mirrorGrown = true
96 }
97 fields[f].ranges[r] = range(old, grows: grows)
98 }
99 }
100 exit = range(exit, grows: false)
101 extent = point(extent.lowerBound, right: false)..<point(extent.upperBound, right: true)
102 return true
103 }
104
105 /// Edits that make every mirror show its field's text in `text`, the buffer as it is now.
106 public func mirrorEdits(in text: String) -> [TextEdit] {
107 let ns = text as NSString
108 func substring(_ r: Range<Int>) -> String? {
109 guard r.upperBound <= ns.length else { return nil }
110 return ns.substring(with: NSRange(location: r.lowerBound, length: r.count))
111 }
112 var edits: [TextEdit] = []
113 for field in fields {
114 guard let value = substring(field.ranges[0]) else { continue }
115 for mirror in field.ranges.dropFirst() where substring(mirror) != value && mirror.upperBound <= ns.length {
116 edits.append(TextEdit(range: mirror, replacement: value))
117 }
118 }
119 return edits.sorted { $0.range.lowerBound < $1.range.lowerBound }
120 }
121}