Vim: zz/zt/zb, number increment, replace state, q: !260
8 files changed, +338 −6
Layout: unified · split
Sources/OrgCore/Keymap/Vim.swift +14 −1
| @@ -9,12 +9,13 @@ public struct Vim: Sendable { | |||
| 9 | case normal, insert, visual | 9 | case normal, insert, visual |
| 10 | case visualLine = "visual-line" | 10 | case visualLine = "visual-line" |
| 11 | case visualBlock = "visual-block" | 11 | case visualBlock = "visual-block" |
| 12 | case replace | ||
| 12 | 13 | ||
| 13 | /// The keymap mode name for bindings. | 14 | /// The keymap mode name for bindings. |
| 14 | public var keymapMode: String { | 15 | public var keymapMode: String { |
| 15 | switch self { | 16 | switch self { |
| 16 | case .normal: "normal" | 17 | case .normal: "normal" |
| 17 | case .insert: "insert" | 18 | case .insert, .replace: "insert" |
| 18 | case .visual, .visualLine, .visualBlock: "visual" | 19 | case .visual, .visualLine, .visualBlock: "visual" |
| 19 | } | 20 | } |
| 20 | } | 21 | } |
| @@ -53,6 +54,11 @@ public struct Vim: Sendable { | |||
| 53 | case selectBlock([Range<Int>]) | 54 | case selectBlock([Range<Int>]) |
| 54 | /// `gj`, `gk`: down (or, negative, up) by screen lines, which only the editor knows. | 55 | /// `gj`, `gk`: down (or, negative, up) by screen lines, which only the editor knows. |
| 55 | case visualLines(Int) | 56 | case visualLines(Int) |
| 57 | /// `zz`, `zt`, `zb`: scroll the caret's line to the window's middle, top or bottom. | ||
| 58 | case scroll(ScrollLine) | ||
| 59 | /// `q:`, `q/`, `q?`: the command-line window, the earlier commands or searches to pick | ||
| 60 | /// from and edit. | ||
| 61 | case commandWindow(String) | ||
| 56 | } | 62 | } |
| 57 | 63 | ||
| 58 | public struct Context: Sendable { | 64 | public struct Context: Sendable { |
| @@ -120,6 +126,11 @@ public struct Vim: Sendable { | |||
| 120 | var lastMacro: Character? | 126 | var lastMacro: Character? |
| 121 | /// `$` in block visual state: every line to its end. | 127 | /// `$` in block visual state: every line to its end. |
| 122 | var blockToEnd = false | 128 | var blockToEnd = false |
| 129 | /// Replace state: each typed character's place, what it overwrote (nil past the line's | ||
| 130 | /// end) and its length; the text typed, and the count to repeat it. | ||
| 131 | var replaceStack: [(offset: Int, original: String?, length: Int)] = [] | ||
| 132 | var replaceTyped = "" | ||
| 133 | var replaceCount = 1 | ||
| 123 | 134 | ||
| 124 | public init() {} | 135 | public init() {} |
| 125 | 136 | ||
| @@ -129,6 +140,8 @@ public struct Vim: Sendable { | |||
| 129 | switch mode { | 140 | switch mode { |
| 130 | case .insert: | 141 | case .insert: |
| 131 | return insertKey(key, context) | 142 | return insertKey(key, context) |
| 143 | case .replace: | ||
| 144 | return replaceKey(key, context) | ||
| 132 | case .normal, .visual, .visualLine, .visualBlock: | 145 | case .normal, .visual, .visualLine, .visualBlock: |
| 133 | var key = key | 146 | var key = key |
| 134 | if pending.isEmpty, let repeatKeys = snipeRepeatKeys { | 147 | if pending.isEmpty, let repeatKeys = snipeRepeatKeys { |
Sources/OrgCore/Keymap/VimExtras.swift +1
| @@ -18,6 +18,7 @@ extension Vim { | |||
| 18 | /// Keys evil handles here before operators and motions, or nil. | 18 | /// Keys evil handles here before operators and motions, or nil. |
| 19 | mutating func parseExtras(_ rest: ArraySlice<KeyChord>, _ buffer: inout Buffer, _ context: Context, register: Character?, count: Int?, keys: [KeyChord]) -> Parse? { | 19 | mutating func parseExtras(_ rest: ArraySlice<KeyChord>, _ buffer: inout Buffer, _ context: Context, register: Character?, count: Int?, keys: [KeyChord]) -> Parse? { |
| 20 | guard let first = rest.first else { return .incomplete } | 20 | guard let first = rest.first else { return .incomplete } |
| 21 | if let result = parseMore(rest, &buffer, context, count: count, keys: keys) { return result } | ||
| 21 | let visual = mode == .visual || mode == .visualLine | 22 | let visual = mode == .visual || mode == .visualLine |
| 22 | let n = count ?? 1 | 23 | let n = count ?? 1 |
| 23 | let caret = context.caret | 24 | let caret = context.caret |
Sources/OrgCore/Keymap/VimMore.swift added +196
| @@ -0,0 +1,196 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | // Scrolling the caret's line (`zz`, `zt`, `zb`), numbers (`C-a`, and Doom's evil-numbers keys | ||
| 4 | // `g=` and `g-`), replace state (`R`) and the command-line window (`q:`). | ||
| 5 | |||
| 6 | extension Vim { | ||
| 7 | /// Where `zz`, `zt` and `zb` put the caret's line in the window. | ||
| 8 | public enum ScrollLine: Sendable, Equatable { | ||
| 9 | case center, top, bottom | ||
| 10 | } | ||
| 11 | |||
| 12 | mutating func parseMore(_ rest: ArraySlice<KeyChord>, _ buffer: inout Buffer, _ context: Context, count: Int?, keys: [KeyChord]) -> Parse? { | ||
| 13 | guard let first = rest.first else { return nil } | ||
| 14 | let visual = mode == .visual || mode == .visualLine | ||
| 15 | let second = rest.dropFirst().first | ||
| 16 | let n = count ?? 1 | ||
| 17 | let caret = context.caret | ||
| 18 | if first == KeyChord("a", .control) { | ||
| 19 | return .done(visual ? incrementVisual(buffer, caret, by: n, incremental: false) : increment(buffer, caret, by: n, keys: keys)) | ||
| 20 | } | ||
| 21 | guard first.modifiers.isEmpty else { return nil } | ||
| 22 | switch first.key { | ||
| 23 | case "z" where !visual: | ||
| 24 | guard let second else { return .incomplete } | ||
| 25 | guard second.modifiers.isEmpty else { return nil } | ||
| 26 | let place: ScrollLine | ||
| 27 | switch second.key { | ||
| 28 | case "z", ".": place = .center | ||
| 29 | case "t", "RET": place = .top | ||
| 30 | case "b", "-": place = .bottom | ||
| 31 | default: return nil | ||
| 32 | } | ||
| 33 | // A count names the line; `z.`, `z RET` and `z-` go to its first non-blank. | ||
| 34 | var target = caret | ||
| 35 | if let count { | ||
| 36 | let line = buffer.lineOffset(count) | ||
| 37 | target = buffer.clampNormal(min(line + (caret - buffer.lineStart(caret)), buffer.lineEnd(line)), in: line) | ||
| 38 | } | ||
| 39 | if [".", "RET", "-"].contains(second.key) { target = buffer.firstNonBlank(buffer.lineStart(target)) } | ||
| 40 | return .done((target == caret ? [] : [.move(caret: target)]) + [.scroll(place)]) | ||
| 41 | case "g": | ||
| 42 | guard let second else { return .incomplete } | ||
| 43 | if second == KeyChord("a", .control), visual { return .done(incrementVisual(buffer, caret, by: n, incremental: true)) } | ||
| 44 | guard second.modifiers.isEmpty else { return nil } | ||
| 45 | switch (second.key, visual) { | ||
| 46 | case ("=", false): return .done(increment(buffer, caret, by: n, keys: keys)) | ||
| 47 | case ("-", false): return .done(increment(buffer, caret, by: -n, keys: keys)) | ||
| 48 | case ("=", true): return .done(incrementVisual(buffer, caret, by: n, incremental: true)) | ||
| 49 | case ("-", true): return .done(incrementVisual(buffer, caret, by: -n, incremental: true)) | ||
| 50 | case ("+", true): return .done(incrementVisual(buffer, caret, by: n, incremental: false)) | ||
| 51 | default: return nil | ||
| 52 | } | ||
| 53 | case "R" where !visual: | ||
| 54 | mode = .replace | ||
| 55 | replaceStack = [] | ||
| 56 | replaceTyped = "" | ||
| 57 | replaceCount = n | ||
| 58 | changeKeys = keys | ||
| 59 | return .done([]) | ||
| 60 | case "q" where !visual && !recording: | ||
| 61 | guard let second else { return .incomplete } | ||
| 62 | guard second.modifiers.isEmpty, [":", "/", "?"].contains(second.key) else { return nil } | ||
| 63 | return .done([.commandWindow(second.key)]) | ||
| 64 | default: | ||
| 65 | return nil | ||
| 66 | } | ||
| 67 | } | ||
| 68 | |||
| 69 | // MARK: - Numbers | ||
| 70 | |||
| 71 | /// The numbers of a line, as Vim reads them with `nrformats` `bin,hex`. | ||
| 72 | static let numberPattern = try! NSRegularExpression(pattern: "0[xX][0-9a-fA-F]+|0[bB][01]+|-?[0-9]+") | ||
| 73 | |||
| 74 | /// The number on `line` that ends after `from`, as Vim's `C-a` finds it. | ||
| 75 | static func number(in buffer: Buffer, line: Int, from: Int, to: Int? = nil) -> NSRange? { | ||
| 76 | let end = to ?? buffer.lineEnd(line) | ||
| 77 | guard end > line else { return nil } | ||
| 78 | let text = buffer.substring(line..<end) | ||
| 79 | for m in numberPattern.matches(in: text, range: NSRange(location: 0, length: (text as NSString).length)) where line + NSMaxRange(m.range) > from { | ||
| 80 | return NSRange(location: line + m.range.location, length: m.range.length) | ||
| 81 | } | ||
| 82 | return nil | ||
| 83 | } | ||
| 84 | |||
| 85 | /// `number` plus `amount`, in its own base, width and case. | ||
| 86 | static func adding(_ amount: Int, to number: String) -> String { | ||
| 87 | let lower = number.lowercased() | ||
| 88 | if lower.hasPrefix("0x") || lower.hasPrefix("0b") { | ||
| 89 | let radix = lower.hasPrefix("0x") ? 16 : 2 | ||
| 90 | let digits = String(number.dropFirst(2)) | ||
| 91 | let value = (Int(digits, radix: radix) ?? 0) &+ amount | ||
| 92 | var out = String(UInt(bitPattern: value), radix: radix) | ||
| 93 | if digits.contains(where: \.isUppercase) { out = out.uppercased() } | ||
| 94 | if out.count < digits.count { out = String(repeating: "0", count: digits.count - out.count) + out } | ||
| 95 | return String(number.prefix(2)) + out | ||
| 96 | } | ||
| 97 | let negative = number.hasPrefix("-") | ||
| 98 | let digits = negative ? String(number.dropFirst()) : number | ||
| 99 | let value = (Int(number) ?? 0) &+ amount | ||
| 100 | var out = String(abs(value)) | ||
| 101 | // Leading zeros keep the width. | ||
| 102 | if digits.count > 1, digits.hasPrefix("0"), out.count < digits.count { out = String(repeating: "0", count: digits.count - out.count) + out } | ||
| 103 | return (value < 0 ? "-" : "") + out | ||
| 104 | } | ||
| 105 | |||
| 106 | /// `C-a` with a negative `amount` for `g-`: the number at or after the caret on its line; | ||
| 107 | /// the caret ends on its last character. | ||
| 108 | mutating func increment(_ buffer: Buffer, _ caret: Int, by amount: Int, keys: [KeyChord]) -> [Action] { | ||
| 109 | guard let range = Self.number(in: buffer, line: buffer.lineStart(caret), from: caret) else { return [] } | ||
| 110 | let replacement = Self.adding(amount, to: buffer.ns.substring(with: range)) | ||
| 111 | lastChange = (keys, nil) | ||
| 112 | return [.edit([TextEdit(range: range.location..<NSMaxRange(range), replacement: replacement)], caret: range.location + replacement.utf16.count - 1)] | ||
| 113 | } | ||
| 114 | |||
| 115 | /// Visual `C-a` and Doom's `g=`, as evil-numbers does: every number in the selection by | ||
| 116 | /// `amount`, or with `incremental` the nth by n times `amount`. | ||
| 117 | mutating func incrementVisual(_ buffer: Buffer, _ caret: Int, by amount: Int, incremental: Bool) -> [Action] { | ||
| 118 | let (range, linewise) = visualRange(buffer, caret) | ||
| 119 | lastVisual = (anchor, caret, mode) | ||
| 120 | mode = .normal | ||
| 121 | let text = buffer.substring(range) | ||
| 122 | var edits: [TextEdit] = [] | ||
| 123 | for (k, m) in Self.numberPattern.matches(in: text, range: NSRange(location: 0, length: (text as NSString).length)).enumerated() { | ||
| 124 | let number = (text as NSString).substring(with: m.range) | ||
| 125 | edits.append(TextEdit(range: (range.lowerBound + m.range.location)..<(range.lowerBound + NSMaxRange(m.range)), | ||
| 126 | replacement: Self.adding(incremental ? amount * (k + 1) : amount, to: number))) | ||
| 127 | } | ||
| 128 | let start = linewise ? buffer.lineStart(range.lowerBound) : range.lowerBound | ||
| 129 | return edits.isEmpty ? [.move(caret: buffer.clampNormal(start))] : [.edit(edits, caret: start)] | ||
| 130 | } | ||
| 131 | |||
| 132 | // MARK: - Replace state | ||
| 133 | |||
| 134 | /// A key in replace state: characters overwrite the line's, past its end they add to it, | ||
| 135 | /// RET breaks the line, backspace gives back what was overwritten, and ESC repeats the | ||
| 136 | /// typed text for the count. | ||
| 137 | mutating func replaceKey(_ key: KeyChord, _ context: Context) -> [Action] { | ||
| 138 | changeKeys?.append(key) | ||
| 139 | let buffer = Buffer(context) | ||
| 140 | let caret = context.caret | ||
| 141 | if key == KeyChord("ESC") || key == KeyChord("[", .control) || key == KeyChord("g", .control) { | ||
| 142 | var actions: [Action] = [] | ||
| 143 | var text = context.text | ||
| 144 | var at = caret | ||
| 145 | for _ in 1..<max(1, replaceCount) { | ||
| 146 | for character in replaceTyped { | ||
| 147 | let edit = Self.replacement(String(character), Buffer(text), at) | ||
| 148 | text = edit.edit.apply(to: text) | ||
| 149 | at = edit.caret | ||
| 150 | actions.append(.edit([edit.edit], caret: at)) | ||
| 151 | } | ||
| 152 | } | ||
| 153 | mode = .normal | ||
| 154 | if let keys = changeKeys { | ||
| 155 | lastChange = (keys, nil) | ||
| 156 | changeKeys = nil | ||
| 157 | } | ||
| 158 | let lineStart = Buffer(text).lineStart(at) | ||
| 159 | actions.append(.move(caret: at > lineStart ? at - 1 : at)) | ||
| 160 | return actions | ||
| 161 | } | ||
| 162 | if key == KeyChord("DEL") || key == KeyChord("h", .control) { | ||
| 163 | guard let last = replaceStack.popLast() else { | ||
| 164 | return caret > buffer.lineStart(caret) ? [.move(caret: caret - 1)] : [] | ||
| 165 | } | ||
| 166 | if !replaceTyped.isEmpty { replaceTyped.removeLast() } | ||
| 167 | let edit = TextEdit(range: last.offset..<(last.offset + last.length), replacement: last.original ?? "") | ||
| 168 | return [.edit([edit], caret: last.offset)] | ||
| 169 | } | ||
| 170 | let typed: String | ||
| 171 | switch key.key { | ||
| 172 | case "SPC": typed = " " | ||
| 173 | case "TAB": typed = "\t" | ||
| 174 | case "RET": typed = "\n" | ||
| 175 | default: | ||
| 176 | guard key.modifiers.isEmpty || key.modifiers == [.shift], key.key.count == 1 else { return [] } | ||
| 177 | typed = key.key | ||
| 178 | } | ||
| 179 | let result = Self.replacement(typed, buffer, caret) | ||
| 180 | replaceStack.append((caret, result.original, typed.utf16.count)) | ||
| 181 | replaceTyped += typed | ||
| 182 | return [.edit([result.edit], caret: result.caret)] | ||
| 183 | } | ||
| 184 | |||
| 185 | /// `typed` over the character at `caret`, or after the line's end (and for a line break) | ||
| 186 | /// added there. | ||
| 187 | static func replacement(_ typed: String, _ buffer: Buffer, _ caret: Int) -> (edit: TextEdit, caret: Int, original: String?) { | ||
| 188 | let length = typed.utf16.count | ||
| 189 | guard typed != "\n", caret < buffer.lineEnd(caret) else { | ||
| 190 | return (TextEdit(range: caret..<caret, replacement: typed), caret + length, nil) | ||
| 191 | } | ||
| 192 | let characterEnd = NSMaxRange(buffer.ns.rangeOfComposedCharacterSequence(at: caret)) | ||
| 193 | let original = buffer.substring(caret..<characterEnd) | ||
| 194 | return (TextEdit(range: caret..<characterEnd, replacement: typed), caret + length, original) | ||
| 195 | } | ||
| 196 | } | ||
Sources/OrgEditorAppKit/Modal.swift +38 −4
| @@ -287,6 +287,10 @@ extension OrgEditor { | |||
| 287 | } | 287 | } |
| 288 | case .selectBlock(let ranges): | 288 | case .selectBlock(let ranges): |
| 289 | textView.setSelectedRanges(ranges.map { NSValue(range: NSRange($0)) }, affinity: .downstream, stillSelecting: false) | 289 | textView.setSelectedRanges(ranges.map { NSValue(range: NSRange($0)) }, affinity: .downstream, stillSelecting: false) |
| 290 | case .scroll(let place): | ||
| 291 | scrollCaretLine(place) | ||
| 292 | case .commandWindow(let kind): | ||
| 293 | prompt(kind, history: true) | ||
| 290 | } | 294 | } |
| 291 | } | 295 | } |
| 292 | } | 296 | } |
| @@ -301,10 +305,40 @@ extension OrgEditor { | |||
| 301 | if caret >= end, end > line.location { setCaret(end - 1) } | 305 | if caret >= end, end > line.location { setCaret(end - 1) } |
| 302 | } | 306 | } |
| 303 | 307 | ||
| 304 | /// `/`, `?` and `:` read their argument in the echo area. | 308 | /// `zz`, `zt` and `zb`: the window scrolled so the caret's screen line is in its middle, |
| 305 | private func prompt(_ kind: String) { | 309 | /// at its top or at its bottom. |
| 306 | onPrompt?(Prompt(key: kind, message: kind)) { [weak self] answer in | 310 | private func scrollCaretLine(_ place: Vim.ScrollLine) { |
| 311 | guard let scroll = textView.enclosingScrollView, let layout = textView.textLayoutManager, let content = layout.textContentManager else { return } | ||
| 312 | let caret = textView.selectedRange().location | ||
| 313 | guard let location = content.location(content.documentRange.location, offsetBy: caret) else { return } | ||
| 314 | layout.ensureLayout(for: NSTextRange(location: location)) | ||
| 315 | guard let fragment = layout.textLayoutFragment(for: location) else { return } | ||
| 316 | let within = content.offset(from: fragment.rangeInElement.location, to: location) | ||
| 317 | let line = fragment.textLineFragments.first { $0.characterRange.contains(within) || $0.characterRange.upperBound == within } ?? fragment.textLineFragments.last | ||
| 318 | let lineFrame = line.map { $0.typographicBounds.offsetBy(dx: 0, dy: fragment.layoutFragmentFrame.minY) } ?? fragment.layoutFragmentFrame | ||
| 319 | let top = lineFrame.minY + textView.textContainerOrigin.y | ||
| 320 | let height = scroll.contentView.bounds.height | ||
| 321 | let y: CGFloat = switch place { | ||
| 322 | case .top: top | ||
| 323 | case .center: top + lineFrame.height / 2 - height / 2 | ||
| 324 | case .bottom: top + lineFrame.height - height | ||
| 325 | } | ||
| 326 | let maxY = max(0, textView.frame.height - height) | ||
| 327 | scroll.contentView.scroll(to: NSPoint(x: scroll.contentView.bounds.origin.x, y: min(max(0, y), maxY))) | ||
| 328 | scroll.reflectScrolledClipView(scroll.contentView) | ||
| 329 | } | ||
| 330 | |||
| 331 | /// `/`, `?` and `:` read their argument in the echo area; `history` (`q:`) offers the | ||
| 332 | /// earlier ones to pick and edit. | ||
| 333 | private func prompt(_ kind: String, history: Bool = false) { | ||
| 334 | let earlier = Array((Self.promptHistory[kind] ?? []).reversed()) | ||
| 335 | let request = history ? Prompt(key: kind, message: kind, choices: earlier, requireMatch: false) : Prompt(key: kind, message: kind) | ||
| 336 | onPrompt?(request) { [weak self] answer in | ||
| 307 | guard let self, let answer, !answer.isEmpty else { return } | 337 | guard let self, let answer, !answer.isEmpty else { return } |
| 338 | var list = Self.promptHistory[kind] ?? [] | ||
| 339 | list.removeAll { $0 == answer } | ||
| 340 | list.append(answer) | ||
| 341 | Self.promptHistory[kind] = Array(list.suffix(100)) | ||
| 308 | let caret = self.textView.selectedRange().location | 342 | let caret = self.textView.selectedRange().location |
| 309 | let context = Vim.Context(text: self.document.text, caret: caret) | 343 | let context = Vim.Context(text: self.document.text, caret: caret) |
| 310 | if kind == ":" { | 344 | if kind == ":" { |
| @@ -387,7 +421,7 @@ extension OrgEditor { | |||
| 387 | 421 | ||
| 388 | /// A block cursor in normal and visual states, a bar in insert state. | 422 | /// A block cursor in normal and visual states, a bar in insert state. |
| 389 | func updateCursor() { | 423 | func updateCursor() { |
| 390 | let block = modal && vim.mode != .insert | 424 | let block = modal && vim.mode != .insert && vim.mode != .replace |
| 391 | for view in orgTextViews { view.blockCursor = block } | 425 | for view in orgTextViews { view.blockCursor = block } |
| 392 | dispatcher.mode = modal ? vim.mode.keymapMode : nil | 426 | dispatcher.mode = modal ? vim.mode.keymapMode : nil |
| 393 | let state = modal ? vim.mode.rawValue : nil | 427 | let state = modal ? vim.mode.rawValue : nil |
Sources/OrgEditorAppKit/OrgEditor.swift +2
| @@ -414,6 +414,8 @@ public final class OrgEditor: NSObject { | |||
| 414 | static var vimRegisters: [Character: (text: String, linewise: Bool)] = [:] | 414 | static var vimRegisters: [Character: (text: String, linewise: Bool)] = [:] |
| 415 | static var vimClipboardRecord: (text: String, linewise: Bool)? | 415 | static var vimClipboardRecord: (text: String, linewise: Bool)? |
| 416 | static var macros: [Character: [KeyChord]] = [:] | 416 | static var macros: [Character: [KeyChord]] = [:] |
| 417 | /// What `:`, `/` and `?` read, oldest first, for the command-line window (`q:`). | ||
| 418 | static var promptHistory: [String: [String]] = [:] | ||
| 417 | /// Shows `editor`'s buffer with the caret at the offset, for a jump to a file mark set | 419 | /// Shows `editor`'s buffer with the caret at the offset, for a jump to a file mark set |
| 418 | /// there. | 420 | /// there. |
| 419 | public var onJumpToEditor: ((OrgEditor, Int) -> Void)? | 421 | public var onJumpToEditor: ((OrgEditor, Int) -> Void)? |
Sources/Orgstar/Keys.swift +1
| @@ -143,6 +143,7 @@ struct StateTag: View { | |||
| 143 | private var color: Color { | 143 | private var color: Color { |
| 144 | switch state { | 144 | switch state { |
| 145 | case "insert": theme.color("state-insert") ?? .green | 145 | case "insert": theme.color("state-insert") ?? .green |
| 146 | case "replace": theme.color("state-replace") ?? .red | ||
| 146 | case "visual", "visual-line", "visual-block": theme.color("state-visual") ?? .orange | 147 | case "visual", "visual-line", "visual-block": theme.color("state-visual") ?? .orange |
| 147 | default: theme.color("state-normal") ?? .blue | 148 | default: theme.color("state-normal") ?? .blue |
| 148 | } | 149 | } |
Tests/OrgCoreTests/VimTests.swift +80
| @@ -306,6 +306,86 @@ struct VimTests { | |||
| 306 | #expect(actions == [.jumped(from: 70), .move(caret: 133)]) | 306 | #expect(actions == [.jumped(from: 70), .move(caret: 133)]) |
| 307 | } | 307 | } |
| 308 | 308 | ||
| 309 | /// Replace state, and evil-numbers on the keys Doom binds (`g=`, `g-`, visual `g=`, `g-` | ||
| 310 | /// and `g+`) and on `C-a`. | ||
| 311 | static let replaceAndNumbers: [(String, Int, String)] = [ | ||
| 312 | ("hello world\n", 0, "R J E L ESC"), | ||
| 313 | ("hello\n", 3, "R a b c d ESC"), | ||
| 314 | ("hello world\n", 0, "R a b DEL DEL c ESC"), | ||
| 315 | ("hello world\n", 0, "3 R x y ESC"), | ||
| 316 | ("hello world\n", 2, "R a RET b ESC"), | ||
| 317 | ("aaaa bbbb\n", 0, "R x y ESC w ."), | ||
| 318 | ("item 7 and 12\n", 0, "g ="), | ||
| 319 | ("item 7 and 12\n", 6, "5 g ="), | ||
| 320 | ("item 7 and 12\n", 6, "g -"), | ||
| 321 | ("value -3 here\n", 0, "4 g ="), | ||
| 322 | ("count 009\n", 0, "g ="), | ||
| 323 | ("count 010\n", 0, "g -"), | ||
| 324 | ("addr 0xff\n", 0, "g ="), | ||
| 325 | ("addr 0xFE\n", 0, "g ="), | ||
| 326 | ("bits 0b0111\n", 0, "g ="), | ||
| 327 | ("no digits\n", 0, "g ="), | ||
| 328 | ("1\n1\n1\n", 0, "V j j g ="), | ||
| 329 | ("1\n1\n1\n", 0, "V j j g +"), | ||
| 330 | ("a 1 b 2\nc 3\n", 0, "V j 2 g -"), | ||
| 331 | ("x 1 y\n", 0, "C-a"), | ||
| 332 | ("x 1 y 2\n", 4, "3 C-a"), | ||
| 333 | ] | ||
| 334 | |||
| 335 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | ||
| 336 | func replaceAndNumbersMatchEvil() throws { | ||
| 337 | let repos = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".config/emacs/.local/straight/repos") | ||
| 338 | guard FileManager.default.fileExists(atPath: repos.appendingPathComponent("evil-numbers/evil-numbers.el").path) else { return } | ||
| 339 | var forms: [EmacsOracle.Case] = [] | ||
| 340 | for (text, point, keys) in Self.replaceAndNumbers { | ||
| 341 | forms.append(EmacsOracle.Case(text: text, point: point + 1, form: """ | ||
| 342 | (progn | ||
| 343 | (setq evil-want-Y-yank-to-eol t evil-undo-system 'undo-redo) | ||
| 344 | (dolist (p '("evil" "goto-chg" "evil-numbers" "emacs-shift-number")) (add-to-list 'load-path (concat "\(repos.path)/" p))) | ||
| 345 | (require 'evil) | ||
| 346 | (require 'evil-numbers) | ||
| 347 | (evil-define-key 'normal 'global (kbd "g=") #'evil-numbers/inc-at-pt (kbd "g-") #'evil-numbers/dec-at-pt (kbd "C-a") #'evil-numbers/inc-at-pt) | ||
| 348 | (evil-define-key 'visual 'global (kbd "g=") #'evil-numbers/inc-at-pt-incremental (kbd "g-") #'evil-numbers/dec-at-pt-incremental (kbd "g+") #'evil-numbers/inc-at-pt) | ||
| 349 | (switch-to-buffer (current-buffer)) | ||
| 350 | (evil-local-mode 1) | ||
| 351 | (evil-normal-state) | ||
| 352 | (execute-kbd-macro (kbd "\(keys.replacingOccurrences(of: "ESC", with: "<escape>").replacingOccurrences(of: "DEL", with: "DEL"))")) | ||
| 353 | (let ((p (point)) (s evil-state)) | ||
| 354 | (goto-char (point-max)) | ||
| 355 | (insert (format "\\n@@STATE %s" s)) | ||
| 356 | (goto-char p))) | ||
| 357 | """)) | ||
| 358 | } | ||
| 359 | let results = try EmacsOracle.run(forms) | ||
| 360 | for ((text, point, keys), result) in zip(Self.replaceAndNumbers, results) { | ||
| 361 | var driver = VimDriver(text, caret: point) | ||
| 362 | driver.visible = 0..<text.utf16.count | ||
| 363 | driver.type(Self.keys(keys)) | ||
| 364 | guard let marker = result.text.range(of: "\n@@STATE ") else { | ||
| 365 | Issue.record("\(keys): \(result.error)") | ||
| 366 | continue | ||
| 367 | } | ||
| 368 | let emacsText = String(result.text[..<marker.lowerBound]) | ||
| 369 | let state = String(result.text[marker.upperBound...]) | ||
| 370 | let ours = driver.vim.mode == .normal ? "normal" : driver.vim.mode.rawValue | ||
| 371 | let emacsCaret = EmacsOracle.offset(result.point, in: result.text) | ||
| 372 | #expect(driver.text == emacsText && driver.caret == emacsCaret && ours == state, | ||
| 373 | "\(keys.debugDescription) on \(text.debugDescription) at \(point)\nours: \(driver.text.debugDescription) @\(driver.caret) \(ours)\nevil: \(emacsText.debugDescription) @\(emacsCaret) \(state) \(result.error)") | ||
| 374 | } | ||
| 375 | } | ||
| 376 | |||
| 377 | @Test func scrollsAndOpensTheCommandWindow() { | ||
| 378 | var vim = Vim() | ||
| 379 | let text = "one\n two\nthree\n" | ||
| 380 | #expect(vim.feed(KeyChord("z"), Vim.Context(text: text, caret: 0)) == []) | ||
| 381 | #expect(vim.feed(KeyChord("z"), Vim.Context(text: text, caret: 0)) == [.scroll(.center)]) | ||
| 382 | _ = vim.feed(KeyChord("2"), Vim.Context(text: text, caret: 0)) | ||
| 383 | _ = vim.feed(KeyChord("z"), Vim.Context(text: text, caret: 0)) | ||
| 384 | #expect(vim.feed(KeyChord("RET"), Vim.Context(text: text, caret: 0)) == [.move(caret: 6), .scroll(.top)]) | ||
| 385 | _ = vim.feed(KeyChord("q"), Vim.Context(text: text, caret: 0)) | ||
| 386 | #expect(vim.feed(KeyChord(":"), Vim.Context(text: text, caret: 0)) == [.commandWindow(":")]) | ||
| 387 | } | ||
| 388 | |||
| 309 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | 389 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) |
| 310 | func matchesEvil() throws { | 390 | func matchesEvil() throws { |
| 311 | let evil = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".config/emacs/.local/straight/repos") | 391 | let evil = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".config/emacs/.local/straight/repos") |
docs/manual/guide/03-keys.org +6 −1
| @@ -380,6 +380,9 @@ Single-key changes: | |||
| 380 | | =J= | Joins the next line (count: that many lines) with one space. | | 380 | | =J= | Joins the next line (count: that many lines) with one space. | |
| 381 | | =~= | Toggles the case of the character under the caret and moves right. | | 381 | | =~= | Toggles the case of the character under the caret and moves right. | |
| 382 | | =r= /x/ | Replaces the character under the caret (count: that many) with /x/; =r RET= splits the line. | | 382 | | =r= /x/ | Replaces the character under the caret (count: that many) with /x/; =r RET= splits the line. | |
| 383 | | =R= | Replace state: what you type overwrites the line's characters, and past the line's end adds to it. =RET= breaks the line, =DEL= gives back what was overwritten, =ESC= returns to normal state. A count types the text that many times. | | ||
| 384 | | =g==, =g-=, =C-a= | Adds the count (1) to the number at or after the caret on its line, or with =g-= takes it away, as evil-numbers does on Doom's =g== and =g-=: decimal, =0x= hex and =0b= binary numbers, keeping leading zeros and the hex digits' case. In visual state =g== and =g-= change every number in the selection, the nth by n times the count; =g+= and =C-a= by the count. =C-x= stays the Emacs prefix, as in Doom. | | ||
| 385 | | =zz=, =zt=, =zb= | Scrolls the caret's line to the middle, top or bottom of the window. =z.=, =z RET= and =z-= do the same and go to its first non-blank. A count names the line. | | ||
| 383 | | =u=, =C-r= | Undo, redo, with counts. | | 386 | | =u=, =C-r= | Undo, redo, with counts. | |
| 384 | | =.= | Repeats the last change. | | 387 | | =.= | Repeats the last change. | |
| 385 | | =ZZ= | Saves the file and closes the window, as =:wq=. | | 388 | | =ZZ= | Saves the file and closes the window, as =:wq=. | |
| @@ -655,11 +658,13 @@ Besides the leader, the preset binds these evil-org and Doom keys in normal stat | |||
| 655 | | =:%s/= /pattern/ =/= /replacement/ =/= /flags/ | The same on every line. | | 658 | | =:%s/= /pattern/ =/= /replacement/ =/= /flags/ | The same on every line. | |
| 656 | | =:noh=, =:nohlsearch= | Accepted; does nothing. | | 659 | | =:noh=, =:nohlsearch= | Accepted; does nothing. | |
| 657 | 660 | ||
| 661 | =q:= opens the ex prompt with your earlier commands listed, most recent first, to pick and edit; =q/= and =q?= do the same for searches. | ||
| 662 | |||
| 658 | Anything else shows =Not an editor command=. Ranges other than =%=, the =c= flag, =:g=, =:normal= and =:set= are not available, and =:= does not work in visual state. | 663 | Anything else shows =Not an editor command=. Ranges other than =%=, the =c= flag, =:g=, =:normal= and =:set= are not available, and =:= does not work in visual state. |
| 659 | 664 | ||
| 660 | ** Not available | 665 | ** Not available |
| 661 | 666 | ||
| 662 | Things evil users may reach for that orgstar does not have: =zz=, =zt= and the other scroll and fold =z= commands except =za=, =zc=, =zo= and =zA=; =C-a= and =C-x= to increment numbers; =gi=, =g;=, =gJ=; replace state (=R=); =&=; =q:=; the numbered and read-only registers; tag and sentence text objects. | 667 | Things evil users may reach for that orgstar does not have: the fold =z= commands other than =za=, =zc=, =zo= and =zA=, and scrolling by lines (=zh=, =zl=, =C-e=, =C-y=); =gi=, =g;=, =gJ=; =&=; the numbered and read-only registers; tag and sentence text objects. |
| 663 | 668 | ||
| 664 | * Keys in other windows | 669 | * Keys in other windows |
| 665 | 670 | ||