Sources/OrgCore/Keymap/VimMotions.swift
285 lines · 15165 bytes
6 symbols in this file
1import Foundation
2
3extension Vim {
4 // MARK: - Motions
5
6 enum MotionKind { case exclusive, inclusive, linewise }
7
8 enum MotionResult {
9 case incomplete
10 case invalid
11 case moved(Int, MotionKind)
12 }
13
14 mutating func motion(_ keys: [KeyChord], _ buffer: inout Buffer, _ caret: inout Int, count n: Int, operatorPending: Bool) -> MotionResult {
15 guard let key = keys.first else { return .incomplete }
16 let c = caret
17 func column(_ position: Int) -> Int { position - buffer.lineStart(position) }
18 switch (key.key, key.modifiers) {
19 case ("h", []), ("<left>", []), ("DEL", []):
20 goalColumn = nil
21 return .moved(max(buffer.lineStart(c), c - n), .exclusive)
22 case ("l", []), ("<right>", []), ("SPC", []):
23 goalColumn = nil
24 let end = buffer.lineEnd(c)
25 let limit = operatorPending ? end : max(buffer.lineStart(c), end - 1)
26 return .moved(min(limit, c + n), .exclusive)
27 case ("j", []), ("k", []), ("<down>", []), ("<up>", []), ("d", [.control]), ("u", [.control]), ("+", []), ("-", []), ("RET", []):
28 let down = ["j", "<down>", "+", "RET"].contains(key.key) || key == KeyChord("d", .control)
29 let lines = key.modifiers.contains(.control) ? (n == 1 ? contextHalfPage : n) : n
30 let goal = goalColumn ?? column(c)
31 var line = buffer.lineStart(c)
32 var moved = 0
33 for _ in 0..<lines {
34 if down {
35 let end = buffer.lineEnd(line)
36 guard end < buffer.length, end + 1 <= buffer.length else { break }
37 if end + 1 == buffer.length { break }
38 line = end + 1
39 } else {
40 guard line > 0 else { break }
41 line = buffer.lineStart(line - 1)
42 }
43 moved += 1
44 }
45 if moved == 0, !key.modifiers.contains(.control) { return .invalid }
46 if ["+", "-", "RET"].contains(key.key) { return .moved(buffer.firstNonBlank(line), .linewise) }
47 goalColumn = goal
48 let length = buffer.lineEnd(line) - line
49 return .moved(line + min(goal, operatorPending ? length : max(0, length - 1)), .linewise)
50 case ("w", []), ("W", []):
51 goalColumn = nil
52 var p = c
53 for _ in 0..<n { p = buffer.wordForward(p, bigWord: key.key == "W") }
54 return .moved(p, .exclusive)
55 case ("b", []), ("B", []):
56 goalColumn = nil
57 var p = c
58 for _ in 0..<n { p = buffer.wordBackward(p, bigWord: key.key == "B", stopAtLine: false) }
59 return .moved(p, .exclusive)
60 case ("e", []), ("E", []):
61 goalColumn = nil
62 var p = c
63 for _ in 0..<n { p = buffer.wordEnd(p, bigWord: key.key == "E", fromInside: false) }
64 return .moved(p, .inclusive)
65 case ("0", []), ("<home>", []):
66 goalColumn = nil
67 return .moved(buffer.lineStart(c), .exclusive)
68 case ("^", []):
69 goalColumn = nil
70 return .moved(buffer.firstNonBlank(buffer.lineStart(c)), .exclusive)
71 case ("$", []), ("<end>", []):
72 var line = buffer.lineStart(c)
73 for _ in 1..<max(1, n) where buffer.lineEnd(line) < buffer.length { line = buffer.lineEnd(line) + 1 }
74 goalColumn = Int.max
75 let end = buffer.lineEnd(line)
76 if mode == .visual { return .moved(end, .inclusive) }
77 return .moved(max(line, end - 1), .inclusive)
78 case ("G", []):
79 // `evil-start-of-line` nil: the column stays.
80 let line = n > 1 || keys.count > 1 ? buffer.lineOffset(n) : buffer.lineStart(buffer.length)
81 let column = c - buffer.lineStart(c)
82 let length = buffer.lineEnd(line) - line
83 return .moved(line + min(column, operatorPending ? length : max(0, length - 1)), .linewise)
84 case ("g", []):
85 guard keys.count >= 2 else { return .incomplete }
86 switch keys[1].key {
87 case "g":
88 let line = buffer.lineOffset(n)
89 let column = c - buffer.lineStart(c)
90 let length = buffer.lineEnd(line) - line
91 return .moved(line + min(column, operatorPending ? length : max(0, length - 1)), .linewise)
92 case "e", "E":
93 var p = c
94 for _ in 0..<n { p = buffer.wordEndBackward(p, bigWord: keys[1].key == "E") }
95 return .moved(p, .inclusive)
96 case "j" where contextOrg, "k" where contextOrg:
97 // evil-org: org-forward-element and org-backward-element, which take no count.
98 guard let p = Self.orgObject(keys[1].key, inner: false, buffer, c)?.range.lowerBound, p != c else { return .invalid }
99 goalColumn = nil
100 return .moved(p, .exclusive)
101 case "j":
102 return motion([KeyChord("j")], &buffer, &caret, count: n, operatorPending: operatorPending)
103 case "k":
104 return motion([KeyChord("k")], &buffer, &caret, count: n, operatorPending: operatorPending)
105 case "_":
106 let end = buffer.lineEnd(c)
107 var p = end
108 while p > buffer.lineStart(c), let ch = buffer.char(p - 1), Buffer.isBlank(ch) { p -= 1 }
109 return .moved(max(buffer.lineStart(c), p - 1), .inclusive)
110 default:
111 return .invalid
112 }
113 case ("f", []), ("F", []), ("t", []), ("T", []):
114 // evil-snipe-override-mode: one-character snipes.
115 guard keys.count >= 2 else { return .incomplete }
116 let char = keys[1].key == "SPC" ? " " : keys[1].key == "TAB" ? "\t" : keys[1].key
117 guard char.count == 1 else { return .invalid }
118 let forward = key.key == "f" || key.key == "t"
119 lastSnipe = (forward, char, n, key.key == "f" || key.key == "F", (KeyChord(key.key.lowercased()), KeyChord(key.key.uppercased())))
120 return snipe(forward: forward, count: n, buffer, c, operatorPending: operatorPending, repeating: false)
121 case (";", []), (",", []):
122 // evil-snipe-repeat, with Doom's `evil-snipe-repeat-scope` visible.
123 guard let last = lastSnipe else { return .invalid }
124 let forward = key.key == ";" ? last.forward : !last.forward
125 return snipe(forward: forward, count: n * last.count, buffer, c, operatorPending: operatorPending, repeating: true)
126 case ("s", []) where !operatorPending, ("S", []) where !operatorPending:
127 guard keys.count >= 3 else { return .incomplete }
128 let chars = keys[1...2].map { $0.key == "SPC" ? " " : $0.key == "TAB" ? "\t" : $0.key }.joined()
129 lastSnipe = (key.key == "s", chars, n, true, (KeyChord("s"), KeyChord("S")))
130 return snipe(forward: key.key == "s", count: n, buffer, c, operatorPending: operatorPending, repeating: false)
131 case ("%", []):
132 guard let p = buffer.matchingBracket(c) else { return .invalid }
133 return .moved(p, .inclusive)
134 case ("'", []), ("`", []):
135 guard keys.count >= 2 else { return .incomplete }
136 let name = keys[1].key == "'" || keys[1].key == "`" ? Character("'") : keys[1].key.first
137 guard let name, let mark = currentMarks[name] else { return .invalid }
138 goalColumn = nil
139 let p = min(mark, buffer.length)
140 return key.key == "'" ? .moved(buffer.firstNonBlank(buffer.lineStart(p)), .linewise) : .moved(p, .exclusive)
141 case ("}", []), ("{", []):
142 var p = c
143 for _ in 0..<n { p = buffer.paragraph(p, forward: key.key == "}") }
144 return .moved(p, .exclusive)
145 case (")", []), ("(", []):
146 goalColumn = nil
147 var p = c
148 for _ in 0..<n { p = buffer.sentence(p, forward: key.key == ")", org: contextOrg) }
149 guard p != c else { return .invalid }
150 // Evil's exclusive motion that ends at a line's start stops at the end of the line
151 // before, and from the line's indentation takes whole lines.
152 if operatorPending, p > c, p == buffer.lineStart(p), p > 0, buffer.char(p - 1) == 10 {
153 if c <= buffer.firstNonBlankOrEnd(buffer.lineStart(c)) { return .moved(p - 1, .linewise) }
154 return .moved(p - 1, .exclusive)
155 }
156 return .moved(p, .exclusive)
157 case ("n", []), ("N", []):
158 guard let search = lastSearch else { return .invalid }
159 let forward = key.key == "n" ? search.forward : !search.forward
160 guard let p = buffer.search(search.pattern, from: c, forward: forward, count: n) else { return .invalid }
161 return .moved(p, .exclusive)
162 case ("*", []), ("#", []):
163 guard let word = buffer.wordAt(c) else { return .invalid }
164 let pattern = "\\b" + NSRegularExpression.escapedPattern(for: word) + "\\b"
165 lastSearch = (pattern, key.key == "*")
166 guard let p = buffer.search(pattern, from: buffer.wordStart(c), forward: key.key == "*", count: n) else { return .invalid }
167 return .moved(p, .exclusive)
168 case ("H", []), ("M", []), ("L", []):
169 // The visible lines: H the count-th from the top, L from the bottom, M the middle.
170 guard let visible = contextVisible else { return .invalid }
171 goalColumn = nil
172 let lower = min(visible.lowerBound, buffer.length)
173 let last = buffer.lineStart(max(lower, min(visible.upperBound, buffer.length) - 1))
174 var lines: [Int] = []
175 var line = buffer.lineStart(lower)
176 while true {
177 lines.append(line)
178 guard line < last, buffer.lineEnd(line) < buffer.length else { break }
179 line = buffer.lineEnd(line) + 1
180 }
181 let index = key.key == "H" ? min(n, lines.count) - 1 : key.key == "L" ? max(0, lines.count - n) : (lines.count - 1) / 2
182 return .moved(buffer.firstNonBlank(lines[index]), .linewise)
183 default:
184 return .invalid
185 }
186 }
187
188 /// `evil-snipe--seek` for the last snipe: the `n`th match from `c` in the line after (or
189 /// before) the search start, or for a repeat in the visible text, with smart case,
190 /// Doom's `evil-snipe-char-fold` and `evil-snipe-skip-leading-whitespace`.
191 mutating func snipe(forward: Bool, count n: Int, _ buffer: Buffer, _ c: Int, operatorPending: Bool, repeating: Bool) -> MotionResult {
192 guard let last = lastSnipe else { return .invalid }
193 // f, s and F search from the next or this character, t and T one further.
194 let start = forward ? c + (last.consume ? 1 : 2) : c - (last.consume ? 0 : 1)
195 guard start >= 0, start <= buffer.length else { return .invalid }
196 var bound = forward ? buffer.lineEnd(start) : buffer.lineStart(start)
197 if repeating, let visible = contextVisible {
198 bound = forward ? min(visible.upperBound, buffer.length) - 1 : min(visible.lowerBound, start)
199 }
200 let blankKeys = last.chars.first == " " || last.chars.first == "\t"
201 let regexps = last.chars.map(CharFold.regexp)
202 var pattern = regexps.map(CharFold.icu).joined()
203 if blankKeys, let ch = buffer.char(start), Buffer.isBlank(ch) { pattern += "[^ \t]" }
204 // `evil-snipe--case-p`: case matters when the regexps hold a capital letter.
205 let caseFold = !regexps.joined().unicodeScalars.contains { ("A"..."Z").contains($0) }
206 let regex = try! NSRegularExpression(pattern: pattern, options: caseFold ? .caseInsensitive : [])
207 var match: NSRange?
208 if forward, start <= bound {
209 var from = start
210 for _ in 0..<n {
211 match = regex.firstMatch(in: buffer.ns as String, range: NSRange(location: from, length: bound - from))?.range
212 guard let found = match else { break }
213 from = NSMaxRange(found)
214 }
215 } else if !forward {
216 var from = start
217 for _ in 0..<n {
218 match = nil
219 var p = from - 1
220 while p >= bound, match == nil {
221 match = regex.firstMatch(in: buffer.ns as String, options: .anchored, range: NSRange(location: p, length: from - p))?.range
222 p -= 1
223 }
224 guard let found = match else { break }
225 from = found.location
226 }
227 }
228 guard let found = match else {
229 if repeating { snipeRepeatKeys = last.keys }
230 return .invalid
231 }
232 if !operatorPending { snipeRepeatKeys = last.keys }
233 var end = NSMaxRange(found)
234 var length = found.length
235 if blankKeys {
236 end -= 1
237 length -= 1
238 }
239 let visual = mode == .visual || mode == .visualLine || mode == .visualBlock
240 var p: Int
241 if !forward {
242 p = last.consume ? found.location : end
243 } else {
244 p = visual ? (last.consume ? end : found.location) : operatorPending ? end : found.location
245 if last.consume {
246 if visual { p -= 1 }
247 } else {
248 p -= length
249 if length > 1, !operatorPending { p += 1 }
250 }
251 }
252 return .moved(p, .exclusive)
253 }
254
255 // MARK: - Text objects
256
257 func textObject(_ inner: Bool, _ key: KeyChord, _ buffer: Buffer, _ c: Int, count: Int) -> (range: Range<Int>, linewise: Bool)? {
258 switch key.key {
259 case "w", "W":
260 return buffer.wordObject(c, inner: inner, bigWord: key.key == "W", count: count).map { ($0, false) }
261 case "\"", "'", "`":
262 return buffer.quoteObject(c, quote: key.key.utf16.first!, inner: inner).map { ($0, false) }
263 case "(", ")", "b":
264 return buffer.bracketObject(c, open: 40, close: 41, inner: inner).map { ($0, false) }
265 case "[", "]":
266 return buffer.bracketObject(c, open: 91, close: 93, inner: inner).map { ($0, false) }
267 case "{", "}", "B":
268 return buffer.bracketObject(c, open: 123, close: 125, inner: inner).map { ($0, false) }
269 case "<", ">":
270 return buffer.bracketObject(c, open: 60, close: 62, inner: inner).map { ($0, false) }
271 case "p":
272 return buffer.paragraphObject(c, inner: inner).map { ($0, true) }
273 case "s":
274 return buffer.sentenceObject(c, inner: inner, count: count, org: contextOrg).map { ($0, false) }
275 case "t":
276 return buffer.tagObject(c, inner: inner, count: count).map { range in
277 !inner && buffer.coversLines(range) ? (range.lowerBound..<min(buffer.length, range.upperBound + 1), true) : (range, false)
278 }
279 case "e", "E", "r", "R":
280 return Self.orgObject(key.key, inner: inner, buffer, c)
281 default:
282 return nil
283 }
284 }
285}