Sources/OrgCore/Keymap/VimMotions.swift

267 lines · 14073 bytes

  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 ("n", []), ("N", []):
146            guard let search = lastSearch else { return .invalid }
147            let forward = key.key == "n" ? search.forward : !search.forward
148            guard let p = buffer.search(search.pattern, from: c, forward: forward, count: n) else { return .invalid }
149            return .moved(p, .exclusive)
150        case ("*", []), ("#", []):
151            guard let word = buffer.wordAt(c) else { return .invalid }
152            let pattern = "\\b" + NSRegularExpression.escapedPattern(for: word) + "\\b"
153            lastSearch = (pattern, key.key == "*")
154            guard let p = buffer.search(pattern, from: buffer.wordStart(c), forward: key.key == "*", count: n) else { return .invalid }
155            return .moved(p, .exclusive)
156        case ("H", []), ("M", []), ("L", []):
157            // The visible lines: H the count-th from the top, L from the bottom, M the middle.
158            guard let visible = contextVisible else { return .invalid }
159            goalColumn = nil
160            let lower = min(visible.lowerBound, buffer.length)
161            let last = buffer.lineStart(max(lower, min(visible.upperBound, buffer.length) - 1))
162            var lines: [Int] = []
163            var line = buffer.lineStart(lower)
164            while true {
165                lines.append(line)
166                guard line < last, buffer.lineEnd(line) < buffer.length else { break }
167                line = buffer.lineEnd(line) + 1
168            }
169            let index = key.key == "H" ? min(n, lines.count) - 1 : key.key == "L" ? max(0, lines.count - n) : (lines.count - 1) / 2
170            return .moved(buffer.firstNonBlank(lines[index]), .linewise)
171        default:
172            return .invalid
173        }
174    }
175
176    /// `evil-snipe--seek` for the last snipe: the `n`th match from `c` in the line after (or
177    /// before) the search start, or for a repeat in the visible text, with smart case,
178    /// Doom's `evil-snipe-char-fold` and `evil-snipe-skip-leading-whitespace`.
179    mutating func snipe(forward: Bool, count n: Int, _ buffer: Buffer, _ c: Int, operatorPending: Bool, repeating: Bool) -> MotionResult {
180        guard let last = lastSnipe else { return .invalid }
181        // f, s and F search from the next or this character, t and T one further.
182        let start = forward ? c + (last.consume ? 1 : 2) : c - (last.consume ? 0 : 1)
183        guard start >= 0, start <= buffer.length else { return .invalid }
184        var bound = forward ? buffer.lineEnd(start) : buffer.lineStart(start)
185        if repeating, let visible = contextVisible {
186            bound = forward ? min(visible.upperBound, buffer.length) - 1 : min(visible.lowerBound, start)
187        }
188        let blankKeys = last.chars.first == " " || last.chars.first == "\t"
189        let regexps = last.chars.map(CharFold.regexp)
190        var pattern = regexps.map(CharFold.icu).joined()
191        if blankKeys, let ch = buffer.char(start), Buffer.isBlank(ch) { pattern += "[^ \t]" }
192        // `evil-snipe--case-p`: case matters when the regexps hold a capital letter.
193        let caseFold = !regexps.joined().unicodeScalars.contains { ("A"..."Z").contains($0) }
194        let regex = try! NSRegularExpression(pattern: pattern, options: caseFold ? .caseInsensitive : [])
195        var match: NSRange?
196        if forward, start <= bound {
197            var from = start
198            for _ in 0..<n {
199                match = regex.firstMatch(in: buffer.ns as String, range: NSRange(location: from, length: bound - from))?.range
200                guard let found = match else { break }
201                from = NSMaxRange(found)
202            }
203        } else if !forward {
204            var from = start
205            for _ in 0..<n {
206                match = nil
207                var p = from - 1
208                while p >= bound, match == nil {
209                    match = regex.firstMatch(in: buffer.ns as String, options: .anchored, range: NSRange(location: p, length: from - p))?.range
210                    p -= 1
211                }
212                guard let found = match else { break }
213                from = found.location
214            }
215        }
216        guard let found = match else {
217            if repeating { snipeRepeatKeys = last.keys }
218            return .invalid
219        }
220        if !operatorPending { snipeRepeatKeys = last.keys }
221        var end = NSMaxRange(found)
222        var length = found.length
223        if blankKeys {
224            end -= 1
225            length -= 1
226        }
227        let visual = mode == .visual || mode == .visualLine || mode == .visualBlock
228        var p: Int
229        if !forward {
230            p = last.consume ? found.location : end
231        } else {
232            p = visual ? (last.consume ? end : found.location) : operatorPending ? end : found.location
233            if last.consume {
234                if visual { p -= 1 }
235            } else {
236                p -= length
237                if length > 1, !operatorPending { p += 1 }
238            }
239        }
240        return .moved(p, .exclusive)
241    }
242
243    // MARK: - Text objects
244
245    func textObject(_ inner: Bool, _ key: KeyChord, _ buffer: Buffer, _ c: Int, count: Int) -> (range: Range<Int>, linewise: Bool)? {
246        switch key.key {
247        case "w", "W":
248            return buffer.wordObject(c, inner: inner, bigWord: key.key == "W", count: count).map { ($0, false) }
249        case "\"", "'", "`":
250            return buffer.quoteObject(c, quote: key.key.utf16.first!, inner: inner).map { ($0, false) }
251        case "(", ")", "b":
252            return buffer.bracketObject(c, open: 40, close: 41, inner: inner).map { ($0, false) }
253        case "[", "]":
254            return buffer.bracketObject(c, open: 91, close: 93, inner: inner).map { ($0, false) }
255        case "{", "}", "B":
256            return buffer.bracketObject(c, open: 123, close: 125, inner: inner).map { ($0, false) }
257        case "<", ">":
258            return buffer.bracketObject(c, open: 60, close: 62, inner: inner).map { ($0, false) }
259        case "p":
260            return buffer.paragraphObject(c, inner: inner).map { ($0, true) }
261        case "e", "E", "r", "R":
262            return Self.orgObject(key.key, inner: inner, buffer, c)
263        default:
264            return nil
265        }
266    }
267}