diff --git a/apple/TablePro/Core/Vim/VimEngine+Characters.swift b/apple/TablePro/Core/Vim/VimEngine+Characters.swift index 186864c896..5b6e93aac9 100644 --- a/apple/TablePro/Core/Vim/VimEngine+Characters.swift +++ b/apple/TablePro/Core/Vim/VimEngine+Characters.swift @@ -29,4 +29,15 @@ extension VimEngine { } return max(position, limit) } + + // A character's class is its first scalar's, so a variation selector or mark never splits it. + func wordClass(at offset: Int, in buffer: VimTextBuffer) -> VimWordScanner.CharacterClass { + let base = characterStart(at: offset, in: buffer) + let trail = base + 1 < buffer.length ? buffer.character(at: base + 1) : nil + return VimWordScanner.characterClass(lead: buffer.character(at: base), trail: trail) + } + + func isWordCharacter(at offset: Int, in buffer: VimTextBuffer) -> Bool { + wordClass(at: offset, in: buffer) == .word + } } diff --git a/apple/TablePro/Core/Vim/VimEngine+InsertReplace.swift b/apple/TablePro/Core/Vim/VimEngine+InsertReplace.swift index 2a53ae73f8..25a07cb2d1 100644 --- a/apple/TablePro/Core/Vim/VimEngine+InsertReplace.swift +++ b/apple/TablePro/Core/Vim/VimEngine+InsertReplace.swift @@ -94,25 +94,33 @@ extension VimEngine { func processCommandLine(_ char: Character, buffer commandBuffer: String) -> Bool { switch char { + // Leaving the command line ends the command it is part of, an operator typed before it included. case "\u{1B}": + cancelPendingCommand() setMode(.normal) return true case "\r", "\n": let prefix = commandBuffer.first let body = String(commandBuffer.dropFirst()) setMode(.normal) - if prefix == "/" { - runSearch(pattern: body, forward: true) - } else if prefix == "?" { - runSearch(pattern: body, forward: false) + if prefix == "/" || prefix == "?" { + // A search after an operator is its motion, as `d/foo` deletes up to foo. + if pendingOperator != nil, let buffer { + let target = searchTarget(pattern: body, forward: prefix == "/", count: searchCount, in: buffer) + applyMotion(to: target, kind: .exclusive, in: buffer) + } else { + runSearch(pattern: body, forward: prefix == "/", count: searchCount) + } } else { onCommand?(body) } + cancelPendingCommand() return true case "\u{7F}", "\u{08}": if (commandBuffer as NSString).length > 1 { setMode(.commandLine(buffer: String(commandBuffer.dropLast()))) } else { + cancelPendingCommand() setMode(.normal) } return true diff --git a/apple/TablePro/Core/Vim/VimEngine+Motions.swift b/apple/TablePro/Core/Vim/VimEngine+Motions.swift index 10e46b619c..52886742a4 100644 --- a/apple/TablePro/Core/Vim/VimEngine+Motions.swift +++ b/apple/TablePro/Core/Vim/VimEngine+Motions.swift @@ -34,47 +34,29 @@ extension VimEngine { } func moveDown(_ count: Int, in buffer: VimTextBuffer) { - let pos = buffer.selectedRange().location - let (line, col) = buffer.lineAndColumn(forOffset: pos) - if goalColumn == nil { goalColumn = col } - let targetLine = min(buffer.lineCount - 1, line + count) - let newPos = buffer.offset(forLine: targetLine, column: goalColumn ?? col) - if let op = pendingOperator { - let startLineRange = buffer.lineRange(forOffset: pos) - let endLineRange = buffer.lineRange(forOffset: newPos) - let rangeStart = min(startLineRange.location, endLineRange.location) - let rangeEnd = max( - startLineRange.location + startLineRange.length, - endLineRange.location + endLineRange.length - ) - let opRange = NSRange(location: rangeStart, length: rangeEnd - rangeStart) - executeOperatorOnRange(op, range: opRange, linewise: true, in: buffer) - pendingOperator = nil - } else { - buffer.setSelectedRange(NSRange(location: newPos, length: 0)) - } + moveVertically(by: count, in: buffer) } func moveUp(_ count: Int, in buffer: VimTextBuffer) { + moveVertically(by: -count, in: buffer) + } + + // An operator takes the lines whole; on the first or last line it has nothing to take and the command ends. + private func moveVertically(by delta: Int, in buffer: VimTextBuffer) { let pos = buffer.selectedRange().location let (line, col) = buffer.lineAndColumn(forOffset: pos) if goalColumn == nil { goalColumn = col } - let targetLine = max(0, line - count) + let targetLine = min(max(0, line + delta), buffer.lineCount - 1) let newPos = buffer.offset(forLine: targetLine, column: goalColumn ?? col) - if let op = pendingOperator { - let startLineRange = buffer.lineRange(forOffset: newPos) - let endLineRange = buffer.lineRange(forOffset: pos) - let rangeStart = min(startLineRange.location, endLineRange.location) - let rangeEnd = max( - startLineRange.location + startLineRange.length, - endLineRange.location + endLineRange.length - ) - let opRange = NSRange(location: rangeStart, length: rangeEnd - rangeStart) - executeOperatorOnRange(op, range: opRange, linewise: true, in: buffer) - pendingOperator = nil - } else { + guard let op = pendingOperator else { buffer.setSelectedRange(NSRange(location: newPos, length: 0)) + return + } + guard targetLine != line else { + cancelPendingCommand() + return } + operate(op, from: pos, to: newPos, kind: .linewise, in: buffer) } func moveToLineStart(in buffer: VimTextBuffer) { @@ -118,28 +100,51 @@ extension VimEngine { buffer.setSelectedRange(NSRange(location: offset, length: 0)) } - func wordForward(_ count: Int, in buffer: VimTextBuffer) { + // `cw` on a word changes to its end, as `ce` does; elsewhere `w` and `W` go to the next word's start. + func wordMotion(_ count: Int, bigWord: Bool, in buffer: VimTextBuffer) { + let pos = buffer.selectedRange().location + if pendingOperator == .change, pos < buffer.length, !isBlank(buffer.character(at: pos)) { + let end: (Int) -> Int = { bigWord ? buffer.bigWordEnd(from: $0) : buffer.wordEnd(from: $0) } + var target = end(pos - 1) + for _ in 1.. Int? { var pos = buffer.selectedRange().location let isOperator = pendingOperator != nil for i in 0.. prevLineRange.location - && lineEnd <= buffer.length - && buffer.character(at: lineEnd - 1) == 0x0A ? lineEnd - 1 : lineEnd - pos = contentEnd - break + let line = buffer.lineRange(forOffset: pos) + if buffer.lineRange(forOffset: min(next, buffer.length)).location != line.location { + let end = contentEnd(ofLineAt: pos, in: buffer) + if end > line.location { return end } + return NSMaxRange(line) < buffer.length ? NSMaxRange(line) : nil } } pos = next } - if !isOperator { pos = clampToContentPosition(pos, in: buffer) } - buffer.setSelectedRange(NSRange(location: pos, length: 0)) + return pos + } + + func contentEnd(ofLineAt offset: Int, in buffer: VimTextBuffer) -> Int { + let lineRange = buffer.lineRange(forOffset: offset) + let lineEnd = NSMaxRange(lineRange) + let endsInNewline = lineEnd > lineRange.location && lineEnd <= buffer.length + && buffer.character(at: lineEnd - 1) == 0x0A + return endsInNewline ? lineEnd - 1 : lineEnd + } + + func isBlank(_ ch: unichar) -> Bool { + ch == 0x20 || ch == 0x09 || ch == 0x0A || ch == 0x0D } func clampToContentPosition(_ offset: Int, in buffer: VimTextBuffer) -> Int { @@ -173,14 +178,6 @@ extension VimEngine { buffer.setSelectedRange(NSRange(location: pos, length: 0)) } - func bigWordForward(_ count: Int, in buffer: VimTextBuffer) { - var pos = buffer.selectedRange().location - let isOperator = pendingOperator != nil - for _ in 0.. Int? { let pos = buffer.selectedRange().location - let lineRange = buffer.lineRange(forOffset: pos) - let lineEnd = lineRange.location + lineRange.length - let contentEnd = lineEnd > lineRange.location - && lineEnd <= buffer.length - && buffer.character(at: lineEnd - 1) == 0x0A ? lineEnd - 1 : lineEnd + let lineEnd = contentEnd(ofLineAt: pos, in: buffer) var scan = pos - while scan < contentEnd { - if let target = buffer.matchingBracket(at: scan) { - buffer.setSelectedRange(NSRange(location: target, length: 0)) - return - } + while scan < lineEnd { + if let target = buffer.matchingBracket(at: scan) { return target } scan += 1 } + return nil } - func jumpToVisibleLine(_ position: VimScreenPosition, in buffer: VimTextBuffer) { + // `{count}%`: the line that far through the text, as Vim rounds it. + func percentLineTarget(_ count: Int, in buffer: VimTextBuffer) -> Int? { + guard count <= 100 else { return nil } + let line = min(max(0, (count * buffer.lineCount + 99) / 100 - 1), buffer.lineCount - 1) + return firstNonBlankOffset(from: buffer.offset(forLine: line, column: 0), in: buffer) + } + + // Enter and `+` go down `delta` lines, `-` up, to the first non-blank; at the first or last line they fail. + func lineStepTarget(_ delta: Int, in buffer: VimTextBuffer) -> Int? { + let line = buffer.lineAndColumn(forOffset: buffer.selectedRange().location).line + let target = min(max(0, line + delta), buffer.lineCount - 1) + guard target != line else { return nil } + return firstNonBlankOffset(from: buffer.offset(forLine: target, column: 0), in: buffer) + } + + // A count is lines from the top for H and from the bottom for L. + func visibleLineTarget(_ position: VimScreenPosition, count: Int, in buffer: VimTextBuffer) -> Int { let (firstLine, lastLine) = buffer.visibleLineRange() + let skip = max(0, count - 1) let targetLine: Int switch position { - case .top: targetLine = firstLine - case .bottom: targetLine = lastLine + case .top: targetLine = min(firstLine + skip, lastLine) + case .bottom: targetLine = max(lastLine - skip, firstLine) case .middle: targetLine = (firstLine + lastLine) / 2 } let lineStart = buffer.offset(forLine: targetLine, column: 0) - let target = firstNonBlankOffset(from: lineStart, in: buffer) - buffer.setSelectedRange(NSRange(location: target, length: 0)) - goalColumn = nil + return firstNonBlankOffset(from: lineStart, in: buffer) } func executeFindChar(_ char: Character, request: VimFindCharRequest, in buffer: VimTextBuffer) -> Bool { @@ -289,30 +296,26 @@ extension VimEngine { } } - guard var finalPos = resolved else { return true } + guard var finalPos = resolved else { + cancelPendingCommand() + return true + } if request.till { finalPos = request.forward ? previous(finalPos) : characterEnd(at: finalPos, in: buffer) } - executeMotion(in: buffer, inclusive: true) { + // `f` and `t` take the character they reach; `F` and `T` stop short of the cursor's. + executeMotion(in: buffer, inclusive: request.forward) { buffer.setSelectedRange(NSRange(location: finalPos, length: 0)) } return true } - func sentenceForward(_ count: Int, in buffer: VimTextBuffer) { + func sentenceTarget(forward: Bool, count: Int, in buffer: VimTextBuffer) -> Int { var pos = buffer.selectedRange().location for _ in 0.. Int { @@ -332,7 +335,7 @@ extension VimEngine { } i += 1 } - return buffer.length > 0 ? buffer.length - 1 : 0 + return lastLineContentEnd(in: buffer) } func previousSentenceStart(before origin: Int, in buffer: VimTextBuffer) -> Int { @@ -357,20 +360,12 @@ extension VimEngine { return 0 } - func paragraphForward(_ count: Int, in buffer: VimTextBuffer) { + func paragraphTarget(forward: Bool, count: Int, in buffer: VimTextBuffer) -> Int { var pos = buffer.selectedRange().location for _ in 0.. Int { @@ -383,7 +378,12 @@ extension VimEngine { } line += 1 } - return buffer.length > 0 ? buffer.length - 1 : 0 + return lastLineContentEnd(in: buffer) + } + + // Past the last character, so an operator takes it, and a plain motion steps back onto it. + func lastLineContentEnd(in buffer: VimTextBuffer) -> Int { + contentEnd(ofLineAt: buffer.offset(forLine: buffer.lineCount - 1, column: 0), in: buffer) } func previousParagraphBoundary(before origin: Int, in buffer: VimTextBuffer) -> Int { @@ -398,34 +398,38 @@ extension VimEngine { return 0 } - func sectionForward(in buffer: VimTextBuffer) { - let origin = buffer.selectedRange().location - let (originLine, _) = buffer.lineAndColumn(forOffset: origin) - var line = originLine + 1 - while line < buffer.lineCount { - let off = buffer.offset(forLine: line, column: 0) - if off < buffer.length && buffer.character(at: off) == 0x7B { - buffer.setSelectedRange(NSRange(location: off, length: 0)) - return + // `]]` and `[[`: the next or previous line that starts with `{`. With none, the first or last line, and after an + // operator the end of the last line. + func sectionTarget(forward: Bool, count: Int, in buffer: VimTextBuffer) -> Int { + var line = buffer.lineAndColumn(forOffset: buffer.selectedRange().location).line + for _ in 0..= 0 && next < buffer.lineCount { + let off = buffer.offset(forLine: next, column: 0) + if off < buffer.length && buffer.character(at: off) == 0x7B { break } + next += forward ? 1 : -1 } - line += 1 + guard next >= 0 && next < buffer.lineCount else { + guard forward else { return 0 } + let lastLineStart = buffer.offset(forLine: buffer.lineCount - 1, column: 0) + return pendingOperator != nil ? lastLineContentEnd(in: buffer) : lastLineStart + } + line = next } - buffer.setSelectedRange(NSRange(location: max(0, buffer.length - 1), length: 0)) + return buffer.offset(forLine: line, column: 0) } - func sectionBackward(in buffer: VimTextBuffer) { - let origin = buffer.selectedRange().location - let (originLine, _) = buffer.lineAndColumn(forOffset: origin) - var line = originLine - 1 - while line >= 0 { - let off = buffer.offset(forLine: line, column: 0) - if off < buffer.length && buffer.character(at: off) == 0x7B { - buffer.setSelectedRange(NSRange(location: off, length: 0)) - return - } - line -= 1 + // A line of only blanks ends a paragraph for `ip` and `ap`, though not for `{` and `}`. + func lineIsWhite(_ line: Int, in buffer: VimTextBuffer) -> Bool { + let start = buffer.offset(forLine: line, column: 0) + let end = contentEnd(ofLineAt: start, in: buffer) + var scan = start + while scan < end { + let ch = buffer.character(at: scan) + guard ch == 0x20 || ch == 0x09 || ch == 0x0D else { return false } + scan += 1 } - buffer.setSelectedRange(NSRange(location: 0, length: 0)) + return true } func lineIsBlank(_ line: Int, in buffer: VimTextBuffer) -> Bool { diff --git a/apple/TablePro/Core/Vim/VimEngine+NormalMode.swift b/apple/TablePro/Core/Vim/VimEngine+NormalMode.swift index 1d689ecab8..6f115e61c5 100644 --- a/apple/TablePro/Core/Vim/VimEngine+NormalMode.swift +++ b/apple/TablePro/Core/Vim/VimEngine+NormalMode.swift @@ -6,72 +6,81 @@ import Foundation extension VimEngine { - func processNormal(_ char: Character, shift: Bool) -> Bool { // swiftlint:disable:this function_body_length cyclomatic_complexity + func processNormal(_ char: Character, shift: Bool) -> Bool { guard let buffer else { return false } + if char == "\u{1B}" { + cancelPendingCommand() + return true + } + if pendingRegisterSelect { + pendingRegisterSelect = false + // `""` names the unnamed register. + selectedRegister = char == "\"" ? nil : char + return true + } + if !takesCharacterArgument, char.isASCII, let digit = char.wholeNumberValue, countPrefix > 0 || digit > 0 { + if countPrefix <= 99_999 { countPrefix = countPrefix * 10 + digit } + return true + } + let consumed = processNormalCommand(char, shift: shift, in: buffer) + // A finished command drops the count and register typed for it, used or not. + if !hasPendingCommand { + countPrefix = 0 + operatorCount = 0 + selectedRegister = nil + } + return consumed + } + + private var takesCharacterArgument: Bool { + pendingFindChar != nil || pendingReplaceChar || pendingMarkSet || pendingMarkJumpExact != nil || pendingZ + || pendingTextObject || pendingMacroTarget != nil || pendingBracket != nil + } + private func processNormalCommand(_ char: Character, shift: Bool, in buffer: VimTextBuffer) -> Bool { // swiftlint:disable:this function_body_length if let req = pendingFindChar { pendingFindChar = nil - if char == "\u{1B}" { return true } return executeFindChar(char, request: req, in: buffer) } if pendingReplaceChar { pendingReplaceChar = false - if char == "\u{1B}" { return true } return executeReplaceChar(char, in: buffer) } if pendingMarkSet { pendingMarkSet = false - if char == "\u{1B}" { return true } - marks[char] = buffer.selectedRange().location + setMark(char, at: buffer.selectedRange().location, in: buffer) return true } if let exact = pendingMarkJumpExact { pendingMarkJumpExact = nil - if char == "\u{1B}" { return true } jumpToMark(char, exact: exact, in: buffer) return true } - if pendingRegisterSelect { - pendingRegisterSelect = false - if char == "\u{1B}" { return true } - selectedRegister = char - return true - } if pendingZ { pendingZ = false return true } if pendingTextObject { pendingTextObject = false - if char == "\u{1B}" { - pendingOperator = nil - return true - } return executeTextObject(char, around: pendingTextObjectAround, in: buffer) } if let kind = pendingMacroTarget { pendingMacroTarget = nil - if char == "\u{1B}" { return true } handleMacroTarget(kind: kind, register: char) return true } if let bracketKind = pendingBracket { pendingBracket = nil - if char == "\u{1B}" { return true } + let count = consumeCount() switch (bracketKind, char) { - case (.openBracket, "["): sectionBackward(in: buffer); return true - case (.closeBracket, "]"): sectionForward(in: buffer); return true - default: return true - } - } - - if char.isNumber { - let digit = char.wholeNumberValue ?? 0 - if countPrefix > 0 || digit > 0 { - guard countPrefix <= 99_999 else { return true } - countPrefix = countPrefix * 10 + digit - return true + case (.openBracket, "["): + applyMotion(to: sectionTarget(forward: false, count: count, in: buffer), kind: .exclusive, jump: true, in: buffer) + case (.closeBracket, "]"): + applyMotion(to: sectionTarget(forward: true, count: count, in: buffer), kind: .exclusive, jump: true, in: buffer) + default: + cancelPendingCommand() } + return true } if pendingG { @@ -83,6 +92,13 @@ extension VimEngine { return true } + // A key that is not a motion, a text object or the operator doubled ends the command, as Vim's operators + // accept nothing else. + if let op = pendingOperator, !acceptsAfterOperator(char, op) { + cancelPendingCommand() + return true + } + switch char { case "h": let count = consumeCount() @@ -101,13 +117,14 @@ extension VimEngine { case "w": let count = consumeCount() let op = pendingOperator + wordMotion(count, bigWord: false, in: buffer) if let op { - executeOperatorWithMotion(op, motion: { self.wordForward(count, in: buffer) }, in: buffer) recordDot(.operatorWithMotion(op: op, motion: "w", shift: false, count: count)) - } else { - wordForward(count, in: buffer) } - goalColumn = nil + return true + case "b" where buffer.selectedRange().location == 0, "B" where buffer.selectedRange().location == 0: + // Nothing before the start of the text, so the motion fails and an operator does nothing. + applyMotion(to: nil, kind: .exclusive, in: buffer) return true case "b": let count = consumeCount() @@ -161,8 +178,7 @@ extension VimEngine { case "G": return handleG(in: buffer) case "W": - let count = consumeCount() - executeMotion(in: buffer) { self.bigWordForward(count, in: buffer) } + wordMotion(consumeCount(), bigWord: true, in: buffer) return true case "B": let count = consumeCount() @@ -190,7 +206,8 @@ extension VimEngine { } countPrefix = 0 let pos = buffer.selectedRange().location - if pos < buffer.length { + // On an empty line the caret is on the line break, and the text goes before it. + if pos < contentEnd(ofLineAt: pos, in: buffer) { buffer.setSelectedRange(NSRange(location: characterEnd(at: pos, in: buffer), length: 0)) } setMode(.insert) @@ -317,12 +334,18 @@ extension VimEngine { pendingFindChar = VimFindCharRequest(forward: false, till: true) return true case ";": - guard let last = lastFindChar else { return true } + guard let last = lastFindChar else { + applyMotion(to: nil, kind: .exclusive, in: buffer) + return true + } let req = VimFindCharRequest(forward: last.forward, till: last.till) _ = executeFindChar(last.char, request: req, in: buffer) return true case ",": - guard let last = lastFindChar else { return true } + guard let last = lastFindChar else { + applyMotion(to: nil, kind: .exclusive, in: buffer) + return true + } let req = VimFindCharRequest(forward: !last.forward, till: last.till) _ = executeFindChar(last.char, request: req, in: buffer) return true @@ -363,29 +386,36 @@ extension VimEngine { beginOperator(.outdent) return true - case "?": + case "?", "/", ":": + // A count before a search finds that many matches, as `2d/x` deletes up to the second x. + searchCount = char == ":" ? 1 : consumeCount() countPrefix = 0 operatorCount = 0 - setMode(.commandLine(buffer: "?")) + setMode(.commandLine(buffer: String(char))) return true case "%": - jumpToMatchingBracket(in: buffer) + if countPrefix > 0 || operatorCount > 0 { + applyMotion(to: percentLineTarget(consumeCount(), in: buffer), kind: .linewise, jump: true, in: buffer) + } else { + applyMotion(to: matchingBracketTarget(in: buffer), kind: .inclusive, jump: true, in: buffer) + } return true - case "n": - let count = consumeCount() - for _ in 0.. = [ + "h", "j", "k", "l", "w", "b", "e", "W", "B", "E", "0", "$", "^", "_", "g", "G", "f", "F", "t", "T", ";", ",", + "%", "n", "N", "*", "#", "'", "`", "(", ")", "{", "}", "[", "]", "H", "M", "L", "/", "?", ":", "\r", "+", "-", + "i", "a" + ] + + private func acceptsAfterOperator(_ char: Character, _ op: VimOperator) -> Bool { + if Self.keysAfterOperator.contains(char) { return true } + switch char { + case "d": return op == .delete + case "y": return op == .yank + case "c": return op == .change + case ">": return op == .indent + case "<": return op == .outdent + case "~": return op == .toggleCase + case "u": return op == .lowercase + case "U": return op == .uppercase + default: return false + } + } + func handlePendingG(_ char: Character, in buffer: VimTextBuffer) -> Bool { + if pendingOperator != nil, char == "i" || char == "v" || char == "J" { + cancelPendingCommand() + return true + } switch char { case "g": let count = countPrefix @@ -591,6 +617,10 @@ extension VimEngine { pendingOperator = nil return true } + if pendingOperator != nil { + cancelPendingCommand() + return true + } beginOperator(.lowercase) return true case "U": @@ -599,6 +629,10 @@ extension VimEngine { pendingOperator = nil return true } + if pendingOperator != nil { + cancelPendingCommand() + return true + } beginOperator(.uppercase) return true case "~": @@ -607,6 +641,10 @@ extension VimEngine { pendingOperator = nil return true } + if pendingOperator != nil { + cancelPendingCommand() + return true + } beginOperator(.toggleCase) return true default: @@ -657,6 +695,24 @@ extension VimEngine { goalColumn = nil } + // Moves to `target`, or with an operator pending applies it from the cursor to `target`. A motion that found no + // target ends the command, as Vim's failed motions do. + func applyMotion(to target: Int?, kind: VimMotionKind, jump: Bool = false, in buffer: VimTextBuffer) { + goalColumn = nil + guard let target else { + cancelPendingCommand() + return + } + let origin = buffer.selectedRange().location + if let op = pendingOperator { + operate(op, from: origin, to: target, kind: kind, in: buffer) + return + } + let destination = kind == .linewise ? target : clampToContentPosition(target, in: buffer) + buffer.setSelectedRange(NSRange(location: destination, length: 0)) + if jump { lastJumpOrigin = origin } + } + func executeLinewiseOperator(_ op: VimOperator, fromOffset: Int, toLine: Int, in buffer: VimTextBuffer) { let startLineRange = buffer.lineRange(forOffset: fromOffset) let targetOffset = buffer.offset(forLine: toLine, column: 0) diff --git a/apple/TablePro/Core/Vim/VimEngine+Operators.swift b/apple/TablePro/Core/Vim/VimEngine+Operators.swift index 582aa26f7a..92e0c30f17 100644 --- a/apple/TablePro/Core/Vim/VimEngine+Operators.swift +++ b/apple/TablePro/Core/Vim/VimEngine+Operators.swift @@ -16,16 +16,73 @@ extension VimEngine { let startPos = buffer.selectedRange().location motion() let endPos = buffer.selectedRange().location + operate(op, from: startPos, to: endPos, kind: inclusive ? .inclusive : .exclusive, in: buffer) + } - let rangeStart = min(startPos, endPos) - var rangeEnd = max(startPos, endPos) - if inclusive && rangeEnd < buffer.length && buffer.character(at: rangeEnd) != 0x0A { - rangeEnd = characterEnd(at: rangeEnd, in: buffer) + func operate(_ op: VimOperator, from origin: Int, to target: Int, kind: VimMotionKind, in buffer: VimTextBuffer) { + pendingOperator = nil + let start = min(origin, target) + let end = max(origin, target) + if kind == .linewise { + executeOperatorOnRange(op, range: wholeLines(from: start, through: end, in: buffer), linewise: true, in: buffer) + return + } + var rangeEnd = end + if kind == .inclusive, end < buffer.length, buffer.character(at: end) != 0x0A { + rangeEnd = characterEnd(at: end, in: buffer) + } + let startsInIndent = isInIndent(start, in: buffer) + // `:help exclusive`: an exclusive motion that ends at the start of a later line stops at the end of the line + // before, and takes whole lines when it starts in the indent. + if kind == .exclusive, end > start, buffer.lineRange(forOffset: end).location == end { + if startsInIndent { + executeOperatorOnRange(op, range: wholeLines(from: start, through: end - 1, in: buffer), linewise: true, in: buffer) + return + } + rangeEnd = characterStart(at: end - 1, in: buffer) + } + // `>` and `<` shift the lines the motion covers whatever its kind. + if op == .indent || op == .outdent { + let lines = wholeLines(from: start, through: max(start, rangeEnd - 1), in: buffer) + executeOperatorOnRange(op, range: lines, linewise: true, in: buffer) + return } - let range = NSRange(location: rangeStart, length: rangeEnd - rangeStart) + // A delete over several lines from the indent to the end of a line takes the lines, as Vim's `d` does. + if op == .delete, startsInIndent, rangeEnd > start, + buffer.lineRange(forOffset: start).location != buffer.lineRange(forOffset: rangeEnd - 1).location, + isBlankToLineEnd(from: rangeEnd, in: buffer) { + executeOperatorOnRange(op, range: wholeLines(from: start, through: rangeEnd - 1, in: buffer), linewise: true, in: buffer) + return + } + executeOperatorOnRange(op, range: NSRange(location: start, length: rangeEnd - start), linewise: false, in: buffer) + } - executeOperatorOnRange(op, range: range, linewise: false, in: buffer) - pendingOperator = nil + func wholeLines(from start: Int, through end: Int, in buffer: VimTextBuffer) -> NSRange { + let first = buffer.lineRange(forOffset: start).location + let last = NSMaxRange(buffer.lineRange(forOffset: max(start, end))) + return NSRange(location: first, length: last - first) + } + + // Only blanks come before `offset` on its line. + func isInIndent(_ offset: Int, in buffer: VimTextBuffer) -> Bool { + var scan = buffer.lineRange(forOffset: offset).location + while scan < offset { + let ch = buffer.character(at: scan) + guard ch == 0x20 || ch == 0x09 else { return false } + scan += 1 + } + return true + } + + func isBlankToLineEnd(from offset: Int, in buffer: VimTextBuffer) -> Bool { + let lineEnd = contentEnd(ofLineAt: offset, in: buffer) + var scan = offset + while scan < lineEnd { + let ch = buffer.character(at: scan) + guard ch == 0x20 || ch == 0x09 || ch == 0x0D else { return false } + scan += 1 + } + return true } func executeOperatorOnRange(_ op: VimOperator, range proposed: NSRange, linewise: Bool, in buffer: VimTextBuffer) { @@ -39,8 +96,8 @@ extension VimEngine { let text = buffer.string(in: range) writeToActiveRegister(text: text, linewise: linewise, asDelete: true) buffer.replaceCharacters(in: range, with: "") - adjustMarksForEdit(in: range, replacementLength: 0) - buffer.setSelectedRange(NSRange(location: clampToContentPosition(range.location, in: buffer), length: 0)) + let landing = linewise ? firstNonBlankOffset(from: range.location, in: buffer) : range.location + buffer.setSelectedRange(NSRange(location: clampToContentPosition(landing, in: buffer), length: 0)) case .yank: let text = buffer.string(in: range) writeToActiveRegister(text: text, linewise: linewise, asDelete: false) @@ -48,8 +105,11 @@ extension VimEngine { case .change: let text = buffer.string(in: range) writeToActiveRegister(text: text, linewise: linewise, asDelete: true) - buffer.replaceCharacters(in: range, with: "") - adjustMarksForEdit(in: range, replacementLength: 0) + // A linewise change leaves one empty line to type on, as `cc` does. + let keepsLineBreak = linewise && NSMaxRange(range) <= buffer.length && range.length > 0 + && buffer.character(at: NSMaxRange(range) - 1) == 0x0A + let deleted = keepsLineBreak ? NSRange(location: range.location, length: range.length - 1) : range + buffer.replaceCharacters(in: deleted, with: "") buffer.setSelectedRange(NSRange(location: range.location, length: 0)) setMode(.insert) case .lowercase: @@ -122,7 +182,6 @@ extension VimEngine { } let deleteRange = NSRange(location: startRange.location, length: endOffset - startRange.location) writeToActiveRegister(text: buffer.string(in: deleteRange), linewise: true, asDelete: true) - adjustMarksForEdit(in: deleteRange, replacementLength: 0) buffer.replaceCharacters(in: deleteRange, with: "") let newPos = min(startRange.location, max(0, buffer.length - 1)) if buffer.length > 0 { @@ -160,51 +219,45 @@ extension VimEngine { && buffer.character(at: endOffset - 1) == 0x0A ? endOffset - 1 : endOffset let deleteRange = NSRange(location: startRange.location, length: deleteEnd - startRange.location) writeToActiveRegister(text: buffer.string(in: deleteRange), linewise: true, asDelete: true) - adjustMarksForEdit(in: deleteRange, replacementLength: 0) buffer.replaceCharacters(in: deleteRange, with: "") buffer.setSelectedRange(NSRange(location: startRange.location, length: 0)) setMode(.insert) } - func paste(after: Bool, in buffer: VimTextBuffer) { + // The register is read once, so a count pastes copies of the one register, and the copies go in as one run. + func paste(after: Bool, count: Int, in buffer: VimTextBuffer) { let source = activePasteRegister() guard !source.text.isEmpty else { return } - + let copies = max(1, count) let pos = buffer.selectedRange().location if source.isLinewise { - if after { - let lineRange = buffer.lineRange(forOffset: pos) - let insertPos = lineRange.location + lineRange.length - var text = source.text - let nsText = text as NSString - if nsText.length == 0 || nsText.character(at: nsText.length - 1) != 0x0A { - text += "\n" - } - buffer.replaceCharacters(in: NSRange(location: insertPos, length: 0), with: text) - buffer.setSelectedRange(NSRange(location: insertPos, length: 0)) - } else { - let lineRange = buffer.lineRange(forOffset: pos) - var text = source.text - let nsText = text as NSString - if nsText.length == 0 || nsText.character(at: nsText.length - 1) != 0x0A { - text += "\n" - } - buffer.replaceCharacters(in: NSRange(location: lineRange.location, length: 0), with: text) - buffer.setSelectedRange(NSRange(location: lineRange.location, length: 0)) - } - } else { - if after { - let insertPos = characterEnd(at: pos, in: buffer) - buffer.replaceCharacters(in: NSRange(location: insertPos, length: 0), with: source.text) - let newPos = insertPos + (source.text as NSString).length - 1 - buffer.setSelectedRange(NSRange(location: max(insertPos, newPos), length: 0)) - } else { - buffer.replaceCharacters(in: NSRange(location: pos, length: 0), with: source.text) - let newPos = pos + (source.text as NSString).length - 1 - buffer.setSelectedRange(NSRange(location: max(pos, newPos), length: 0)) + var line = source.text + if (line as NSString).character(at: (line as NSString).length - 1) != 0x0A { line += "\n" } + var text = String(repeating: line, count: copies) + let lineRange = buffer.lineRange(forOffset: pos) + var insertPos = after ? NSMaxRange(lineRange) : lineRange.location + var firstLine = insertPos + // Below a last line with no line break, the break goes before the pasted lines. + if after, insertPos == buffer.length, insertPos > lineRange.location, + buffer.character(at: insertPos - 1) != 0x0A { + text = "\n" + text.dropLast() + firstLine = insertPos + 1 } + buffer.replaceCharacters(in: NSRange(location: insertPos, length: 0), with: text) + insertPos = firstLine + buffer.setSelectedRange(NSRange(location: firstNonBlankOffset(from: insertPos, in: buffer), length: 0)) + return } + + let text = String(repeating: source.text, count: copies) + // On an empty line the caret is on the line break, and `p` puts the text before it. + let insertPos = after && pos < contentEnd(ofLineAt: pos, in: buffer) ? characterEnd(at: pos, in: buffer) : pos + buffer.replaceCharacters(in: NSRange(location: insertPos, length: 0), with: text) + let length = (text as NSString).length + // Text over several lines leaves the cursor at its start, a single line on its last character. + let landing = text.contains("\n") ? insertPos : characterStart(at: insertPos + length - 1, in: buffer) + buffer.setSelectedRange(NSRange(location: landing, length: 0)) } func deleteCharUnderCursor(_ count: Int, in buffer: VimTextBuffer) { @@ -218,7 +271,6 @@ extension VimEngine { guard end > pos else { return } let range = NSRange(location: pos, length: end - pos) writeToActiveRegister(text: buffer.string(in: range), linewise: false, asDelete: true) - adjustMarksForEdit(in: range, replacementLength: 0) noteEdit(at: pos, in: buffer) buffer.replaceCharacters(in: range, with: "") let newContentEnd = contentEnd - range.length diff --git a/apple/TablePro/Core/Vim/VimEngine+RegistersMarks.swift b/apple/TablePro/Core/Vim/VimEngine+RegistersMarks.swift index fe9796d5a2..c09092fe22 100644 --- a/apple/TablePro/Core/Vim/VimEngine+RegistersMarks.swift +++ b/apple/TablePro/Core/Vim/VimEngine+RegistersMarks.swift @@ -13,9 +13,12 @@ struct VimDocumentMarks { var lastVisualLinewise = false var lastJumpOrigin: Int? var lastInsertOffset: Int? + var markColumns: [Character: Int] = [:] + var editJournal: [VimEditRecord] = [] var isEmpty: Bool { marks.isEmpty && lastVisualStart == nil && lastVisualEnd == nil && lastJumpOrigin == nil && lastInsertOffset == nil + && editJournal.isEmpty } } @@ -27,12 +30,17 @@ extension VimEngine { lastVisualEnd: lastVisualEnd, lastVisualLinewise: lastVisualLinewise, lastJumpOrigin: lastJumpOrigin, - lastInsertOffset: lastInsertOffset + lastInsertOffset: lastInsertOffset, + markColumns: markColumns, + editJournal: editJournal ) } func restoreDocumentMarks(_ saved: VimDocumentMarks) { marks = saved.marks + markColumns = saved.markColumns + editJournal = saved.editJournal + editJournalTextLength = saved.editJournal.reduce(0) { $0 + $1.textLength } lastVisualStart = saved.lastVisualStart lastVisualEnd = saved.lastVisualEnd lastVisualLinewise = saved.lastVisualLinewise @@ -81,39 +89,32 @@ extension VimEngine { return register } + // `'` goes to the first non-blank of the mark's line and takes whole lines after an operator; `` ` `` goes to + // the mark itself. An unset mark ends the command. func jumpToMark(_ name: Character, exact: Bool, in buffer: VimTextBuffer) { - if name == "'" || name == "`" { - if let origin = lastJumpOrigin { - let originPos = buffer.selectedRange().location - let clamped = min(max(0, origin), buffer.length) - buffer.setSelectedRange(NSRange(location: clamped, length: 0)) - lastJumpOrigin = originPos - } - return + let offset: Int? + switch name { + case "'", "`": offset = lastJumpOrigin + case "<": offset = lastVisualStart + case ">": offset = lastVisualEnd + default: offset = marks[name] } - if name == "<", let start = lastVisualStart { - let originPos = buffer.selectedRange().location - buffer.setSelectedRange(NSRange(location: min(max(0, start), buffer.length), length: 0)) - lastJumpOrigin = originPos + guard let offset else { + applyMotion(to: nil, kind: .exclusive, in: buffer) return } - if name == ">", let end = lastVisualEnd { - let originPos = buffer.selectedRange().location - buffer.setSelectedRange(NSRange(location: min(max(0, end), buffer.length), length: 0)) - lastJumpOrigin = originPos - return + var clamped = min(max(0, offset), buffer.length) + if let column = markColumns[name] { + let lineStart = buffer.lineRange(forOffset: clamped).location + let lastCharacter = max(lineStart, contentEnd(ofLineAt: clamped, in: buffer) - 1) + clamped = min(lineStart + column, lastCharacter) } - guard let offset = marks[name] else { return } - let originPos = buffer.selectedRange().location - let clamped = min(max(0, offset), buffer.length) if exact { - buffer.setSelectedRange(NSRange(location: clamped, length: 0)) + applyMotion(to: clamped, kind: .exclusive, jump: true, in: buffer) } else { let lineStart = buffer.lineRange(forOffset: clamped).location - let target = firstNonBlankOffset(from: lineStart, in: buffer) - buffer.setSelectedRange(NSRange(location: target, length: 0)) + applyMotion(to: firstNonBlankOffset(from: lineStart, in: buffer), kind: .linewise, jump: true, in: buffer) } - lastJumpOrigin = originPos } func recordVisualSelection(linewise: Bool, in buffer: VimTextBuffer) { @@ -144,15 +145,255 @@ extension VimEngine { } } - func adjustMarksForEdit(in editRange: NSRange, replacementLength: Int) { - let delta = replacementLength - editRange.length - guard delta != 0 else { return } - for (key, offset) in marks { - if offset >= editRange.location + editRange.length { - marks[key] = offset + delta - } else if offset >= editRange.location { - marks[key] = editRange.location + func setMark(_ name: Character, at offset: Int, in buffer: VimTextBuffer) { + marks[name] = offset + markColumns[name] = offset - buffer.lineRange(forOffset: offset).location + } + + var positionSnapshot: VimPositionSnapshot { + VimPositionSnapshot( + marks: marks, + markColumns: markColumns, + lastJumpOrigin: lastJumpOrigin, + lastInsertOffset: lastInsertOffset, + lastVisualStart: lastVisualStart, + lastVisualEnd: lastVisualEnd + ) + } + + // Called before every edit, typed, pasted, undone or the engine's own. A mark keeps its line and column, as Vim's + // do (`:help mark-motions`): lines added or removed before it move it, a join carries it with its text, and + // removing its whole line removes a named mark. Each edit is kept with the positions from before it, so an undo or + // redo that reverses it puts them back, as Vim's undo restores its marks. Typing the same text back is not undo, + // and an undo reverses only edits, a redo only undos. + func textWillChange(in range: NSRange, with replacement: String, source: VimEditSource = .edit) { + guard let buffer else { return } + let hasPositions = !marks.isEmpty || lastJumpOrigin != nil || lastInsertOffset != nil + || lastVisualStart != nil || lastVisualEnd != nil + guard hasPositions || !editJournal.isEmpty else { return } + let removedText = buffer.string(in: range) + let before = positionSnapshot + var restored: VimPositionSnapshot? + if source != .edit, let index = reversedJournalIndex(range: range, replacement: replacement, source: source) { + restored = editJournal[index].positions + editJournalTextLength -= editJournal[index...].reduce(0) { $0 + $1.textLength } + editJournal.removeSubrange(index...) + } + let change = VimMarkChange(range: range, replacement: replacement, in: buffer) + for (name, offset) in marks { + let mapped = change.map(offset, removable: true, in: buffer) + if mapped?.keepsColumn != true { markColumns[name] = nil } + marks[name] = mapped?.offset + } + lastJumpOrigin = lastJumpOrigin.flatMap { change.map($0, removable: false, in: buffer)?.offset } + lastInsertOffset = lastInsertOffset.flatMap { + change.map($0, removable: false, isInsertionPoint: true, in: buffer)?.offset + } + lastVisualStart = lastVisualStart.flatMap { change.map($0, removable: false, in: buffer)?.offset } + lastVisualEnd = lastVisualEnd.flatMap { change.map($0, removable: false, in: buffer)?.offset } + if let restored { restorePositions(restored) } + editJournal.append(VimEditRecord( + location: range.location, + removedText: removedText, + insertedText: replacement, + positions: before, + isUndo: source == .undo + )) + // An undo step can hold a long run of typing, so the journal keeps thousands of edits, bounded by the text they + // hold rather than their number. + editJournalTextLength += editJournal.last?.textLength ?? 0 + while editJournal.count > 10_000 || editJournalTextLength > 1_000_000, let oldest = editJournal.first { + editJournalTextLength -= oldest.textLength + editJournal.removeFirst() + } + } + + // Undo reverses the newest step first, so only the newest records, folded together, can match. An editor may undo + // a run of keys, such as backspaces, as one edit, which is why more than one record may be folded. Records of the other direction are passed over: + // each is an undo of an edit already gone from the journal, so the two cancel out. + private func reversedJournalIndex(range: NSRange, replacement: String, source: VimEditSource) -> Int? { + let reversesUndo = source == .redo + var folded: VimEditRecord? + for index in editJournal.indices.reversed() where editJournal[index].isUndo == reversesUndo { + let record = editJournal[index] + var combined = record + if let next = folded { + guard let joined = record.followed(by: next) else { return nil } + combined = joined + } + if combined.isReversed(by: range, replacement: replacement) { return index } + folded = combined + } + return nil + } + + // A mark set since the reversed edit keeps its place, as Vim restores only the marks its undo step saved. + private func restorePositions(_ saved: VimPositionSnapshot) { + for (name, offset) in saved.marks { + marks[name] = offset + markColumns[name] = saved.markColumns[name] + } + lastJumpOrigin = saved.lastJumpOrigin ?? lastJumpOrigin + lastInsertOffset = saved.lastInsertOffset ?? lastInsertOffset + lastVisualStart = saved.lastVisualStart ?? lastVisualStart + lastVisualEnd = saved.lastVisualEnd ?? lastVisualEnd + } +} + +// Where the marks were before one edit. +struct VimPositionSnapshot { + var marks: [Character: Int] + var markColumns: [Character: Int] + var lastJumpOrigin: Int? + var lastInsertOffset: Int? + var lastVisualStart: Int? + var lastVisualEnd: Int? +} + +// One edit, and the positions from before it. Undo reverses edits newest first, so the reversing edit finds its +// record at the end of the journal, past any whose undo the editor folded into one step. +enum VimEditSource { + case edit, undo, redo +} + +struct VimEditRecord { + let location: Int + let removedText: String + let insertedText: String + let positions: VimPositionSnapshot + // An undo's own edit, which only a redo reverses. + let isUndo: Bool + + func isReversed(by range: NSRange, replacement: String) -> Bool { + range.location == location && range.length == (insertedText as NSString).length && replacement == removedText + } + + var textLength: Int { + (removedText as NSString).length + (insertedText as NSString).length + } + + // This edit and the next as one, when the next touches the text this one left, with this one's positions. + func followed(by next: VimEditRecord) -> VimEditRecord? { + let removed = removedText as NSString + let inserted = insertedText as NSString + let nextRemoved = next.removedText as NSString + let nextInserted = next.insertedText as NSString + let end = location + inserted.length + let nextEnd = next.location + nextRemoved.length + guard next.location <= end, nextEnd >= location else { return nil } + let before = next.location < location ? nextRemoved.substring(to: location - next.location) : "" + let after = nextEnd > end ? nextRemoved.substring(from: end - next.location) : "" + let keptHead = next.location > location ? inserted.substring(to: next.location - location) : "" + let keptTail = nextEnd < end ? inserted.substring(from: nextEnd - location) : "" + return VimEditRecord( + location: min(location, next.location), + removedText: before + (removed as String) + after, + insertedText: keptHead + (nextInserted as String) + keptTail, + positions: positions, + isUndo: isUndo + ) + } +} + +// One edit, read from the text before it, as Vim's line-based mark adjustment sees it. +@MainActor +struct VimMarkChange { + private let location: Int + private let end: Int + private let delta: Int + private let removed: [unichar] + private let inserted: [unichar] + private let insertedBreaks: Int + private let removesLineBreak: Bool + // Whole lines removed or inserted at a line start, as `dd`, `p` and `O` and their undo make. + private let isLinewise: Bool + // As many line breaks go in as come out, so every line keeps its marks, as a shift or a case change does. + private let keepsLines: Bool + private let firstLineStart: Int + // Where the line holding the end of the removed text ends, in the text before the edit. + private let endLineEnd: Int + // Where the line holding the end of the inserted text ends, before its break, once the edit is in. + private let lastLineContentEnd: Int + + init(range: NSRange, replacement: String, in buffer: VimTextBuffer) { + location = range.location + end = NSMaxRange(range) + removed = Array(buffer.string(in: range).utf16) + inserted = Array(replacement.utf16) + delta = inserted.count - removed.count + let removedBreaks = removed.filter { $0 == 0x0A }.count + insertedBreaks = inserted.filter { $0 == 0x0A }.count + removesLineBreak = removedBreaks > 0 + keepsLines = removedBreaks == insertedBreaks + let firstLine = buffer.lineRange(forOffset: range.location) + firstLineStart = firstLine.location + let removedEndsWithBreak = removed.last.map { $0 == 0x0A } ?? true + let insertedEndsWithBreak = inserted.last.map { $0 == 0x0A } ?? true + isLinewise = range.location == firstLine.location && removedEndsWithBreak && insertedEndsWithBreak + let endLine = buffer.lineRange(forOffset: end) + endLineEnd = NSMaxRange(endLine) + let endLineHasBreak = endLineEnd > endLine.location && buffer.character(at: endLineEnd - 1) == 0x0A + lastLineContentEnd = (endLineHasBreak ? endLineEnd - 1 : endLineEnd) + delta + } + + // Nil when the edit removes the line of a removable mark. `keepsColumn` is false where the mark moved onto + // another line's text, as a join moves it. + // An insertion point may sit after a line's last character; a mark sits on a character. + func map( + _ offset: Int, + removable: Bool, + isInsertionPoint: Bool = false, + in buffer: VimTextBuffer + ) -> (offset: Int, keepsColumn: Bool)? { + let lineEndSlack = isInsertionPoint ? 1 : 0 + let onFirstLine = { self.keepingColumnOnFirstLine($0, lineEndSlack: lineEndSlack) } + if offset < location { return (offset, true) } + if offset >= endLineEnd { return (offset + delta, true) } + if keepsLines { return (keepingLineAndColumn(offset, lineEndSlack: lineEndSlack), true) } + if isLinewise { + if offset >= end { return (offset + delta, true) } + return removable ? nil : (location, false) + } + if offset >= end { + return removesLineBreak ? (offset + delta, false) : (onFirstLine(offset), true) + } + if removesLineBreak { + let line = buffer.lineRange(forOffset: offset) + if line.location > firstLineStart { + if NSMaxRange(line) <= end { return removable ? nil : (location, false) } + return (end + delta, false) } } + return (onFirstLine(offset), true) + } + + // The first line keeps its start, so the offset keeps its column, up to the line's new last character. + private func keepingColumnOnFirstLine(_ offset: Int, lineEndSlack: Int) -> Int { + let firstBreak = inserted.firstIndex(of: 0x0A) + let contentEnd = firstBreak.map { location + $0 } ?? lastLineContentEnd + return min(offset, max(firstLineStart, contentEnd - 1 + lineEndSlack)) + } + + // The mark's line is the same line of the new text, at the same column up to that line's last character. + private func keepingLineAndColumn(_ offset: Int, lineEndSlack: Int) -> Int { + var line = 0 + var lineStart = firstLineStart + for index in 0.. Int { + var seen = 0 + for (index, unit) in inserted.enumerated() where unit == 0x0A { + seen += 1 + if seen == count { return index } + } + return inserted.count } } diff --git a/apple/TablePro/Core/Vim/VimEngine+Search.swift b/apple/TablePro/Core/Vim/VimEngine+Search.swift index af62ca108e..3ebe1563f8 100644 --- a/apple/TablePro/Core/Vim/VimEngine+Search.swift +++ b/apple/TablePro/Core/Vim/VimEngine+Search.swift @@ -6,43 +6,62 @@ import Foundation extension VimEngine { - func runSearch(pattern: String, forward: Bool) { - guard !pattern.isEmpty, let buffer else { return } - lastSearchPattern = pattern - lastSearchForward = forward + func runSearch(pattern: String, forward: Bool, count: Int = 1) { + guard let buffer else { return } let origin = buffer.selectedRange().location - if let target = findPattern(pattern, from: origin, forward: forward, wholeWord: false, in: buffer) { + if let target = searchTarget(pattern: pattern, forward: forward, count: count, in: buffer) { buffer.setSelectedRange(NSRange(location: target, length: 0)) lastJumpOrigin = origin } } - func searchNext(in buffer: VimTextBuffer, reverseDirection: Bool) { - guard let pattern = lastSearchPattern else { return } + // Remembers the pattern for `n` and `N`, as a search does even when nothing matches. + func searchTarget(pattern: String, forward: Bool, count: Int = 1, in buffer: VimTextBuffer) -> Int? { + guard !pattern.isEmpty else { return nil } + lastSearchPattern = pattern + lastSearchForward = forward + var position = buffer.selectedRange().location + for _ in 0.. Int? { + guard let pattern = lastSearchPattern else { return nil } let forward = reverseDirection ? !lastSearchForward : lastSearchForward - let origin = buffer.selectedRange().location - if let target = findPattern(pattern, from: origin, forward: forward, wholeWord: false, in: buffer) { - buffer.setSelectedRange(NSRange(location: target, length: 0)) - lastJumpOrigin = origin + var position = buffer.selectedRange().location + for _ in 0.. Int? { let pos = buffer.selectedRange().location - guard pos < buffer.length else { return } + guard pos < buffer.length else { return nil } var start = pos - while start > 0 && isWordChar(buffer.character(at: start - 1)) { start -= 1 } + while start > 0 && isWordCharacter(at: start - 1, in: buffer) { start -= 1 } var end = pos - while end < buffer.length && isWordChar(buffer.character(at: end)) { end += 1 } - guard end > start else { return } + while end < buffer.length && isWordCharacter(at: end, in: buffer) { end += 1 } + guard end > start else { return nil } let word = buffer.string(in: NSRange(location: start, length: end - start)) lastSearchPattern = word lastSearchForward = forward - let origin = pos - if let target = findPattern(word, from: origin, forward: forward, wholeWord: true, in: buffer) { - buffer.setSelectedRange(NSRange(location: target, length: 0)) - lastJumpOrigin = origin + var position = pos + for _ in 0..= total || !self.isWordChar(nsBuffer.character(at: afterIdx)) + let afterOk = afterIdx >= total || VimWordScanner.characterClass(at: afterIdx, in: nsBuffer) != .word return beforeOk && afterOk } @@ -95,10 +114,4 @@ extension VimEngine { } return nil } - - func isWordChar(_ ch: unichar) -> Bool { - if ch == 0x5F { return true } - guard let scalar = UnicodeScalar(ch) else { return false } - return CharacterSet.alphanumerics.contains(scalar) - } } diff --git a/apple/TablePro/Core/Vim/VimEngine+TextObjects.swift b/apple/TablePro/Core/Vim/VimEngine+TextObjects.swift index 2b02f0070d..37de0fb192 100644 --- a/apple/TablePro/Core/Vim/VimEngine+TextObjects.swift +++ b/apple/TablePro/Core/Vim/VimEngine+TextObjects.swift @@ -12,12 +12,18 @@ extension VimEngine { pendingOperator = nil return true } + // A paragraph is whole lines, every other object characters, and Visual mode takes the object's kind. + let linewise = key == "p" if mode.isVisual { - buffer.setSelectedRange(range) + // The object's start becomes Visual's anchor and its end the cursor, so the next motion extends it. + guard range.length > 0 else { return true } + if linewise != mode.isVisualLinewise { setMode(.visual(linewise: linewise)) } + visualAnchor = range.location + updateVisualSelection(cursorPos: NSMaxRange(range) - 1, linewise: linewise, in: buffer) return true } if let op = pendingOperator { - executeOperatorOnRange(op, range: range, linewise: false, in: buffer) + executeOperatorOnRange(op, range: range, linewise: linewise, in: buffer) pendingOperator = nil } return true @@ -41,20 +47,22 @@ extension VimEngine { func wordObject(at cursor: Int, bigWord: Bool, around: Bool, in buffer: VimTextBuffer) -> NSRange? { guard buffer.length > 0 else { return nil } - let pos = min(max(0, cursor), buffer.length - 1) - let classifier: (unichar) -> Int = { ch in - if ch == 0x20 || ch == 0x09 || ch == 0x0A || ch == 0x0D { return 0 } - if bigWord { return 1 } - if ch == 0x5F { return 1 } - if let scalar = UnicodeScalar(ch), CharacterSet.alphanumerics.contains(scalar) { return 1 } - return 2 + let pos = characterStart(at: min(max(0, cursor), buffer.length - 1), in: buffer) + let classOf: (Int) -> VimWordScanner.CharacterClass = { offset in + let cls = self.wordClass(at: offset, in: buffer) + return bigWord && cls != .whitespace ? .word : cls } - let startClass = classifier(buffer.character(at: pos)) + let startClass = classOf(pos) var start = pos - while start > 0 && classifier(buffer.character(at: start - 1)) == startClass { start -= 1 } - var end = pos - while end < buffer.length - 1 && classifier(buffer.character(at: end + 1)) == startClass { end += 1 } - var rangeEnd = end + 1 + while start > 0 { + let previous = characterStart(at: start - 1, in: buffer) + guard classOf(previous) == startClass else { break } + start = previous + } + var rangeEnd = characterEnd(at: pos, in: buffer) + while rangeEnd < buffer.length && classOf(rangeEnd) == startClass { + rangeEnd = characterEnd(at: rangeEnd, in: buffer) + } if around { var trail = rangeEnd while trail < buffer.length { @@ -219,32 +227,27 @@ extension VimEngine { return NSRange(location: oe + 1, length: closeStart - oe - 1) } + // Whole lines: the run of paragraph or blank lines at the cursor. `ap` adds the blank lines after a paragraph, + // or the paragraph after blank lines, and with nothing after it the blank lines before. func paragraphObject(at cursor: Int, around: Bool, in buffer: VimTextBuffer) -> NSRange? { - let (currentLine, _) = buffer.lineAndColumn(forOffset: cursor) + let lineCount = buffer.lineCount + let currentLine = buffer.lineAndColumn(forOffset: cursor).line + let blank = lineIsWhite(currentLine, in: buffer) var startLine = currentLine - while startLine > 0 && !lineIsBlank(startLine - 1, in: buffer) { - startLine -= 1 - } + while startLine > 0 && lineIsWhite(startLine - 1, in: buffer) == blank { startLine -= 1 } var endLine = currentLine - while endLine < buffer.lineCount - 1 && !lineIsBlank(endLine + 1, in: buffer) { - endLine += 1 - } - let start = buffer.offset(forLine: startLine, column: 0) - let lastContentLineRange = buffer.lineRange(forOffset: buffer.offset(forLine: endLine, column: 0)) - var end = lastContentLineRange.location + lastContentLineRange.length - if !around && end > start { - end -= 1 - } + while endLine < lineCount - 1 && lineIsWhite(endLine + 1, in: buffer) == blank { endLine += 1 } if around { - var trailing = endLine - while trailing < buffer.lineCount - 1 && lineIsBlank(trailing + 1, in: buffer) { - trailing += 1 - } - if trailing > endLine { - let trailingRange = buffer.lineRange(forOffset: buffer.offset(forLine: trailing, column: 0)) - end = trailingRange.location + trailingRange.length + var next = endLine + while next < lineCount - 1 && lineIsWhite(next + 1, in: buffer) != blank { next += 1 } + if next > endLine { + endLine = next + } else if !blank { + while startLine > 0 && lineIsWhite(startLine - 1, in: buffer) { startLine -= 1 } } } + let start = buffer.offset(forLine: startLine, column: 0) + let end = NSMaxRange(buffer.lineRange(forOffset: buffer.offset(forLine: endLine, column: 0))) return NSRange(location: start, length: end - start) } } diff --git a/apple/TablePro/Core/Vim/VimEngine+VisualMode.swift b/apple/TablePro/Core/Vim/VimEngine+VisualMode.swift index 1f3a12c37b..758de77f87 100644 --- a/apple/TablePro/Core/Vim/VimEngine+VisualMode.swift +++ b/apple/TablePro/Core/Vim/VimEngine+VisualMode.swift @@ -20,6 +20,11 @@ extension VimEngine { if char == "\u{1B}" { return true } return executeTextObject(char, around: pendingTextObjectAround, in: buffer) } + if pendingRegisterSelect { + pendingRegisterSelect = false + if char != "\u{1B}" { selectedRegister = char == "\"" ? nil : char } + return true + } let isLinewise: Bool if case .visual(let lw) = mode { isLinewise = lw } else { isLinewise = false } @@ -43,6 +48,7 @@ extension VimEngine { switch char { case "\u{1B}": + selectedRegister = nil recordVisualSelection(linewise: isLinewise, in: buffer) setMode(.normal) let pos = buffer.selectedRange().location @@ -132,8 +138,12 @@ extension VimEngine { setMode(.insert) return true + case "\"": + pendingRegisterSelect = true + return true + case "p", "P": - pasteOverVisualSelection(in: buffer) + pasteOverVisualSelection(keepingRegister: char == "P", linewise: isLinewise, in: buffer) return true case "d", "x": @@ -141,7 +151,6 @@ extension VimEngine { recordVisualSelection(linewise: isLinewise, in: buffer) if sel.length > 0 { writeToActiveRegister(text: buffer.string(in: sel), linewise: isLinewise, asDelete: true) - adjustMarksForEdit(in: sel, replacementLength: 0) buffer.replaceCharacters(in: sel, with: "") } setMode(.normal) @@ -276,11 +285,16 @@ extension VimEngine { setMode(.normal) } - func pasteOverVisualSelection(in buffer: VimTextBuffer) { + // `p` puts the text it replaces in the unnamed register, `P` leaves the registers as they were. + func pasteOverVisualSelection(keepingRegister: Bool, linewise: Bool, in buffer: VimTextBuffer) { let sel = buffer.selectedRange() - let text = register.text + let text = activePasteRegister().text guard sel.length > 0 else { setMode(.normal); return } + let replaced = buffer.string(in: sel) buffer.replaceCharacters(in: sel, with: text) + if !keepingRegister { + writeToActiveRegister(text: replaced, linewise: linewise, asDelete: true) + } let newPos = sel.location + (text as NSString).length - 1 buffer.setSelectedRange(NSRange(location: max(sel.location, newPos), length: 0)) setMode(.normal) diff --git a/apple/TablePro/Core/Vim/VimEngine.swift b/apple/TablePro/Core/Vim/VimEngine.swift index b841a6d271..bbc486345a 100644 --- a/apple/TablePro/Core/Vim/VimEngine.swift +++ b/apple/TablePro/Core/Vim/VimEngine.swift @@ -38,6 +38,9 @@ enum VimDotKind { case replaceChar(char: Character, count: Int) } +// `:help exclusive`, `:help inclusive`, `:help linewise`. +enum VimMotionKind { case exclusive, inclusive, linewise } + enum VimMacroPendingKind { case recordTarget, replayTarget } enum VimBracketPending { case openBracket, closeBracket } enum VimScreenPosition { case top, middle, bottom } @@ -101,6 +104,12 @@ final class VimEngine { var visualAnchor: Int = 0 var lastInsertOffset: Int? var replaceModeEdits: [VimReplaceModeEdit] = [] + var searchCount: Int = 1 + // The column each named mark was set at, kept past the end of a line that shrinks, as Vim keeps it. + var markColumns: [Character: Int] = [:] + // Recent edits with the positions from before each, so undoing one puts them back. + var editJournal: [VimEditRecord] = [] + var editJournalTextLength = 0 var buffer: VimTextBuffer? @@ -123,6 +132,8 @@ final class VimEngine { consumed = processReplace(char) case .visual: consumed = processVisual(char, shift: shift) + // A register named in Visual mode belongs to the command that ends it, used or not. + if !mode.isVisual { selectedRegister = nil } case .commandLine(let commandBuffer): consumed = processCommandLine(char, buffer: commandBuffer) } @@ -149,11 +160,37 @@ final class VimEngine { } func reset() { + cancelPendingCommand() + mode = .normal + } + + // Escape, leaving the command line or a motion that cannot move ends the whole command, so no part of it + // reaches the next key. + func cancelPendingCommand() { pendingOperator = nil countPrefix = 0 operatorCount = 0 pendingG = false - mode = .normal + pendingFindChar = nil + pendingReplaceChar = false + pendingMarkSet = false + pendingMarkJumpExact = nil + pendingRegisterSelect = false + selectedRegister = nil + pendingReplaceCharForVisual = false + pendingZ = false + pendingTextObject = false + pendingMacroTarget = nil + pendingMacroCount = 1 + pendingBracket = nil + searchCount = 1 + } + + // A key that still waits for the rest of its command, not counting a count or a register already typed. + var hasPendingCommand: Bool { + pendingOperator != nil || pendingG || pendingFindChar != nil || pendingReplaceChar || pendingMarkSet + || pendingMarkJumpExact != nil || pendingRegisterSelect || pendingZ || pendingTextObject + || pendingMacroTarget != nil || pendingBracket != nil } func setMode(_ newMode: VimMode) { diff --git a/apple/TablePro/Core/Vim/VimMode.swift b/apple/TablePro/Core/Vim/VimMode.swift index 543cc0ece3..deb6da82f9 100644 --- a/apple/TablePro/Core/Vim/VimMode.swift +++ b/apple/TablePro/Core/Vim/VimMode.swift @@ -1,11 +1,3 @@ -// -// VimMode.swift -// TablePro -// -// Vim editing modes for the SQL editor -// - -/// Vim editing modes enum VimMode: Equatable { case normal case insert @@ -13,7 +5,6 @@ enum VimMode: Equatable { case visual(linewise: Bool) case commandLine(buffer: String) - /// Display label for the mode indicator var displayLabel: String { switch self { case .normal: return "NORMAL" @@ -24,7 +15,7 @@ enum VimMode: Equatable { } } - /// Whether this mode passes text input through to the text view (insert or replace) + // Insert and Replace leave typed text to the text view. var isInsert: Bool { switch self { case .insert, .replace: return true @@ -32,12 +23,16 @@ enum VimMode: Equatable { } } - /// Whether this mode is a visual selection mode var isVisual: Bool { if case .visual = self { return true } return false } + var isVisualLinewise: Bool { + if case .visual(let linewise) = self { return linewise } + return false + } + var isCommandLine: Bool { if case .commandLine = self { return true } return false diff --git a/apple/TablePro/Core/Vim/VimTextBufferAdapter.swift b/apple/TablePro/Core/Vim/VimTextBufferAdapter.swift index 53ee9d9c44..99ec98c957 100644 --- a/apple/TablePro/Core/Vim/VimTextBufferAdapter.swift +++ b/apple/TablePro/Core/Vim/VimTextBufferAdapter.swift @@ -92,52 +92,12 @@ final class VimTextBufferAdapter: VimTextBuffer { func wordBoundary(forward: Bool, from offset: Int) -> Int { guard let text else { return offset } - guard text.length > 0 else { return 0 } - - if forward { - var pos = min(offset, text.length - 1) - let startClass = charClass(text.character(at: pos)) - if startClass == .whitespace { - while pos < text.length && charClass(text.character(at: pos)) == .whitespace { - pos += 1 - } - } else { - while pos < text.length && charClass(text.character(at: pos)) == startClass { - pos += 1 - } - while pos < text.length && charClass(text.character(at: pos)) == .whitespace { - pos += 1 - } - } - return min(pos, text.length) - } else { - var pos = min(offset, text.length) - if pos > 0 { pos -= 1 } - while pos > 0 && charClass(text.character(at: pos)) == .whitespace { - pos -= 1 - } - let cls = charClass(text.character(at: pos)) - while pos > 0 && charClass(text.character(at: pos - 1)) == cls { - pos -= 1 - } - return max(0, pos) - } + return VimWordScanner.wordBoundary(forward: forward, from: offset, in: text) } func wordEnd(from offset: Int) -> Int { guard let text else { return offset } - guard text.length > 0 else { return 0 } - - var pos = min(offset + 1, text.length - 1) - while pos < text.length && charClass(text.character(at: pos)) == .whitespace { - pos += 1 - } - guard pos < text.length else { return text.length - 1 } - let cls = charClass(text.character(at: pos)) - while pos < text.length - 1 && charClass(text.character(at: pos + 1)) == cls { - pos += 1 - } - return min(pos, text.length - 1) + return VimWordScanner.wordEnd(from: offset, in: text) } func selectedRange() -> NSRange { @@ -194,92 +154,22 @@ final class VimTextBufferAdapter: VimTextBuffer { func wordEndBackward(from offset: Int) -> Int { guard let text else { return 0 } - guard text.length > 0 else { return 0 } - var pos = min(max(0, offset), text.length - 1) - if pos > 0 { pos -= 1 } - if charClass(text.character(at: pos)) == .whitespace { - while pos > 0 && charClass(text.character(at: pos)) == .whitespace { - pos -= 1 - } - return pos - } - let cls = charClass(text.character(at: pos)) - while pos > 0 && charClass(text.character(at: pos - 1)) == cls { - pos -= 1 - } - guard pos > 0 else { return 0 } - pos -= 1 - while pos > 0 && charClass(text.character(at: pos)) == .whitespace { - pos -= 1 - } - return pos + return VimWordScanner.wordEndBackward(from: offset, in: text) } func bigWordBoundary(forward: Bool, from offset: Int) -> Int { guard let text else { return offset } - guard text.length > 0 else { return 0 } - if forward { - var pos = min(offset, text.length - 1) - let startWS = isWhitespace(text.character(at: pos)) - if startWS { - while pos < text.length && isWhitespace(text.character(at: pos)) { - pos += 1 - } - } else { - while pos < text.length && !isWhitespace(text.character(at: pos)) { - pos += 1 - } - while pos < text.length && isWhitespace(text.character(at: pos)) { - pos += 1 - } - } - return min(pos, text.length) - } - var pos = min(offset, text.length) - if pos > 0 { pos -= 1 } - while pos > 0 && isWhitespace(text.character(at: pos)) { - pos -= 1 - } - while pos > 0 && !isWhitespace(text.character(at: pos - 1)) { - pos -= 1 - } - return max(0, pos) + return VimWordScanner.bigWordBoundary(forward: forward, from: offset, in: text) } func bigWordEnd(from offset: Int) -> Int { guard let text else { return offset } - guard text.length > 0 else { return 0 } - var pos = min(offset + 1, text.length - 1) - while pos < text.length && isWhitespace(text.character(at: pos)) { - pos += 1 - } - guard pos < text.length else { return text.length - 1 } - while pos < text.length - 1 && !isWhitespace(text.character(at: pos + 1)) { - pos += 1 - } - return min(pos, text.length - 1) + return VimWordScanner.bigWordEnd(from: offset, in: text) } func bigWordEndBackward(from offset: Int) -> Int { guard let text else { return 0 } - guard text.length > 0 else { return 0 } - var pos = min(max(0, offset), text.length - 1) - if pos > 0 { pos -= 1 } - if isWhitespace(text.character(at: pos)) { - while pos > 0 && isWhitespace(text.character(at: pos)) { - pos -= 1 - } - return pos - } - while pos > 0 && !isWhitespace(text.character(at: pos - 1)) { - pos -= 1 - } - guard pos > 0 else { return 0 } - pos -= 1 - while pos > 0 && isWhitespace(text.character(at: pos)) { - pos -= 1 - } - return pos + return VimWordScanner.bigWordEndBackward(from: offset, in: text) } func matchingBracket(at offset: Int) -> Int? { @@ -380,23 +270,6 @@ final class VimTextBufferAdapter: VimTextBuffer { // MARK: - Helpers - private enum CharClass { - case word, punctuation, whitespace - } - - private func charClass(_ char: unichar) -> CharClass { - if isWhitespace(char) { return .whitespace } - guard let scalar = UnicodeScalar(char) else { return .punctuation } - if CharacterSet.alphanumerics.contains(scalar) || char == 0x5F { - return .word - } - return .punctuation - } - - private func isWhitespace(_ char: unichar) -> Bool { - char == 0x20 || char == 0x09 || char == 0x0A || char == 0x0D - } - private func isLineBreak(_ char: unichar) -> Bool { char == 0x0A || char == 0x0D } diff --git a/apple/TablePro/Core/Vim/VimWordScanner.swift b/apple/TablePro/Core/Vim/VimWordScanner.swift new file mode 100644 index 0000000000..029130dc23 --- /dev/null +++ b/apple/TablePro/Core/Vim/VimWordScanner.swift @@ -0,0 +1,125 @@ +import Foundation + +// Word and WORD scans for Vim's motions. They step by composed character sequence and class each one by its first +// scalar, so a variation selector or a combining mark after a symbol never splits it into two words. +enum VimWordScanner { + enum CharacterClass { + case word, punctuation, whitespace + } + + static func characterClass(lead: unichar, trail: unichar?) -> CharacterClass { + if lead == 0x20 || lead == 0x09 || lead == 0x0A || lead == 0x0D { return .whitespace } + if lead == 0x5F { return .word } + var value = UInt32(lead) + if UTF16.isLeadSurrogate(lead), let trail, UTF16.isTrailSurrogate(trail) { + value = 0x10000 + ((UInt32(lead) - 0xD800) << 10) + (UInt32(trail) - 0xDC00) + } + guard let scalar = Unicode.Scalar(value) else { return .punctuation } + return CharacterSet.alphanumerics.contains(scalar) ? .word : .punctuation + } + + static func characterClass(at offset: Int, in text: NSString) -> CharacterClass { + let base = characterStart(at: offset, in: text) + let lead = text.character(at: base) + return characterClass(lead: lead, trail: base + 1 < text.length ? text.character(at: base + 1) : nil) + } + + static func wordBoundary(forward: Bool, from offset: Int, in text: NSString) -> Int { + scanBoundary(forward: forward, from: offset, in: text) { characterClass(at: $0, in: text) } + } + + static func bigWordBoundary(forward: Bool, from offset: Int, in text: NSString) -> Int { + scanBoundary(forward: forward, from: offset, in: text) { bigClass(at: $0, in: text) } + } + + static func wordEnd(from offset: Int, in text: NSString) -> Int { + scanEnd(from: offset, in: text) { characterClass(at: $0, in: text) } + } + + static func bigWordEnd(from offset: Int, in text: NSString) -> Int { + scanEnd(from: offset, in: text) { bigClass(at: $0, in: text) } + } + + static func wordEndBackward(from offset: Int, in text: NSString) -> Int { + scanEndBackward(from: offset, in: text) { characterClass(at: $0, in: text) } + } + + static func bigWordEndBackward(from offset: Int, in text: NSString) -> Int { + scanEndBackward(from: offset, in: text) { bigClass(at: $0, in: text) } + } + + // MARK: - Scans + + private static func bigClass(at offset: Int, in text: NSString) -> CharacterClass { + characterClass(at: offset, in: text) == .whitespace ? .whitespace : .word + } + + private static func characterStart(at offset: Int, in text: NSString) -> Int { + // Below U+0300 a unit after another such unit starts its own character, which skips the lookup for ASCII. + if text.character(at: offset) < 0x300, offset == 0 || text.character(at: offset - 1) < 0x300 { + return offset + } + return text.rangeOfComposedCharacterSequence(at: offset).location + } + + private static func next(_ offset: Int, in text: NSString) -> Int { + NSMaxRange(text.rangeOfComposedCharacterSequence(at: offset)) + } + + private static func previous(_ offset: Int, in text: NSString) -> Int { + characterStart(at: offset - 1, in: text) + } + + private static func scanBoundary( + forward: Bool, + from offset: Int, + in text: NSString, + classOf: (Int) -> CharacterClass + ) -> Int { + guard text.length > 0 else { return 0 } + if forward { + var pos = characterStart(at: min(max(0, offset), text.length - 1), in: text) + let startClass = classOf(pos) + if startClass != .whitespace { + while pos < text.length && classOf(pos) == startClass { pos = next(pos, in: text) } + } + while pos < text.length && classOf(pos) == .whitespace { pos = next(pos, in: text) } + return min(pos, text.length) + } + var pos = min(max(0, offset), text.length) + if pos > 0 { pos = previous(pos, in: text) } + while pos > 0 && classOf(pos) == .whitespace { pos = previous(pos, in: text) } + let cls = classOf(pos) + while pos > 0 && classOf(previous(pos, in: text)) == cls { pos = previous(pos, in: text) } + return pos + } + + // The start of the last character of the next word. An offset below 0 starts at the first character, so the + // word under the caret counts. + private static func scanEnd(from offset: Int, in text: NSString, classOf: (Int) -> CharacterClass) -> Int { + guard text.length > 0 else { return 0 } + let last = characterStart(at: text.length - 1, in: text) + var pos = offset < 0 ? 0 : min(next(min(offset, text.length - 1), in: text), last) + while pos < text.length && classOf(pos) == .whitespace { pos = next(pos, in: text) } + guard pos < text.length else { return last } + let cls = classOf(pos) + while next(pos, in: text) < text.length && classOf(next(pos, in: text)) == cls { pos = next(pos, in: text) } + return pos + } + + private static func scanEndBackward(from offset: Int, in text: NSString, classOf: (Int) -> CharacterClass) -> Int { + guard text.length > 0 else { return 0 } + var pos = characterStart(at: min(max(0, offset), text.length - 1), in: text) + if pos > 0 { pos = previous(pos, in: text) } + if classOf(pos) == .whitespace { + while pos > 0 && classOf(pos) == .whitespace { pos = previous(pos, in: text) } + return pos + } + let cls = classOf(pos) + while pos > 0 && classOf(previous(pos, in: text)) == cls { pos = previous(pos, in: text) } + guard pos > 0 else { return 0 } + pos = previous(pos, in: text) + while pos > 0 && classOf(pos) == .whitespace { pos = previous(pos, in: text) } + return pos + } +} diff --git a/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift b/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift index 24fa269596..816b4b1399 100644 --- a/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift +++ b/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift @@ -250,6 +250,14 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie } } + // Marks move with typed, pasted and undone text, which never passes through the Vim engine. + func textView(_ textView: TextView, willReplaceContentsIn range: NSRange, with string: String) { + guard let vimEngine else { return } + let undoManager = textView.undoManager + let source: VimEditSource = undoManager?.isUndoing == true ? .undo : undoManager?.isRedoing == true ? .redo : .edit + vimEngine.textWillChange(in: range, with: string, source: source) + } + func textView(_ textView: TextView, didReplaceContentsIn range: NSRange, with string: String) { vimEngine?.invalidateLineCache() foldPreview.dismiss() diff --git a/apple/TableProTests/Core/Vim/VimEngineCommandLineTests.swift b/apple/TableProTests/Core/Vim/VimEngineCommandLineTests.swift index 38ae0ad925..4cfe26b51f 100644 --- a/apple/TableProTests/Core/Vim/VimEngineCommandLineTests.swift +++ b/apple/TableProTests/Core/Vim/VimEngineCommandLineTests.swift @@ -226,4 +226,61 @@ final class VimEngineCommandLineTests { #expect(engine.mode.displayLabel == ":wq", "displayLabel for commandLine should be the literal buffer text") } + + // MARK: - The command line after an operator + + @Test("Escape on the command line drops the operator typed before it") + func escapeFromCommandLineDropsTheOperator() { + keys("d/") + escape() + keys("w") + #expect(buffer.text == "hello world\nsecond line\nthird line\n") + #expect(buffer.selectedRange().location == 6) + } + + @Test("Backspacing out of the command line drops the operator") + func backspaceOutOfCommandLineDropsTheOperator() { + keys("d/x") + backspace() + backspace() + #expect(engine.mode == .normal) + keys("w") + #expect(buffer.text == "hello world\nsecond line\nthird line\n") + } + + @Test("d/ with a pattern deletes up to the match") + func operatorSearchDeletesUpToTheMatch() { + keys("d/sec") + enter() + #expect(buffer.text == "second line\nthird line\n") + #expect(engine.register.text == "hello world\n") + #expect(engine.mode == .normal) + } + + @Test("A count before d/ deletes up to that many matches") + func countedOperatorSearch() { + buffer = VimTextBufferMock(text: "x one x two x three x\n") + engine = VimEngine(buffer: buffer) + keys("2d/x") + enter() + #expect(buffer.text == "x three x\n") + } + + @Test("d/ with no match deletes nothing and ends the command") + func operatorSearchWithoutMatchEndsTheCommand() { + keys("d/zzz") + enter() + keys("w") + #expect(buffer.text == "hello world\nsecond line\nthird line\n") + #expect(buffer.selectedRange().location == 6) + } + + @Test("An ex command after an operator runs and drops the operator") + func exCommandDropsTheOperator() { + keys("d:w") + enter() + #expect(dispatchedCommand == "w") + keys("w") + #expect(buffer.text == "hello world\nsecond line\nthird line\n") + } } diff --git a/apple/TableProTests/Core/Vim/VimEngineComposedCharacterTests.swift b/apple/TableProTests/Core/Vim/VimEngineComposedCharacterTests.swift index c86aa02130..4a88ca19a3 100644 --- a/apple/TableProTests/Core/Vim/VimEngineComposedCharacterTests.swift +++ b/apple/TableProTests/Core/Vim/VimEngineComposedCharacterTests.swift @@ -7,6 +7,7 @@ import Testing private let thumbsUp = "\u{1F44D}" private let family = "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}" private let accented = "e\u{301}" +private let heart = "\u{2764}\u{FE0F}" private let composedCharacters = [thumbsUp, family, accented] private func units(_ text: String) -> Int { @@ -575,5 +576,42 @@ extension GlobalStateSuites { #expect(adapter.selectedRange().location == 30) } } + + // MARK: - Word motions over a symbol with a variation selector + + @Test + func wStepsOverASymbolWithAVariationSelector() { + let session = Session("\(heart) x\n", caret: 0) + session.press("w") + #expect(session.caret == units(heart) + 1) + } + + @Test + func eStepsOverASymbolWithAVariationSelector() { + let session = Session("\(heart) xy\n", caret: 0) + session.press("e") + #expect(session.caret == units(heart) + 2) + } + + @Test + func bStepsBackOverASymbolWithAVariationSelector() { + let session = Session("ab \(heart)\(heart) x\n", caret: 3 + 2 * units(heart) + 1) + session.press("b") + #expect(session.caret == 3) + } + + @Test + func starFindsTheWordAfterASymbolWithAVariationSelector() { + let session = Session("\(heart)foo \(heart)foo\n", caret: units(heart)) + session.press("*") + #expect(session.caret == 2 * units(heart) + 4) + } + + @Test + func innerWordBesideASymbolWithAVariationSelectorLeavesTheSymbol() { + let session = Session("\(heart)x\n", caret: units(heart)) + session.press("diw") + #expect(session.text == "\(heart)\n") + } } } diff --git a/apple/TableProTests/Core/Vim/VimEngineCountPrefixTests.swift b/apple/TableProTests/Core/Vim/VimEngineCountPrefixTests.swift index a24a558663..ea70136bf6 100644 --- a/apple/TableProTests/Core/Vim/VimEngineCountPrefixTests.swift +++ b/apple/TableProTests/Core/Vim/VimEngineCountPrefixTests.swift @@ -194,4 +194,41 @@ final class VimEngineCountPrefixTests { let consumed = engine.process("3", shift: false) #expect(!consumed, "Digits in insert mode must pass through to the text view") } + + // MARK: - A count or register the command does not use + + @Test("A count before a command that takes none is dropped") + func unusedCountIsDropped() { + buffer = VimTextBufferMock(text: "abcdef\n") + engine = VimEngine(buffer: buffer) + keys("3max") + #expect(buffer.text == "bcdef\n") + } + + @Test("A register before a motion is dropped with it") + func registerBeforeAMotionIsDropped() { + buffer = VimTextBufferMock(text: "one two three\n") + engine = VimEngine(buffer: buffer) + keys("\"awyw") + #expect(engine.namedRegisters["a"] == nil) + #expect(engine.register.text == "two ") + } + + @Test("Escape drops a register typed before it") + func escapeDropsTheRegister() { + buffer = VimTextBufferMock(text: "one two\n") + engine = VimEngine(buffer: buffer) + keys("\"a\u{1B}yw") + #expect(engine.namedRegisters["a"] == nil) + #expect(engine.register.text == "one ") + } + + @Test("Escape drops a count and an operator") + func escapeDropsCountAndOperator() { + buffer = VimTextBufferMock(text: "one two three four\n") + engine = VimEngine(buffer: buffer) + keys("2d\u{1B}w") + #expect(buffer.text == "one two three four\n") + #expect(buffer.selectedRange().location == 4) + } } diff --git a/apple/TableProTests/Core/Vim/VimEngineFindCharTests.swift b/apple/TableProTests/Core/Vim/VimEngineFindCharTests.swift index d2449a1838..a6c743dd67 100644 --- a/apple/TableProTests/Core/Vim/VimEngineFindCharTests.swift +++ b/apple/TableProTests/Core/Vim/VimEngineFindCharTests.swift @@ -309,4 +309,61 @@ final class VimEngineFindCharTests { keys("l") #expect(pos == 1, "After Escape during f, next key should run as normal command") } + + // MARK: - A cancelled or failed find ends the command + + @Test("Escape after df drops the operator, so the next w only moves") + func escapeAfterOperatorFindDropsTheOperator() { + buffer.setSelectedRange(NSRange(location: 0, length: 0)) + keys("df\u{1B}w") + #expect(buffer.text == "hello world foo bar\nsecond line\n") + #expect(pos == 6) + } + + @Test("A failed df drops the operator") + func failedOperatorFindDropsTheOperator() { + buffer.setSelectedRange(NSRange(location: 0, length: 0)) + keys("dfzw") + #expect(buffer.text == "hello world foo bar\nsecond line\n") + #expect(pos == 6) + } + + @Test("A failed d; drops the operator") + func failedRepeatFindDropsTheOperator() { + buffer.setSelectedRange(NSRange(location: 0, length: 0)) + keys("fbd;w") + #expect(buffer.text == "hello world foo bar\nsecond line\n") + #expect(pos == 20) + } + + @Test("d; with no find to repeat drops the operator") + func repeatFindWithNothingToRepeatDropsTheOperator() { + buffer = VimTextBufferMock(text: "one two three\n") + engine = VimEngine(buffer: buffer) + keys("d;w") + #expect(buffer.text == "one two three\n") + #expect(pos == 4) + } + + @Test("dF stops short of the character under the cursor") + func dCapitalFIsExclusive() { + buffer = VimTextBufferMock(text: "abcdef\n") + engine = VimEngine(buffer: buffer) + buffer.setSelectedRange(NSRange(location: 4, length: 0)) + keys("d") + key("F", shift: true) + keys("b") + #expect(buffer.text == "aef\n") + } + + @Test("dT keeps the target and the character under the cursor") + func dCapitalTIsExclusive() { + buffer = VimTextBufferMock(text: "abcdef\n") + engine = VimEngine(buffer: buffer) + buffer.setSelectedRange(NSRange(location: 4, length: 0)) + keys("d") + key("T", shift: true) + keys("b") + #expect(buffer.text == "abef\n") + } } diff --git a/apple/TableProTests/Core/Vim/VimEngineInsertEntryTests.swift b/apple/TableProTests/Core/Vim/VimEngineInsertEntryTests.swift index 1e94fa94c1..3f66761eb1 100644 --- a/apple/TableProTests/Core/Vim/VimEngineInsertEntryTests.swift +++ b/apple/TableProTests/Core/Vim/VimEngineInsertEntryTests.swift @@ -352,4 +352,16 @@ final class VimEngineInsertEntryTests { escape() #expect(capturedMode == .normal) } + + // MARK: - a on an empty line + + @Test("a on an empty line inserts on that line") + func appendOnAnEmptyLineStaysOnIt() { + buffer = VimTextBufferMock(text: "one\n\ntwo\n") + engine = VimEngine(buffer: buffer) + buffer.setSelectedRange(NSRange(location: 4, length: 0)) + keys("a") + #expect(engine.mode == .insert) + #expect(pos == 4) + } } diff --git a/apple/TableProTests/Core/Vim/VimEngineMarksAndRegistersTests.swift b/apple/TableProTests/Core/Vim/VimEngineMarksAndRegistersTests.swift index 23e7f2c96a..afa5542751 100644 --- a/apple/TableProTests/Core/Vim/VimEngineMarksAndRegistersTests.swift +++ b/apple/TableProTests/Core/Vim/VimEngineMarksAndRegistersTests.swift @@ -18,6 +18,7 @@ final class VimEngineMarksAndRegistersTests { init() { buffer = VimTextBufferMock(text: "hello world\nsecond line\nthird line\n") engine = VimEngine(buffer: buffer) + buffer.editObserver = engine } private func keys(_ chars: String) { @@ -200,4 +201,319 @@ final class VimEngineMarksAndRegistersTests { #expect(buffer.text.contains("hello world\nsecond line\nhello world\nsecond line\n") == true, "Uppercase register should append to lowercase counterpart") } + + // MARK: - Marks follow edits made outside the engine + + // Insert mode leaves typing to the text view, which puts the text at the caret. + private func typeInTextView(_ text: String) { + buffer.replaceCharacters(in: buffer.selectedRange(), with: text) + } + + @Test("A line typed above a mark moves the mark down with its line") + func lineTypedAboveMovesTheMark() { + buffer.setSelectedRange(NSRange(location: 25, length: 0)) + keys("magg") + key("O", shift: true) + typeInTextView("new") + key("\u{1B}") + keys("`a") + #expect(pos == 29) + } + + @Test("Text typed before a mark on its line keeps the mark's column") + func textTypedOnTheMarkedLineKeepsTheColumn() { + buffer.setSelectedRange(NSRange(location: 6, length: 0)) + keys("ma0i") + typeInTextView("XX") + key("\u{1B}") + keys("`a") + #expect(pos == 6) + } + + @Test("A line pasted above a mark moves the mark down") + func linePastedAboveMovesTheMark() { + buffer.setSelectedRange(NSRange(location: 25, length: 0)) + keys("maggyy") + key("P", shift: true) + keys("`a") + #expect(pos == 37) + } + + @Test("A line brought back above a mark, as undo does, moves the mark down") + func lineRestoredAboveMovesTheMark() { + keys("dd") + buffer.setSelectedRange(NSRange(location: 13, length: 0)) + keys("ma") + buffer.replaceCharacters(in: NSRange(location: 0, length: 0), with: "hello world\n") + buffer.setSelectedRange(NSRange(location: 0, length: 0)) + keys("`a") + #expect(pos == 25) + } + + @Test("Deleting the marked line removes the mark") + func deletingTheMarkedLineRemovesTheMark() { + buffer.setSelectedRange(NSRange(location: 13, length: 0)) + keys("madd") + #expect(engine.marks["a"] == nil) + } + + @Test("Shifting the marked line keeps the mark on its line and column") + func shiftKeepsTheMark() { + buffer.setSelectedRange(NSRange(location: 6, length: 0)) + keys("ma>>`a") + #expect(buffer.text == " hello world\nsecond line\nthird line\n") + #expect(pos == 6) + } + + @Test("Undoing the delete of a marked line brings the mark back") + func undoingTheDeleteRestoresTheMark() { + buffer.setSelectedRange(NSRange(location: 13, length: 0)) + keys("madd") + buffer.replayUndo(in: NSRange(location: 12, length: 0), with: "second line\n") + buffer.setSelectedRange(NSRange(location: 0, length: 0)) + keys("`a") + #expect(pos == 13) + } + + @Test("Undoing the delete brings the mark back over one set since, as Vim does") + func undoingTheDeleteRestoresTheMarkOverANewerOne() { + buffer.setSelectedRange(NSRange(location: 13, length: 0)) + keys("maddggma") + buffer.replayUndo(in: NSRange(location: 12, length: 0), with: "second line\n") + keys("`a") + #expect(pos == 13) + } + + @Test("Undo that replaces the pasted lines brings back the marks they took") + func undoingAReplacementRestoresTheMark() { + buffer = VimTextBufferMock(text: "foo\nbar\ntail\n") + engine = VimEngine(buffer: buffer) + buffer.editObserver = engine + buffer.setSelectedRange(NSRange(location: 5, length: 0)) + keys("ma") + buffer.setSelectedRange(NSRange(location: 0, length: 0)) + engine.register = VimRegister(text: "new\n", isLinewise: true) + key("V", shift: true) + keys("jp") + #expect(engine.marks["a"] == nil) + buffer.replayUndo(in: NSRange(location: 0, length: 4), with: "foo\nbar\n") + buffer.setSelectedRange(NSRange(location: 0, length: 0)) + keys("`a") + #expect(pos == 5) + } + + @Test("An edit before the last insert point on its line keeps the point past the last character") + func lastInsertPointStaysAtTheLineEnd() { + buffer = VimTextBufferMock(text: "abc\ntail\n") + engine = VimEngine(buffer: buffer) + buffer.editObserver = engine + key("A", shift: true) + typeInTextView("X") + key("\u{1B}") + keys("0rYgi") + typeInTextView("Z") + key("\u{1B}") + #expect(buffer.text == "YbcXZ\ntail\n") + } + + @Test("Undoing a join puts the mark back on its line") + func undoingAJoinRestoresTheMark() { + buffer = VimTextBufferMock(text: "hello world\n second\n") + engine = VimEngine(buffer: buffer) + buffer.editObserver = engine + buffer.setSelectedRange(NSRange(location: 16, length: 0)) + keys("magg") + key("J", shift: true) + buffer.replayUndo(in: NSRange(location: 11, length: 1), with: "\n ") + buffer.setSelectedRange(NSRange(location: 0, length: 0)) + keys("`a") + #expect(buffer.text == "hello world\n second\n") + #expect(pos == 16) + } + + @Test("Undoing an edit after a join, then the join, puts the mark back") + func undoingNestedEditsRestoresTheMark() { + buffer = VimTextBufferMock(text: "aaa\nbbb\nccc\n") + engine = VimEngine(buffer: buffer) + buffer.editObserver = engine + buffer.setSelectedRange(NSRange(location: 6, length: 0)) + keys("magg") + key("J", shift: true) + keys("05x") + buffer.replayUndo(in: NSRange(location: 0, length: 0), with: "aaa b") + buffer.replayUndo(in: NSRange(location: 3, length: 1), with: "\n") + buffer.setSelectedRange(NSRange(location: 0, length: 0)) + keys("`a") + #expect(buffer.text == "aaa\nbbb\nccc\n") + #expect(pos == 6) + } + + @Test("Undoing a Visual delete lets gv reselect the restored lines") + func undoingAVisualDeleteRestoresTheLastSelection() { + buffer = VimTextBufferMock(text: "aaa\nbbb\nccc\n") + engine = VimEngine(buffer: buffer) + buffer.editObserver = engine + keys("j") + key("V", shift: true) + keys("d") + buffer.replayUndo(in: NSRange(location: 4, length: 0), with: "bbb\n") + keys("gv") + #expect(buffer.selectedRange() == NSRange(location: 4, length: 4)) + } + + @Test("Undoing a run of backspaces as one edit puts the mark back") + func undoingCoalescedBackspacesRestoresTheMark() { + buffer = VimTextBufferMock(text: "aaa\nbbb\n") + engine = VimEngine(buffer: buffer) + buffer.editObserver = engine + buffer.setSelectedRange(NSRange(location: 6, length: 0)) + keys("ma") + buffer.replaceCharacters(in: NSRange(location: 3, length: 1), with: "") + buffer.replaceCharacters(in: NSRange(location: 2, length: 1), with: "") + buffer.replayUndo(in: NSRange(location: 2, length: 0), with: "a\n") + buffer.setSelectedRange(NSRange(location: 0, length: 0)) + keys("`a") + #expect(buffer.text == "aaa\nbbb\n") + #expect(pos == 6) + } + + @Test("Two undos in a row restore the marks from before the first edit, not from the first undo") + func consecutiveUndosRestoreTheOriginalMark() { + buffer = VimTextBufferMock(text: "aaa\nbbb\n") + engine = VimEngine(buffer: buffer) + buffer.editObserver = engine + buffer.setSelectedRange(NSRange(location: 6, length: 0)) + keys("magg") + keys("gJ") + buffer.replaceCharacters(in: NSRange(location: 3, length: 0), with: "\n") + buffer.replayUndo(in: NSRange(location: 3, length: 1), with: "") + buffer.replayUndo(in: NSRange(location: 3, length: 0), with: "\n") + buffer.setSelectedRange(NSRange(location: 0, length: 0)) + keys("`a") + #expect(buffer.text == "aaa\nbbb\n") + #expect(pos == 6) + } + + @Test("A long insert after a delete does not lose the record its undo needs") + func longInsertKeepsTheRecordForUndo() { + buffer.setSelectedRange(NSRange(location: 25, length: 0)) + keys("magg") + keys("c") + key("G", shift: true) + for _ in 0..<150 { typeInTextView("x") } + key("\u{1B}") + for offset in stride(from: 149, through: 0, by: -1) { + buffer.replayUndo(in: NSRange(location: offset, length: 1), with: "") + } + buffer.replayUndo(in: NSRange(location: 0, length: 0), with: "hello world\nsecond line\nthird line") + buffer.setSelectedRange(NSRange(location: 0, length: 0)) + keys("`a") + #expect(buffer.text == "hello world\nsecond line\nthird line\n") + #expect(pos == 25) + } + + @Test("Undoing a run of backspaces after undoing a later edit puts the mark back") + func undoingCoalescedBackspacesAfterAnotherUndo() { + buffer = VimTextBufferMock(text: "aaa\nbbb\n") + engine = VimEngine(buffer: buffer) + buffer.editObserver = engine + buffer.setSelectedRange(NSRange(location: 6, length: 0)) + keys("ma") + buffer.replaceCharacters(in: NSRange(location: 3, length: 1), with: "") + buffer.replaceCharacters(in: NSRange(location: 2, length: 1), with: "") + buffer.replaceCharacters(in: NSRange(location: 0, length: 1), with: "X") + buffer.replayUndo(in: NSRange(location: 0, length: 1), with: "a") + buffer.replayUndo(in: NSRange(location: 2, length: 0), with: "a\n") + buffer.setSelectedRange(NSRange(location: 0, length: 0)) + keys("`a") + #expect(buffer.text == "aaa\nbbb\n") + #expect(pos == 6) + } + + @Test("Undoing more than fifty backspaces as one edit puts the mark back") + func undoingALongBackspaceRunRestoresTheMark() { + let head = String(repeating: "a", count: 60) + buffer = VimTextBufferMock(text: head + "\nbbb\n") + engine = VimEngine(buffer: buffer) + buffer.editObserver = engine + buffer.setSelectedRange(NSRange(location: 63, length: 0)) + keys("ma") + for offset in stride(from: 60, through: 10, by: -1) { + buffer.replaceCharacters(in: NSRange(location: offset, length: 1), with: "") + } + buffer.replayUndo(in: NSRange(location: 10, length: 0), with: String(repeating: "a", count: 50) + "\n") + buffer.setSelectedRange(NSRange(location: 0, length: 0)) + keys("`a") + #expect(buffer.text == head + "\nbbb\n") + #expect(pos == 63) + } + + @Test("An undo that folds the newest edits restores their marks, not an older edit's with the same text") + func undoMatchesTheNewestEditsFirst() { + buffer = VimTextBufferMock(text: "aaaa\n") + engine = VimEngine(buffer: buffer) + buffer.editObserver = engine + buffer.setSelectedRange(NSRange(location: 3, length: 0)) + keys("ma") + buffer.replaceCharacters(in: NSRange(location: 0, length: 2), with: "") + buffer.replaceCharacters(in: NSRange(location: 0, length: 0), with: "aa") + buffer.setSelectedRange(NSRange(location: 0, length: 0)) + keys("ma") + buffer.replaceCharacters(in: NSRange(location: 0, length: 1), with: "") + buffer.replaceCharacters(in: NSRange(location: 0, length: 1), with: "") + buffer.replayUndo(in: NSRange(location: 0, length: 0), with: "aa") + buffer.setSelectedRange(NSRange(location: 2, length: 0)) + keys("`a") + #expect(buffer.text == "aaaa\n") + #expect(pos == 0) + } + + @Test("Undoing a later delete of the same text does not bring back a mark an earlier delete took") + func undoingALaterIdenticalDeleteKeepsTheMarkGone() { + buffer = VimTextBufferMock(text: "aaa\nbbb\nccc\n") + engine = VimEngine(buffer: buffer) + buffer.editObserver = engine + keys("jmaddkpdd") + #expect(buffer.text == "aaa\nccc\n") + buffer.replayUndo(in: NSRange(location: 4, length: 0), with: "bbb\n") + #expect(engine.marks["a"] == nil) + } + + @Test("A mark keeps its column through a line that shrinks and grows back") + func markColumnSurvivesAShorterLine() { + buffer = VimTextBufferMock(text: "abcdef\ntail\n") + engine = VimEngine(buffer: buffer) + buffer.editObserver = engine + keys("$ma0xxxi") + // One key at a time, so each key puts back what an `x` took without being its undo. + for character in ["a", "b", "c"] { typeInTextView(character) } + key("\u{1B}") + keys("`a") + #expect(buffer.text == "abcdef\ntail\n") + #expect(pos == 5) + } + + @Test("A join carries the mark with its text") + func joinCarriesTheMark() { + buffer = VimTextBufferMock(text: "hello world\n second\n") + engine = VimEngine(buffer: buffer) + buffer.editObserver = engine + buffer.setSelectedRange(NSRange(location: 16, length: 0)) + keys("magg") + key("J", shift: true) + keys("`a") + #expect(buffer.text == "hello world second\n") + #expect(pos == 12) + } + + @Test("The last jump position moves with a line typed above it") + func lastJumpOriginMovesWithEdits() { + buffer.setSelectedRange(NSRange(location: 25, length: 0)) + key("G", shift: true) + keys("gg") + key("O", shift: true) + key("\u{1B}") + keys("``") + #expect(pos == 26) + } } diff --git a/apple/TableProTests/Core/Vim/VimEngineNormalMotionsTests.swift b/apple/TableProTests/Core/Vim/VimEngineNormalMotionsTests.swift index 9a6f43a316..59c56fb332 100644 --- a/apple/TableProTests/Core/Vim/VimEngineNormalMotionsTests.swift +++ b/apple/TableProTests/Core/Vim/VimEngineNormalMotionsTests.swift @@ -599,6 +599,114 @@ final class VimEngineNormalMotionsTests { #expect(pos == 0) #expect(buffer.text == "") } + + // MARK: - Enter, + and - + + @Test("Enter and + go to the first non-blank of the next line") + func enterAndPlusGoDown() { + buffer = VimTextBufferMock(text: "one\n two\n three\n") + engine = VimEngine(buffer: buffer) + keys("\r") + #expect(pos == 6) + key("+", shift: true) + #expect(pos == 12) + } + + @Test("- goes to the first non-blank of the line before") + func minusGoesUp() { + buffer = VimTextBufferMock(text: " one\ntwo\n") + engine = VimEngine(buffer: buffer) + buffer.setSelectedRange(NSRange(location: 8, length: 0)) + keys("-") + #expect(pos == 2) + } + + @Test("A count moves that many lines and stops at the last") + func plusWithCountStopsAtTheLastLine() { + buffer = VimTextBufferMock(text: "a\nb\nc\n") + engine = VimEngine(buffer: buffer) + keys("5") + key("+", shift: true) + #expect(pos == 4) + } + + @Test("d+ deletes the line and the next") + func dPlusIsLinewise() { + buffer = VimTextBufferMock(text: "a\nb\nc\n") + engine = VimEngine(buffer: buffer) + keys("d") + key("+", shift: true) + #expect(buffer.text == "c\n") + } + + @Test("d- on the first line deletes nothing") + func dMinusOnTheFirstLineFails() { + buffer = VimTextBufferMock(text: "a\nb\n") + engine = VimEngine(buffer: buffer) + keys("d-x") + #expect(buffer.text == "\nb\n") + } + + // MARK: - Counts on jumps + + @Test("A count before % goes that far through the text") + func countPercentGoesToTheLine() { + buffer = VimTextBufferMock(text: "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n") + engine = VimEngine(buffer: buffer) + keys("50%") + #expect(pos == 8) + } + + @Test("2H goes to the second visible line") + func countBeforeH() { + buffer = VimTextBufferMock(text: "a\nb\nc\nd\n") + engine = VimEngine(buffer: buffer) + buffer.setSelectedRange(NSRange(location: 6, length: 0)) + keys("2") + key("H", shift: true) + #expect(pos == 2) + } + + @Test("2* goes to the second match of the word") + func countBeforeStar() { + buffer = VimTextBufferMock(text: "foo x foo y foo z\n") + engine = VimEngine(buffer: buffer) + keys("2*") + #expect(pos == 12) + } + + @Test("]] with no section after goes to the start of the last line") + func sectionForwardWithNoSectionGoesToTheLastLine() { + buffer = VimTextBufferMock(text: "SELECT 1;\nSELECT 2;\n") + engine = VimEngine(buffer: buffer) + keys("]]") + #expect(pos == 10) + } + + @Test("d]] with no section after deletes to the end") + func deleteToSectionWithNoSectionDeletesToTheEnd() { + buffer = VimTextBufferMock(text: "SELECT 1;\nSELECT 2;\n") + engine = VimEngine(buffer: buffer) + keys("d]]") + #expect(buffer.text == "") + #expect(engine.register.isLinewise) + } + + @Test("d) on the last sentence deletes to the end of the text") + func deleteToSentenceEndAtTheEndOfTheText() { + buffer = VimTextBufferMock(text: "abc") + engine = VimEngine(buffer: buffer) + keys("d)") + #expect(buffer.text == "") + } + + @Test("} on the last paragraph stops on its last character") + func braceOnTheLastParagraphStopsOnTheLastCharacter() { + buffer = VimTextBufferMock(text: "aaa\nbbb\n") + engine = VimEngine(buffer: buffer) + keys("}") + #expect(pos == 6) + } } // swiftlint:enable file_length type_body_length diff --git a/apple/TableProTests/Core/Vim/VimEngineOperatorsTests.swift b/apple/TableProTests/Core/Vim/VimEngineOperatorsTests.swift index b957123ee9..84bd19869d 100644 --- a/apple/TableProTests/Core/Vim/VimEngineOperatorsTests.swift +++ b/apple/TableProTests/Core/Vim/VimEngineOperatorsTests.swift @@ -354,7 +354,7 @@ final class VimEngineOperatorsTests { buffer.setSelectedRange(NSRange(location: 0, length: 0)) keys("cw") #expect(engine.mode == .insert) - #expect(buffer.text == "world\nsecond line\nthird line\n") + #expect(buffer.text == " world\nsecond line\nthird line\n") } @Test @@ -447,6 +447,212 @@ final class VimEngineOperatorsTests { #expect(buffer.text == "hello world\nsecond line\nthird line\n", "Deleted text should round-trip through P") } + + // MARK: - Motions after an operator, as Vim takes them + + private func make(_ text: String, at offset: Int) { + buffer = VimTextBufferMock(text: text) + engine = VimEngine(buffer: buffer) + buffer.setSelectedRange(NSRange(location: offset, length: 0)) + } + + @Test("d% deletes through the matching bracket") + func dPercentDeletesThroughTheMatchingBracket() { + make("a (b c) d\n", at: 2) + keys("d%") + #expect(buffer.text == "a d\n") + #expect(engine.register.text == "(b c)") + } + + @Test("d% from before the bracket takes the text up to it") + func dPercentFromBeforeTheBracket() { + make("a (b c) d\n", at: 0) + keys("d%") + #expect(buffer.text == " d\n") + } + + @Test("c% changes the bracketed text") + func cPercentChangesTheBracketedText() { + make("a (b c) d\n", at: 2) + keys("c%") + #expect(buffer.text == "a d\n") + #expect(engine.mode == .insert) + #expect(pos == 2) + } + + @Test("y% yanks without moving") + func yPercentYanks() { + make("a (b c) d\n", at: 0) + keys("y%") + #expect(buffer.text == "a (b c) d\n") + #expect(engine.register.text == "a (b c)") + #expect(pos == 0) + } + + @Test("d% with no bracket ends the command") + func dPercentWithNoBracketEndsTheCommand() { + make("a b c d\n", at: 0) + keys("d%w") + #expect(buffer.text == "a b c d\n") + #expect(pos == 2) + } + + @Test("A key that is not a motion ends the operator") + func nonMotionKeyEndsTheOperator() { + make("one two\n", at: 0) + keys("dxw") + #expect(buffer.text == "one two\n") + #expect(pos == 4) + } + + @Test("dn deletes to the next match") + func dnDeletesToTheNextMatch() { + make("foo bar foo baz\n", at: 0) + keys("/foo\r0dn") + #expect(buffer.text == "foo baz\n") + #expect(engine.register.text == "foo bar ") + } + + @Test("d} from a line start takes the paragraph's lines") + func dBraceFromLineStartIsLinewise() { + make("aaa\nbbb\n\nccc\n", at: 0) + keys("d}") + #expect(buffer.text == "\nccc\n") + #expect(engine.register.text == "aaa\nbbb\n") + #expect(engine.register.isLinewise) + } + + @Test("d} from inside a line stops before the line break") + func dBraceFromInsideALine() { + make("aaa\nbbb\n\nccc\n", at: 1) + keys("d}") + #expect(buffer.text == "a\n\nccc\n") + #expect(engine.register.text == "aa\nbbb") + #expect(!engine.register.isLinewise) + } + + @Test("d} on the last paragraph takes its lines") + func dBraceOnTheLastParagraph() { + make("aaa\nbbb\n", at: 0) + keys("d}") + #expect(buffer.text == "") + #expect(engine.register.isLinewise) + } + + @Test("d'a deletes the lines through the mark") + func dQuoteMarkIsLinewise() { + make("aaa\nbbb\nccc\n", at: 8) + keys("magg") + keys("d'a") + #expect(buffer.text == "") + #expect(engine.register.text == "aaa\nbbb\nccc\n") + } + + @Test("d`a deletes up to the mark") + func dBacktickMarkIsExclusive() { + make("aaa\nbbb\nccc\n", at: 5) + keys("magg") + keys("d`a") + #expect(buffer.text == "bb\nccc\n") + } + + @Test("d'a with the mark unset ends the command") + func dQuoteUnsetMarkEndsTheCommand() { + make("aaa bbb\n", at: 0) + keys("d'aw") + #expect(buffer.text == "aaa bbb\n") + #expect(pos == 4) + } + + @Test("dL deletes to the last visible line") + func dLDeletesToTheLastVisibleLine() { + make("aaa\nbbb\nccc\n", at: 0) + keys("d") + key("L", shift: true) + #expect(buffer.text == "") + } + + @Test("db at a line start keeps the line break") + func dbAtLineStartKeepsTheLineBreak() { + make("foo bar\nbaz\n", at: 8) + keys("db") + #expect(buffer.text == "foo \nbaz\n") + #expect(engine.register.text == "bar") + } + + @Test("dW on the last WORD of a line stops at the line end") + func dBigWOnTheLastWordStopsAtTheLineEnd() { + make("foo b.r\n baz\n", at: 4) + keys("d") + key("W", shift: true) + #expect(buffer.text == "foo \n baz\n") + } + + @Test("dw on an empty line deletes the line") + func dwOnAnEmptyLineDeletesIt() { + make("aaa\n\nbbb\n", at: 4) + keys("dw") + #expect(buffer.text == "aaa\nbbb\n") + } + + @Test("cw on a word changes to its end, not the space after") + func cwChangesToTheWordEnd() { + make("foo bar baz\n", at: 0) + keys("cw") + #expect(buffer.text == " bar baz\n") + #expect(engine.mode == .insert) + } + + @Test("2cw changes two words, not the space after the second") + func cwWithCount() { + make("foo bar baz\n", at: 0) + keys("2cw") + #expect(buffer.text == " baz\n") + } + + @Test("cw on blanks changes them up to the next word") + func cwOnBlanks() { + make("foo bar\n", at: 4) + keys("cw") + #expect(buffer.text == "foo bar\n") + } + + @Test("cj leaves one empty line to type on") + func cjLeavesALine() { + make("a\nb\nc\n", at: 0) + keys("cj") + #expect(buffer.text == "\nc\n") + #expect(engine.mode == .insert) + #expect(pos == 0) + } + + @Test("dj on the last line deletes nothing") + func djOnTheLastLineFails() { + make("aaa\nbbb\n", at: 4) + keys("djx") + #expect(buffer.text == "aaa\nbb\n") + } + + @Test(">b from a line start shifts only the line the motion covers") + func indentBackwardWordFromALineStart() { + make("foo bar\nbaz\n", at: 8) + keys(">b") + #expect(buffer.text == " foo bar\nbaz\n") + } + + @Test(">b at the start of the text shifts nothing") + func indentBackwardWordAtTheStartFails() { + make("abc\n", at: 0) + keys(">b") + #expect(buffer.text == "abc\n") + } + + @Test(">w shifts the whole line") + func indentWithACharacterMotionShiftsTheLine() { + make("hello world\n", at: 6) + keys(">w") + #expect(buffer.text == " hello world\n") + } } // swiftlint:enable file_length type_body_length diff --git a/apple/TableProTests/Core/Vim/VimEnginePasteTests.swift b/apple/TableProTests/Core/Vim/VimEnginePasteTests.swift index 15b0c60b6d..dc0d4ab792 100644 --- a/apple/TableProTests/Core/Vim/VimEnginePasteTests.swift +++ b/apple/TableProTests/Core/Vim/VimEnginePasteTests.swift @@ -199,4 +199,70 @@ final class VimEnginePasteTests { "Paste over a visual selection should replace the selection with the register") #expect(engine.mode == .normal) } + + // MARK: - Counted paste, and paste on an empty line + + private func make(_ text: String, at offset: Int) { + buffer = VimTextBufferMock(text: text) + engine = VimEngine(buffer: buffer) + buffer.setSelectedRange(NSRange(location: offset, length: 0)) + } + + @Test("\"a2p pastes register a twice") + func countedPasteFromANamedRegisterPastesItEachTime() { + make("ab cd\n", at: 0) + keys("\"aylwyl") + keys("$\"a2p") + #expect(buffer.text == "ab cdaa\n") + #expect(pos == 6) + } + + @Test("\"a2p pastes a linewise register a twice") + func countedLinewisePasteFromANamedRegister() { + make("ab\ncd\n", at: 0) + keys("\"ayyjyy\"a2p") + #expect(buffer.text == "ab\ncd\nab\nab\n") + } + + @Test("2P keeps each copy whole") + func countedCapitalPKeepsCopiesWhole() { + make("ab cd\n", at: 0) + keys("yw$2") + key("P", shift: true) + #expect(buffer.text == "ab cab ab d\n") + #expect(pos == 9) + } + + @Test("p on an empty line puts the text on that line") + func pasteOnAnEmptyLineStaysOnIt() { + make("one\n\ntwo\n", at: 0) + keys("ylj") + keys("p") + #expect(buffer.text == "one\no\ntwo\n") + #expect(pos == 4) + } + + @Test("p below a last line with no line break adds the break first") + func linewisePasteBelowALastLineWithoutABreak() { + make("a\nb", at: 2) + keys("yyp") + #expect(buffer.text == "a\nb\nb") + #expect(pos == 4) + } + + @Test("A linewise paste leaves the cursor on the first non-blank") + func linewisePasteLandsOnTheFirstNonBlank() { + make(" ab\ncd\n", at: 0) + keys("yyjp") + #expect(buffer.text == " ab\ncd\n ab\n") + #expect(pos == 10) + } + + @Test("A paste over several lines leaves the cursor at its start") + func multilineCharacterPasteLandsAtItsStart() { + make("ab cd\nef\n", at: 1) + keys("vjy$p") + #expect(buffer.text == "ab cdb cd\nef\nef\n") + #expect(pos == 5) + } } diff --git a/apple/TableProTests/Core/Vim/VimEngineTextObjectsTests.swift b/apple/TableProTests/Core/Vim/VimEngineTextObjectsTests.swift index ae64f3ea79..7a05e6d2db 100644 --- a/apple/TableProTests/Core/Vim/VimEngineTextObjectsTests.swift +++ b/apple/TableProTests/Core/Vim/VimEngineTextObjectsTests.swift @@ -249,8 +249,8 @@ final class VimEngineTextObjectsTests { engine = VimEngine(buffer: buffer) buffer.setSelectedRange(NSRange(location: 3, length: 0)) keys("dip") - #expect(buffer.text == "\n\npara two\n", - "dip should delete the paragraph at cursor (without surrounding blank lines)") + #expect(buffer.text == "\npara two\n", + "dip should delete the paragraph's lines, as Vim's linewise ip does") } @Test @@ -318,4 +318,64 @@ final class VimEngineTextObjectsTests { #expect(buffer.text == "f()\n", "di( with cursor on the closing paren should still work") } + + // MARK: - ip and ap take whole lines + + private func make(_ text: String, at offset: Int) { + buffer = VimTextBufferMock(text: text) + engine = VimEngine(buffer: buffer) + buffer.setSelectedRange(NSRange(location: offset, length: 0)) + } + + @Test("yip on the last paragraph keeps its last character") + func yankInnerParagraphAtTheEndOfTheText() { + make("a\n\nb\nc", at: 5) + keys("yip") + #expect(engine.register.text == "b\nc") + #expect(engine.register.isLinewise) + #expect(buffer.selectedRange().location == 3) + } + + @Test("dip on the last paragraph deletes its lines") + func deleteInnerParagraphAtTheEndOfTheText() { + make("a\n\nb\nc", at: 5) + keys("dip") + #expect(buffer.text == "a\n\n") + } + + @Test("cip leaves one empty line to type on") + func changeInnerParagraphLeavesALine() { + make("a\nb\n\nc\n", at: 0) + keys("cip") + #expect(buffer.text == "\n\nc\n") + #expect(engine.mode == .insert) + } + + @Test("A line of only spaces ends the paragraph for dip") + func whiteLineEndsTheParagraph() { + make("SELECT 1;\n \nSELECT 2;\n", at: 0) + keys("dip") + #expect(buffer.text == " \nSELECT 2;\n") + } + + @Test("dip on blank lines deletes the blank lines") + func deleteInnerParagraphOnBlankLines() { + make("a\n\n\nb\n", at: 2) + keys("dip") + #expect(buffer.text == "a\nb\n") + } + + @Test("dap on blank lines deletes them and the paragraph after") + func deleteAParagraphOnBlankLines() { + make("a\n\n\nb\nc\n\nd\n", at: 2) + keys("dap") + #expect(buffer.text == "a\n\nd\n") + } + + @Test("dap on the last paragraph takes the blank lines before it") + func deleteAParagraphAtTheEndTakesLeadingBlankLines() { + make("a\n\nb\nc\n", at: 3) + keys("dap") + #expect(buffer.text == "a\n") + } } diff --git a/apple/TableProTests/Core/Vim/VimEngineVisualModeTests.swift b/apple/TableProTests/Core/Vim/VimEngineVisualModeTests.swift index ee9cb6b856..d94cdfb3b4 100644 --- a/apple/TableProTests/Core/Vim/VimEngineVisualModeTests.swift +++ b/apple/TableProTests/Core/Vim/VimEngineVisualModeTests.swift @@ -485,6 +485,69 @@ final class VimEngineVisualModeTests { key("V", shift: true) #expect(engine.mode.displayLabel == "VISUAL LINE") } + + // MARK: - Text objects and registers in Visual mode + + private func make(_ text: String, at offset: Int) { + buffer = VimTextBufferMock(text: text) + engine = VimEngine(buffer: buffer) + buffer.setSelectedRange(NSRange(location: offset, length: 0)) + } + + @Test("After viw from inside a word, the next motion extends from the word's end") + func motionAfterInnerWordExtendsTheSelection() { + make("hello world\n", at: 2) + keys("viwe") + #expect(buffer.string(in: sel) == "hello world") + } + + @Test("iw in Visual Line mode selects the word characterwise") + func innerWordLeavesVisualLine() { + make("hello world\nfoo\n", at: 0) + key("V", shift: true) + keys("iwd") + #expect(buffer.text == " world\nfoo\n") + } + + @Test("vip selects the paragraph's lines in Visual Line mode") + func innerParagraphSwitchesToVisualLine() { + make("a\nb\n\nc\n", at: 0) + keys("vip") + #expect(engine.mode == .visual(linewise: true)) + #expect(sel == NSRange(location: 0, length: 4)) + } + + @Test("\"a before y in Visual mode yanks into register a") + func visualYankIntoANamedRegister() { + make("abc def\n", at: 0) + keys("viw\"ay") + #expect(engine.namedRegisters["a"]?.text == "abc") + } + + @Test("p over a selection puts the replaced text in the unnamed register") + func visualPasteKeepsTheReplacedText() { + make("abc def\n", at: 0) + keys("yiwwviwp") + #expect(buffer.text == "abc abc\n") + #expect(engine.register.text == "def") + } + + @Test("P over a selection leaves the registers as they were") + func visualCapitalPasteKeepsTheRegister() { + make("abc def\n", at: 0) + keys("yiwwviw") + key("P", shift: true) + #expect(buffer.text == "abc abc\n") + #expect(engine.register.text == "abc") + } + + @Test("\"ap over a selection pastes register a") + func visualPasteFromANamedRegister() { + make("abc def\n", at: 0) + keys("\"ayiwwviw\"ap") + #expect(buffer.text == "abc abc\n") + #expect(engine.namedRegisters["a"]?.text == "abc") + } } // swiftlint:enable file_length type_body_length diff --git a/apple/TableProTests/Core/Vim/VimTextBufferAdapterLineIndexTests.swift b/apple/TableProTests/Core/Vim/VimTextBufferAdapterLineIndexTests.swift index 407c69ed29..75701ab53f 100644 --- a/apple/TableProTests/Core/Vim/VimTextBufferAdapterLineIndexTests.swift +++ b/apple/TableProTests/Core/Vim/VimTextBufferAdapterLineIndexTests.swift @@ -182,8 +182,8 @@ struct VimTextBufferAdapterLineIndexTests { } } - #expect(shortLanding == short.lastOffset) - #expect(longLanding == long.lastOffset) + #expect(shortLanding == short.lastLineStart) + #expect(longLanding == long.lastLineStart) #expect(longPasses < shortPasses * 2) } @@ -191,19 +191,20 @@ struct VimTextBufferAdapterLineIndexTests { let textView: TextView let adapter: VimTextBufferAdapter let engine: VimEngine - let lastOffset: Int + let lastLineStart: Int } // Not laid out: the motion reads only the line storage, and a text view outside a scroll view lays out every line. private func makeSectionScript(lines: Int) -> SectionScript { - let script = String(repeating: "SELECT id, name FROM users WHERE id = 1;\n", count: lines) + let line = "SELECT id, name FROM users WHERE id = 1;\n" + let script = String(repeating: line, count: lines) let textView = makeTextView(string: script, layingOut: false) let adapter = VimTextBufferAdapter(textView: textView) return SectionScript( textView: textView, adapter: adapter, engine: VimEngine(buffer: adapter), - lastOffset: (script as NSString).length - 1 + lastLineStart: (script as NSString).length - (line as NSString).length ) } diff --git a/apple/TableProTests/Core/Vim/VimTextBufferMock.swift b/apple/TableProTests/Core/Vim/VimTextBufferMock.swift index 7beb32f778..b303b3dd9e 100644 --- a/apple/TableProTests/Core/Vim/VimTextBufferMock.swift +++ b/apple/TableProTests/Core/Vim/VimTextBufferMock.swift @@ -104,140 +104,27 @@ final class VimTextBufferMock: VimTextBuffer { } func wordBoundary(forward: Bool, from offset: Int) -> Int { - let nsString = text as NSString - guard nsString.length > 0 else { return 0 } - if forward { - var pos = min(offset, nsString.length - 1) - let startClass = charClass(nsString.character(at: pos)) - if startClass == .whitespace { - while pos < nsString.length && charClass(nsString.character(at: pos)) == .whitespace { - pos += 1 - } - } else { - while pos < nsString.length && charClass(nsString.character(at: pos)) == startClass { - pos += 1 - } - while pos < nsString.length && charClass(nsString.character(at: pos)) == .whitespace { - pos += 1 - } - } - return min(pos, nsString.length) - } else { - var pos = min(offset, nsString.length) - if pos > 0 { pos -= 1 } - while pos > 0 && charClass(nsString.character(at: pos)) == .whitespace { - pos -= 1 - } - let cls = charClass(nsString.character(at: pos)) - while pos > 0 && charClass(nsString.character(at: pos - 1)) == cls { - pos -= 1 - } - return max(0, pos) - } + VimWordScanner.wordBoundary(forward: forward, from: offset, in: text as NSString) } func wordEnd(from offset: Int) -> Int { - let nsString = text as NSString - guard nsString.length > 0 else { return 0 } - var pos = min(offset + 1, nsString.length - 1) - while pos < nsString.length && charClass(nsString.character(at: pos)) == .whitespace { - pos += 1 - } - guard pos < nsString.length else { return nsString.length - 1 } - let cls = charClass(nsString.character(at: pos)) - while pos < nsString.length - 1 && charClass(nsString.character(at: pos + 1)) == cls { - pos += 1 - } - return min(pos, nsString.length - 1) + VimWordScanner.wordEnd(from: offset, in: text as NSString) } func wordEndBackward(from offset: Int) -> Int { - let nsString = text as NSString - guard nsString.length > 0 else { return 0 } - var pos = min(max(0, offset), nsString.length - 1) - if pos > 0 { pos -= 1 } - if charClass(nsString.character(at: pos)) == .whitespace { - while pos > 0 && charClass(nsString.character(at: pos)) == .whitespace { - pos -= 1 - } - return pos - } - let cls = charClass(nsString.character(at: pos)) - while pos > 0 && charClass(nsString.character(at: pos - 1)) == cls { - pos -= 1 - } - guard pos > 0 else { return 0 } - pos -= 1 - while pos > 0 && charClass(nsString.character(at: pos)) == .whitespace { - pos -= 1 - } - return pos + VimWordScanner.wordEndBackward(from: offset, in: text as NSString) } func bigWordBoundary(forward: Bool, from offset: Int) -> Int { - let nsString = text as NSString - guard nsString.length > 0 else { return 0 } - if forward { - var pos = min(offset, nsString.length - 1) - if isWhitespace(nsString.character(at: pos)) { - while pos < nsString.length && isWhitespace(nsString.character(at: pos)) { - pos += 1 - } - } else { - while pos < nsString.length && !isWhitespace(nsString.character(at: pos)) { - pos += 1 - } - while pos < nsString.length && isWhitespace(nsString.character(at: pos)) { - pos += 1 - } - } - return min(pos, nsString.length) - } - var pos = min(offset, nsString.length) - if pos > 0 { pos -= 1 } - while pos > 0 && isWhitespace(nsString.character(at: pos)) { - pos -= 1 - } - while pos > 0 && !isWhitespace(nsString.character(at: pos - 1)) { - pos -= 1 - } - return max(0, pos) + VimWordScanner.bigWordBoundary(forward: forward, from: offset, in: text as NSString) } func bigWordEnd(from offset: Int) -> Int { - let nsString = text as NSString - guard nsString.length > 0 else { return 0 } - var pos = min(offset + 1, nsString.length - 1) - while pos < nsString.length && isWhitespace(nsString.character(at: pos)) { - pos += 1 - } - guard pos < nsString.length else { return nsString.length - 1 } - while pos < nsString.length - 1 && !isWhitespace(nsString.character(at: pos + 1)) { - pos += 1 - } - return min(pos, nsString.length - 1) + VimWordScanner.bigWordEnd(from: offset, in: text as NSString) } func bigWordEndBackward(from offset: Int) -> Int { - let nsString = text as NSString - guard nsString.length > 0 else { return 0 } - var pos = min(max(0, offset), nsString.length - 1) - if pos > 0 { pos -= 1 } - if isWhitespace(nsString.character(at: pos)) { - while pos > 0 && isWhitespace(nsString.character(at: pos)) { - pos -= 1 - } - return pos - } - while pos > 0 && !isWhitespace(nsString.character(at: pos - 1)) { - pos -= 1 - } - guard pos > 0 else { return 0 } - pos -= 1 - while pos > 0 && isWhitespace(nsString.character(at: pos)) { - pos -= 1 - } - return pos + VimWordScanner.bigWordEndBackward(from: offset, in: text as NSString) } func matchingBracket(at offset: Int) -> Int? { @@ -297,7 +184,20 @@ final class VimTextBufferMock: VimTextBuffer { : NSRange(location: characterRange(at: clampedLocation).location, length: 0) } + // The editor tells the engine about every edit before it lands, typed and undone ones included. + weak var editObserver: VimEngine? + + // Puts text back as the editor's undo does, which the engine tells apart from typing. + func replayUndo(in range: NSRange, with string: String) { + editSource = .undo + defer { editSource = .edit } + replaceCharacters(in: range, with: string) + } + + private var editSource: VimEditSource = .edit + func replaceCharacters(in range: NSRange, with string: String) { + editObserver?.textWillChange(in: range, with: string, source: editSource) let mutable = NSMutableString(string: text) mutable.replaceCharacters(in: range, with: string) text = mutable as String @@ -309,21 +209,4 @@ final class VimTextBufferMock: VimTextBuffer { func undo() { undoCallCount += 1 } func redo() { redoCallCount += 1 } - - private enum CharClass { - case word, punctuation, whitespace - } - - private func charClass(_ char: unichar) -> CharClass { - if isWhitespace(char) { return .whitespace } - guard let scalar = UnicodeScalar(char) else { return .punctuation } - if CharacterSet.alphanumerics.contains(scalar) || char == 0x5F { - return .word - } - return .punctuation - } - - private func isWhitespace(_ char: unichar) -> Bool { - char == 0x20 || char == 0x09 || char == 0x0A || char == 0x0D - } } diff --git a/apple/TableProTests/Views/Editor/SQLEditorVimMarksTests.swift b/apple/TableProTests/Views/Editor/SQLEditorVimMarksTests.swift new file mode 100644 index 0000000000..a4b5829d48 --- /dev/null +++ b/apple/TableProTests/Views/Editor/SQLEditorVimMarksTests.swift @@ -0,0 +1,44 @@ +// Typed, pasted and undone text never passes through the Vim engine, so the editor reports each edit to it. + +import AppKit +import TableProEditorKit +import TableProTestSupport +import TableProTextEngine +import Testing + +@testable import TablePro + +extension GlobalStateSuites { + @Suite(.appSettings { $0.editor.keyBindings = .vim }) + @MainActor + struct SQLEditorVimMarksTests { + @Test("A line typed above a mark moves it down, and undoing the line moves it back") + func marksFollowEditsMadeInTheEditor() throws { + let coordinator = SQLEditorCoordinator(diagnosticsClock: ManualClock()) + coordinator.databaseType = .mysql + let controller = EditorControllerFixture.make(string: "SELECT 1;\nSELECT 2;\n", coordinators: [coordinator]) + defer { coordinator.destroy() } + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 800, height: 600), + styleMask: [.titled], + backing: .buffered, + defer: false + ) + window.isReleasedWhenClosed = false + window.contentView = controller.view + defer { window.orderOut(nil) } + let textView = try #require(controller.textView) + + var marks = VimDocumentMarks() + marks.marks["a"] = 13 + coordinator.restoreVimDocumentMarks(marks) + + textView.replaceCharacters(in: NSRange(location: 0, length: 0), with: "-- note\n") + #expect(coordinator.vimDocumentMarks?.marks["a"] == 21) + + textView.undoManager?.undo() + #expect(textView.string == "SELECT 1;\nSELECT 2;\n") + #expect(coordinator.vimDocumentMarks?.marks["a"] == 13) + } + } +} diff --git a/apple/TableProTests/Views/Editor/VimDocumentMarksTests.swift b/apple/TableProTests/Views/Editor/VimDocumentMarksTests.swift index 5056ec1b91..2e6e270aa7 100644 --- a/apple/TableProTests/Views/Editor/VimDocumentMarksTests.swift +++ b/apple/TableProTests/Views/Editor/VimDocumentMarksTests.swift @@ -52,4 +52,20 @@ struct VimDocumentMarksTests { #expect(!engine.lastVisualLinewise) #expect(engine.lastInsertOffset == nil) } + + @Test("A tab switch keeps a mark's column and the marks an undo can bring back") + func savedMarksKeepColumnsAndErasedMarks() { + buffer.editObserver = engine + buffer.setSelectedRange(NSRange(location: 13, length: 0)) + keys("madd") + let saved = engine.documentMarks + #expect(!saved.isEmpty) + + engine.documentDidReplace() + engine.restoreDocumentMarks(saved) + buffer.replayUndo(in: NSRange(location: 12, length: 0), with: "second line\n") + buffer.setSelectedRange(NSRange(location: 0, length: 0)) + keys("`a") + #expect(pos == 13) + } } diff --git a/apple/changelog.d/4347.fixed.1.md b/apple/changelog.d/4347.fixed.1.md new file mode 100644 index 0000000000..31c36454e1 --- /dev/null +++ b/apple/changelog.d/4347.fixed.1.md @@ -0,0 +1 @@ +In Vim mode, `d%`, `c%`, `dn`, `d}`, `d'a` and other motions after an operator only moved the cursor. diff --git a/apple/changelog.d/4347.fixed.2.md b/apple/changelog.d/4347.fixed.2.md new file mode 100644 index 0000000000..aff71701a0 --- /dev/null +++ b/apple/changelog.d/4347.fixed.2.md @@ -0,0 +1 @@ +In Vim mode, `"a2p` pasted register a once and then the last yank, and `2P` mixed up the copies. diff --git a/apple/changelog.d/4347.fixed.3.md b/apple/changelog.d/4347.fixed.3.md new file mode 100644 index 0000000000..b502d00e2e --- /dev/null +++ b/apple/changelog.d/4347.fixed.3.md @@ -0,0 +1 @@ +In Vim mode, marks stayed where they were when lines were typed, pasted or undone above them. diff --git a/apple/changelog.d/4347.fixed.4.md b/apple/changelog.d/4347.fixed.4.md new file mode 100644 index 0000000000..e8700d8aae --- /dev/null +++ b/apple/changelog.d/4347.fixed.4.md @@ -0,0 +1 @@ +In Vim mode, the next motion after `viw` shrank the selection instead of extending it. diff --git a/apple/changelog.d/4347.fixed.5.md b/apple/changelog.d/4347.fixed.5.md new file mode 100644 index 0000000000..1038579ae7 --- /dev/null +++ b/apple/changelog.d/4347.fixed.5.md @@ -0,0 +1 @@ +In Vim mode, `a` and `p` on an empty line put the text on the next line. diff --git a/apple/changelog.d/4347.fixed.6.md b/apple/changelog.d/4347.fixed.6.md new file mode 100644 index 0000000000..58e69af666 --- /dev/null +++ b/apple/changelog.d/4347.fixed.6.md @@ -0,0 +1 @@ +In Vim mode, `ip` dropped the last character of the last paragraph. diff --git a/apple/changelog.d/4347.fixed.7.md b/apple/changelog.d/4347.fixed.7.md new file mode 100644 index 0000000000..363444518e --- /dev/null +++ b/apple/changelog.d/4347.fixed.7.md @@ -0,0 +1 @@ +In Vim mode, `w` stopped on a symbol followed by a variation selector, such as ❤️. diff --git a/apple/changelog.d/4347.fixed.8.md b/apple/changelog.d/4347.fixed.8.md new file mode 100644 index 0000000000..ad6a5e7639 --- /dev/null +++ b/apple/changelog.d/4347.fixed.8.md @@ -0,0 +1 @@ +In Vim mode, Enter, `+` and `-` did nothing in Normal mode. diff --git a/apple/changelog.d/4347.fixed.9.md b/apple/changelog.d/4347.fixed.9.md new file mode 100644 index 0000000000..34673f4c54 --- /dev/null +++ b/apple/changelog.d/4347.fixed.9.md @@ -0,0 +1 @@ +In Vim mode, `cw`, `cj`, `dF` and `db` at the start of a line changed more text than Vim does. diff --git a/apple/changelog.d/4347.fixed.md b/apple/changelog.d/4347.fixed.md new file mode 100644 index 0000000000..cfdcd4b875 --- /dev/null +++ b/apple/changelog.d/4347.fixed.md @@ -0,0 +1 @@ +In Vim mode, Escape or leaving the command line kept a pending `d` or `c`, so the next key could delete text. diff --git a/windows/docs/decisions/0017-vim-mode.md b/windows/docs/decisions/0017-vim-mode.md index c9aada216b..2c6dbb810a 100644 --- a/windows/docs/decisions/0017-vim-mode.md +++ b/windows/docs/decisions/0017-vim-mode.md @@ -14,7 +14,8 @@ The macOS editor has a Vim mode behind its Key bindings setting (`apple/TablePro - `TablePro.Editor.Model/Vim` is a port of the macOS engine to C#, so its tests run on any machine (`tests/TablePro.Editor.Model.Tests/Vim`, one suite per macOS suite plus the Windows additions). A key is one text element; control keys come as their control characters. - It works on the editor model through `VimTextBuffer`: a character is a grapheme cluster (`StringInfo`), as macOS's composed character sequence is; `f` and `t` compare characters canonically, and `~`, `gU` and `gu` use Unicode's full case mapping, so `ß` becomes `SS`, as Swift's does. - Each key the engine takes is one undo step, and an insert is one step from the key that started it to Escape (`UndoHistory.Coalesce`), as Vim undoes it; an arrow or a click inside the insert starts a new step. A macro replayed by `@` is one step, `u` inside it undoes the macro's own changes (`UndoHistory.Checkpoint`), and it types again what Insert mode typed. -- Marks move with every change to the text, typed, pasted or undone, not only the engine's deletes. Escape drops every prefix of a command, an operator included; `%` takes a pending operator; a count before `p` pastes the chosen register each time; a Visual text object moves Visual's anchor and cursor; Enter, `+` and `-` go to a line's first character; a failed `f` or `t` drops its operator; a counted `P` keeps each copy whole; `a` and `p` on an empty line stay on it; `ip` at the end of the text keeps its last character; and a word motion steps over a symbol with a variation selector. The macOS engine, which this ports, still behaves the old way in each. +- Marks keep their line and column, as Vim's do (`:help mark-motions`), through every change to the text, typed, pasted or undone, not only the engine's own: whole lines added or removed at a line start move the marks on and below them, a join carries a mark with its text, an edit on a mark's line keeps the column it was set at, and removing a named mark's line removes the mark until the undo that puts the line back, while `''`, the last insert and the last Visual selection go to where the lines were. A line changed in place, as `>>` or `gUU` changes it, keeps its marks. +- A command that ends drops the count and register typed for it, and Escape drops every prefix of one, an operator included. After an operator only a motion, a text object, a search or the operator doubled continues the command; a motion that finds nothing ends it. Operators follow `:help exclusive`, `cw` changes to the word's end, a linewise change leaves one empty line, `>` and `<` shift whole lines, and `ip` and `ap` take whole lines. A count before `p` pastes the chosen register each time, a counted `P` keeps each copy whole, and `a` and `p` on an empty line stay on it. In Visual mode `"x` picks the register, `p` keeps the text it replaces and `P` leaves the registers alone, and a text object moves Visual's anchor and cursor. Enter, `+` and `-` go to a line's first character, and a word motion steps over a symbol with a variation selector. - Registers and macros are the app's, shared by every editor (`VimRegisters.Shared`), as Vim keeps them across buffers. Each yank and delete also reaches the clipboard, as on macOS, but kept out of clipboard history and other devices (`ClipboardContentOptions`), since Vim writes on every `x`. ### Folds and wrapped lines @@ -45,6 +46,6 @@ The macOS editor has a Vim mode behind its Key bindings setting (`apple/TablePro ## Consequences - Ctrl+A, B, F and P mean Vim's commands in Normal mode, so Select All, Find, Show objects and Filter objects are reached from the Edit and View menus then, and Ctrl+D pages instead of adding the next match. Ctrl+W and Ctrl+T in Insert mode delete a word and indent, not close and open a tab. -- macOS's quirks come with the port: `cw` takes the space after the word, and `.` repeats `x` and `dw`-style operator motions only. +- `.` repeats `x` and `dw`-style operator motions only, as on macOS. - Visual block mode, `:s`, `:{line}` and text typed by `.` are not built, as on macOS. - A macro keeps the keys Vim sees, typed text included, but not the keys Insert mode leaves to the editor (arrows, Home, End, Ctrl shortcuts), as on macOS. Replaying those needs the editor's commands, paste and undo among them, to run inside the macro's undo step and in order, which is a design of its own. diff --git a/windows/src/TablePro.Editor.Model/Vim/VimEngine.Controls.cs b/windows/src/TablePro.Editor.Model/Vim/VimEngine.Controls.cs index 619da2e999..7e3b886322 100644 --- a/windows/src/TablePro.Editor.Model/Vim/VimEngine.Controls.cs +++ b/windows/src/TablePro.Editor.Model/Vim/VimEngine.Controls.cs @@ -51,9 +51,7 @@ private bool HandleNormalControl(string key) } if (PendingOperator is not null) { - PendingOperator = null; - CountPrefix = 0; - OperatorCount = 0; + CancelPending(); return true; } PerformNormalControl(control); diff --git a/windows/src/TablePro.Editor.Model/Vim/VimEngine.Insert.cs b/windows/src/TablePro.Editor.Model/Vim/VimEngine.Insert.cs index 8bd8f3c3ea..298e827216 100644 --- a/windows/src/TablePro.Editor.Model/Vim/VimEngine.Insert.cs +++ b/windows/src/TablePro.Editor.Model/Vim/VimEngine.Insert.cs @@ -120,20 +120,24 @@ private bool ProcessCommandLine(string key, string commandLine) { var prefix = commandLine.Length > 0 ? commandLine[0] : '\0'; var body = commandLine.Length > 0 ? commandLine[1..] : string.Empty; - CancelPending(); SetMode(VimMode.Normal); - if (prefix == '/') - { - RunSearch(body, forward: true); - } - else if (prefix == '?') + if (prefix is '/' or '?') { - RunSearch(body, forward: false); + // A search after an operator is its motion, as d/foo deletes up to foo. + if (PendingOperator is not null) + { + ApplyMotion(SearchTarget(body, forward: prefix == '/', SearchCount), VimMotionKind.Exclusive); + } + else + { + RunSearch(body, forward: prefix == '/', SearchCount); + } } else { _buffer.Host.Command(body); } + CancelPending(); return true; } case "\u007F" or "\b": diff --git a/windows/src/TablePro.Editor.Model/Vim/VimEngine.Motions.cs b/windows/src/TablePro.Editor.Model/Vim/VimEngine.Motions.cs index bb8a69cb0f..ecb5836d7f 100644 --- a/windows/src/TablePro.Editor.Model/Vim/VimEngine.Motions.cs +++ b/windows/src/TablePro.Editor.Model/Vim/VimEngine.Motions.cs @@ -30,25 +30,26 @@ internal void MoveRight(int count) internal void MoveUp(int count) => MoveVertically(-count); + // An operator takes the lines whole; on the first or last line it has nothing to take and the command ends. private void MoveVertically(int lines) { var pos = _buffer.SelectedRange.Location; var (line, column) = _buffer.LineAndColumn(pos); GoalColumn ??= column; - var target = _buffer.Offset(_buffer.StepLines(line, lines), GoalColumn ?? column); - if (PendingOperator is { } op) + var targetLine = _buffer.StepLines(line, lines); + var target = _buffer.Offset(targetLine, GoalColumn ?? column); + if (PendingOperator is not { } op) { - var from = _buffer.FoldedLineRange(pos); - var to = _buffer.FoldedLineRange(target); - var start = Math.Min(from.Location, to.Location); - var end = Math.Max(from.End, to.End); - ExecuteOperatorOnRange(op, new VimRange(start, end - start), linewise: true); - PendingOperator = null; + _buffer.SetCaret(target); + return; } - else + GoalColumn = null; + if (targetLine == line) { - _buffer.SetCaret(target); + CancelPending(); + return; } + Operate(op, pos, target, VimMotionKind.Linewise); } // gj and gk: rows on screen, so a wrapped line takes several steps and a closed fold one. @@ -105,31 +106,49 @@ internal void GoToLine(int line) _buffer.SetCaret(_buffer.Offset(target, 0)); } - internal void WordForward(int count) + // cw on a word changes to its end, as ce does; elsewhere w and W go to the next word's start. + internal void WordMotion(int count, bool bigWord) + { + var pos = _buffer.SelectedRange.Location; + if (PendingOperator == VimOperator.Change && pos < _buffer.Length && !VimTextBuffer.IsWhitespace(_buffer.CharAt(pos))) + { + int End(int offset) => bigWord ? _buffer.BigWordEnd(offset) : _buffer.WordEnd(offset); + var target = End(pos - 1); + for (var i = 1; i < count; i++) + { + target = End(target); + } + ApplyMotion(target, VimMotionKind.Inclusive); + return; + } + ApplyMotion(WordForwardTarget(count, bigWord), VimMotionKind.Exclusive); + } + + // After an operator the last word stops at the end of its line, and from an empty line at the next line's start, + // which :help exclusive turns into the empty line. + private int? WordForwardTarget(int count, bool bigWord) { var pos = _buffer.SelectedRange.Location; var isOperator = PendingOperator is not null; for (var i = 0; i < count; i++) { - var previous = pos; - var next = _buffer.WordBoundary(forward: true, pos); + var next = bigWord ? _buffer.BigWordBoundary(forward: true, pos) : _buffer.WordBoundary(forward: true, pos); if (isOperator && i == count - 1) { - var previousLine = _buffer.LineRange(previous); - var nextLine = _buffer.LineRange(Math.Min(next, _buffer.Length)); - if (previousLine.Location != nextLine.Location) + var line = _buffer.LineRange(pos); + if (_buffer.LineRange(Math.Min(next, _buffer.Length)).Location != line.Location) { - pos = ContentEnd(previousLine); - break; + var end = ContentEnd(line); + if (end > line.Location) + { + return end; + } + return line.End < _buffer.Length ? line.End : null; } } pos = next; } - if (!isOperator) - { - pos = ClampToContentPosition(pos); - } - _buffer.SetCaret(pos); + return pos; } internal int ClampToContentPosition(int offset) @@ -168,21 +187,6 @@ internal void WordEndMotion(int count) _buffer.SetCaret(pos); } - internal void BigWordForward(int count) - { - var pos = _buffer.SelectedRange.Location; - var isOperator = PendingOperator is not null; - for (var i = 0; i < count; i++) - { - pos = _buffer.BigWordBoundary(forward: true, pos); - } - if (!isOperator) - { - pos = ClampToContentPosition(pos); - } - _buffer.SetCaret(pos); - } - internal void BigWordBackward(int count) { var pos = _buffer.SelectedRange.Location; @@ -238,36 +242,43 @@ internal void BigWordEndBackwardMotion(int count) return null; } - // An operator takes the lines whole, as j and k give them. - internal void MoveToFirstNonBlankOfLine(int lines) + // {count}%: the line that far through the text, as Vim rounds it. + internal int? PercentLineTarget(int count) { - if (PendingOperator is not null) + if (count > 100) { - MoveVertically(lines); - GoalColumn = null; - return; + return null; } - var (line, _) = _buffer.LineAndColumn(_buffer.SelectedRange.Location); - _buffer.SetCaret(FirstNonBlankOffset(_buffer.Offset(_buffer.StepLines(line, lines), 0))); - GoalColumn = null; + var lineCount = _buffer.LineCount; + var line = (int)Math.Clamp(((long)count * lineCount + 99) / 100 - 1, 0, lineCount - 1); + return FirstNonBlankOffset(_buffer.Offset(line, 0)); + } + + // Enter and + go down that many lines, - up, to the first character; at the first or last line they fail. + internal int? LineStepTarget(int lines) + { + var line = _buffer.LineAndColumn(_buffer.SelectedRange.Location).Line; + var target = _buffer.StepLines(line, lines); + return target == line ? null : FirstNonBlankOffset(_buffer.Offset(target, 0)); } // H, M and L read the rows on screen, so a fold or a wrapped line between them counts as it shows; the rows stop - // at Vim's last line, never the empty one after a final break. - internal void JumpToVisibleLine(VimScroll position) + // at Vim's last line, never the empty one after a final break. A count is lines from the top for H and from the + // bottom for L. + internal int VisibleLineTarget(VimScroll position, int count) { var rows = _buffer.Model.Rows; var (firstLine, lastLine) = _buffer.VisibleLineRange(); var (firstRow, lastRow) = _buffer.VisibleRows(); lastRow = Math.Min(lastRow, rows.FirstRowOf(lastLine) + Math.Max(1, rows.RowsOf(lastLine)) - 1); + var skip = Math.Max(0, count - 1); var targetLine = position switch { - VimScroll.Top => firstLine, - VimScroll.Bottom => lastLine, + VimScroll.Top => Math.Min(_buffer.StepLines(firstLine, skip), lastLine), + VimScroll.Bottom => Math.Max(_buffer.StepLines(lastLine, -skip), firstLine), _ => rows.LineAtRow((firstRow + lastRow) / 2), }; - _buffer.SetCaret(FirstNonBlankOffset(_buffer.Offset(Math.Min(targetLine, _buffer.LineCount - 1), 0))); - GoalColumn = null; + return FirstNonBlankOffset(_buffer.Offset(Math.Min(targetLine, _buffer.LineCount - 1), 0)); } internal bool ExecuteFindChar(string target, VimFindCharRequest request) @@ -345,36 +356,26 @@ bool Matches(VimRange range) => // Not found: the command ends here, so an operator waiting on it does not reach the next motion. if (resolved is not { } finalPos) { - PendingOperator = null; - OperatorCount = 0; + CancelPending(); return true; } if (request.Till) { finalPos = request.Forward ? Previous(finalPos) : CharacterEnd(finalPos); } - ExecuteMotion(() => _buffer.SetCaret(finalPos), inclusive: true); + // f and t take the character they reach; F and T stop short of the cursor's. + ExecuteMotion(() => _buffer.SetCaret(finalPos), inclusive: request.Forward); return true; } - internal void SentenceForward(int count) + internal int SentenceTarget(bool forward, int count) { var pos = _buffer.SelectedRange.Location; for (var i = 0; i < count; i++) { - pos = NextSentenceStart(pos); + pos = forward ? NextSentenceStart(pos) : PreviousSentenceStart(pos); } - _buffer.SetCaret(pos); - } - - internal void SentenceBackward(int count) - { - var pos = _buffer.SelectedRange.Location; - for (var i = 0; i < count; i++) - { - pos = PreviousSentenceStart(pos); - } - _buffer.SetCaret(pos); + return pos; } private static bool EndsSentence(char c) => c is '.' or '!' or '?'; @@ -399,7 +400,7 @@ internal int NextSentenceStart(int origin) } } } - return length > 0 ? length - 1 : 0; + return LastLineContentEnd(); } internal int PreviousSentenceStart(int origin) @@ -423,24 +424,14 @@ internal int PreviousSentenceStart(int origin) return 0; } - internal void ParagraphForward(int count) + internal int ParagraphTarget(bool forward, int count) { var pos = _buffer.SelectedRange.Location; for (var i = 0; i < count; i++) { - pos = NextParagraphBoundary(pos); + pos = forward ? NextParagraphBoundary(pos) : PreviousParagraphBoundary(pos); } - _buffer.SetCaret(pos); - } - - internal void ParagraphBackward(int count) - { - var pos = _buffer.SelectedRange.Location; - for (var i = 0; i < count; i++) - { - pos = PreviousParagraphBoundary(pos); - } - _buffer.SetCaret(pos); + return pos; } internal int NextParagraphBoundary(int origin) @@ -454,9 +445,12 @@ internal int NextParagraphBoundary(int origin) return _buffer.Offset(line, 0); } } - return _buffer.Length > 0 ? _buffer.Length - 1 : 0; + return LastLineContentEnd(); } + // Past the last character, so an operator takes it, and a plain motion steps back onto it. + private int LastLineContentEnd() => ContentEnd(_buffer.LineRange(_buffer.Offset(_buffer.LineCount - 1, 0))); + internal int PreviousParagraphBoundary(int origin) { var (originLine, _) = _buffer.LineAndColumn(origin); @@ -470,34 +464,45 @@ internal int PreviousParagraphBoundary(int origin) return 0; } - internal void SectionForward() + // ]] and [[: the next or previous line that starts with {. + internal int SectionTarget(bool forward, int count) { - var (originLine, _) = _buffer.LineAndColumn(_buffer.SelectedRange.Location); - for (var line = originLine + 1; line < _buffer.LineCount; line++) + var line = _buffer.LineAndColumn(_buffer.SelectedRange.Location).Line; + var step = forward ? 1 : -1; + for (var i = 0; i < count; i++) { - var offset = _buffer.Offset(line, 0); - if (offset < _buffer.Length && _buffer.CharAt(offset) == '{') + var next = line + step; + while (next >= 0 && next < _buffer.LineCount) + { + var offset = _buffer.Offset(next, 0); + if (offset < _buffer.Length && _buffer.CharAt(offset) == '{') + { + break; + } + next += step; + } + if (next < 0 || next >= _buffer.LineCount) { - _buffer.SetCaret(offset); - return; + return forward ? LastLineContentEnd() : 0; } + line = next; } - _buffer.SetCaret(Math.Max(0, _buffer.Length - 1)); + return _buffer.Offset(line, 0); } - internal void SectionBackward() + // A line of only blanks ends a paragraph for ip and ap, though not for { and }. + internal bool LineIsWhite(int line) { - var (originLine, _) = _buffer.LineAndColumn(_buffer.SelectedRange.Location); - for (var line = originLine - 1; line >= 0; line--) + var range = _buffer.LineRange(_buffer.Offset(line, 0)); + var end = ContentEnd(range); + for (var scan = range.Location; scan < end; scan++) { - var offset = _buffer.Offset(line, 0); - if (offset < _buffer.Length && _buffer.CharAt(offset) == '{') + if (_buffer.CharAt(scan) is not (' ' or '\t' or '\r')) { - _buffer.SetCaret(offset); - return; + return false; } } - _buffer.SetCaret(0); + return true; } internal bool LineIsBlank(int line) diff --git a/windows/src/TablePro.Editor.Model/Vim/VimEngine.Normal.cs b/windows/src/TablePro.Editor.Model/Vim/VimEngine.Normal.cs index 34eeab1390..d2263be452 100644 --- a/windows/src/TablePro.Editor.Model/Vim/VimEngine.Normal.cs +++ b/windows/src/TablePro.Editor.Model/Vim/VimEngine.Normal.cs @@ -2,50 +2,70 @@ namespace TablePro.Editor.Model.Vim; public sealed partial class VimEngine { - private bool ProcessNormal(string key, bool shift) + private static readonly HashSet s_keysAfterOperator = new(StringComparer.Ordinal) { - var buffer = _buffer; + "h", "j", "k", "l", "w", "b", "e", "W", "B", "E", "0", "$", "^", "_", "g", "G", "f", "F", "t", "T", ";", ",", + "%", "n", "N", "*", "#", "'", "`", "(", ")", "{", "}", "[", "]", "H", "M", "L", "/", "?", ":", "\r", "+", "-", + "i", "a", + }; + private bool ProcessNormal(string key, bool shift) + { if (key == Escape) { CancelPending(); return true; } + if (PendingRegisterSelect) + { + PendingRegisterSelect = false; + // "" names the unnamed register. + SelectedRegister = key == "\"" ? null : key; + return true; + } + if (!TakesCharacterArgument && IsDigit(key, out var digit) && (CountPrefix > 0 || digit > 0)) + { + if (CountPrefix <= 99_999) + { + CountPrefix = CountPrefix * 10 + digit; + } + return true; + } + var consumed = ProcessNormalCommand(key, shift); + // A command that ends drops the count and register typed for it, used or not. + if (!WaitsForKey) + { + CountPrefix = 0; + OperatorCount = 0; + SelectedRegister = null; + } + return consumed; + } + + private bool ProcessNormalCommand(string key, bool shift) + { + var buffer = _buffer; + if (PendingFindChar is { } request) { PendingFindChar = null; - return key == Escape || ExecuteFindChar(key, request); + return ExecuteFindChar(key, request); } if (PendingReplaceChar) { PendingReplaceChar = false; - return key == Escape || ExecuteReplaceChar(key); + return ExecuteReplaceChar(key); } if (PendingMarkSet) { PendingMarkSet = false; - if (key != Escape) - { - Marks[key] = buffer.SelectedRange.Location; - } + SetMark(key, buffer.SelectedRange.Location); return true; } if (PendingMarkJumpExact is { } exact) { PendingMarkJumpExact = null; - if (key != Escape) - { - JumpToMark(key, exact); - } - return true; - } - if (PendingRegisterSelect) - { - PendingRegisterSelect = false; - if (key != Escape) - { - SelectedRegister = key; - } + JumpToMark(key, exact); return true; } if (PendingZ) @@ -57,41 +77,29 @@ private bool ProcessNormal(string key, bool shift) if (PendingTextObject) { PendingTextObject = false; - if (key == Escape) - { - PendingOperator = null; - return true; - } return ExecuteTextObject(key, PendingTextObjectAround); } if (PendingMacroTarget is { } kind) { PendingMacroTarget = null; - if (key != Escape) - { - HandleMacroTarget(kind, key); - } + HandleMacroTarget(kind, key); return true; } if (PendingBracket is { } bracket) { PendingBracket = null; + var count = ConsumeCount(); if (bracket == VimBracketPending.OpenBracket && key == "[") { - SectionBackward(); + ApplyMotion(SectionTarget(forward: false, count), VimMotionKind.Exclusive, jump: true); } else if (bracket == VimBracketPending.CloseBracket && key == "]") { - SectionForward(); + ApplyMotion(SectionTarget(forward: true, count), VimMotionKind.Exclusive, jump: true); } - return true; - } - - if (IsDigit(key, out var digit) && (CountPrefix > 0 || digit > 0)) - { - if (CountPrefix <= 99_999) + else { - CountPrefix = CountPrefix * 10 + digit; + CancelPending(); } return true; } @@ -107,6 +115,14 @@ private bool ProcessNormal(string key, bool shift) return true; } + // A key that is not a motion, a text object or the operator doubled ends the command, as Vim's operators take + // nothing else. + if (PendingOperator is { } pending && !AcceptsAfterOperator(key, pending)) + { + CancelPending(); + return true; + } + switch (key) { case "h": @@ -130,18 +146,18 @@ private bool ProcessNormal(string key, bool shift) case "w": { var count = ConsumeCount(); - if (PendingOperator is { } op) - { - ExecuteOperatorWithMotion(op, () => WordForward(count)); - RecordDot(new VimDotKind.OperatorWithMotion(op, "w", false, count)); - } - else + var op = PendingOperator; + WordMotion(count, bigWord: false); + if (op is { } recorded) { - WordForward(count); + RecordDot(new VimDotKind.OperatorWithMotion(recorded, "w", false, count)); } - GoalColumn = null; return true; } + // Nothing comes before the start of the text, so the motion fails and an operator does nothing. + case "b" or "B" when buffer.SelectedRange.Location == 0: + ApplyMotion(null, VimMotionKind.Exclusive); + return true; case "b": { var count = ConsumeCount(); @@ -212,11 +228,8 @@ private bool ProcessNormal(string key, bool shift) case "G": return HandleG(); case "W": - { - var count = ConsumeCount(); - ExecuteMotion(() => BigWordForward(count)); + WordMotion(ConsumeCount(), bigWord: true); return true; - } case "B": { var count = ConsumeCount(); @@ -383,17 +396,26 @@ private bool ProcessNormal(string key, bool shift) case "T": PendingFindChar = new VimFindCharRequest(Forward: false, Till: true); return true; + // With no find to repeat, ; and , fail and end the command. case ";": if (LastFindChar is { } last) { ExecuteFindChar(last.Char, new VimFindCharRequest(last.Forward, last.Till)); } + else + { + ApplyMotion(null, VimMotionKind.Exclusive); + } return true; case ",": if (LastFindChar is { } previous) { ExecuteFindChar(previous.Char, new VimFindCharRequest(!previous.Forward, previous.Till)); } + else + { + ApplyMotion(null, VimMotionKind.Exclusive); + } return true; case "r": @@ -435,56 +457,39 @@ private bool ProcessNormal(string key, bool shift) BeginOperator(VimOperator.Outdent); return true; - case "?": - CountPrefix = 0; - OperatorCount = 0; - SetMode(VimMode.CommandLine, "?"); + case "/" or "?" or ":": + { + var count = ConsumeCount(); + // A count before a search finds that many matches, as 2d/x deletes up to the second x. + SearchCount = key == ":" ? 1 : count; + SetMode(VimMode.CommandLine, key); return true; + } case "%": - if (MatchingBracketOnLine() is { } pair) + if (CountPrefix > 0 || OperatorCount > 0) { - ExecuteMotion(() => buffer.SetCaret(pair), inclusive: true); + ApplyMotion(PercentLineTarget(ConsumeCount()), VimMotionKind.Linewise, jump: true); } else { - PendingOperator = null; - CountPrefix = 0; - OperatorCount = 0; + ApplyMotion(MatchingBracketOnLine(), VimMotionKind.Inclusive, jump: true); } return true; // Enter and + go to the first character of the next line, - of the line before. case "\r" or "+": - MoveToFirstNonBlankOfLine(ConsumeCount()); + ApplyMotion(LineStepTarget(ConsumeCount()), VimMotionKind.Linewise); return true; case "-": - MoveToFirstNonBlankOfLine(-ConsumeCount()); + ApplyMotion(LineStepTarget(-ConsumeCount()), VimMotionKind.Linewise); return true; - case "n": - { - var count = ConsumeCount(); - for (var i = 0; i < count; i++) - { - SearchNext(reverseDirection: false); - } + case "n" or "N": + ApplyMotion(SearchNextTarget(ConsumeCount(), reverseDirection: key == "N"), VimMotionKind.Exclusive, jump: true); return true; - } - case "N": - { - var count = ConsumeCount(); - for (var i = 0; i < count; i++) - { - SearchNext(reverseDirection: true); - } - return true; - } - case "*": - SearchWordUnderCursor(forward: true); - return true; - case "#": - SearchWordUnderCursor(forward: false); + case "*" or "#": + ApplyMotion(SearchWordUnderCursorTarget(forward: key == "*", ConsumeCount()), VimMotionKind.Exclusive, jump: true); return true; case "m": @@ -504,17 +509,11 @@ private bool ProcessNormal(string key, bool shift) ReplayLastDot(ConsumeCount()); return true; - case "(": - SentenceBackward(ConsumeCount()); - return true; - case ")": - SentenceForward(ConsumeCount()); + case "(" or ")": + ApplyMotion(SentenceTarget(forward: key == ")", ConsumeCount()), VimMotionKind.Exclusive, jump: true); return true; - case "{": - ParagraphBackward(ConsumeCount()); - return true; - case "}": - ParagraphForward(ConsumeCount()); + case "{" or "}": + ApplyMotion(ParagraphTarget(forward: key == "}", ConsumeCount()), VimMotionKind.Exclusive, jump: true); return true; case "[": PendingBracket = VimBracketPending.OpenBracket; @@ -538,44 +537,24 @@ private bool ProcessNormal(string key, bool shift) PendingMacroTarget = VimMacroPendingKind.ReplayTarget; return true; - case "H": - JumpToVisibleLine(VimScroll.Top); - return true; - case "M": - JumpToVisibleLine(VimScroll.Middle); - return true; - case "L": - JumpToVisibleLine(VimScroll.Bottom); + case "H" or "M" or "L": + { + var position = key switch + { + "H" => VimScroll.Top, + "M" => VimScroll.Middle, + _ => VimScroll.Bottom, + }; + ApplyMotion(VisibleLineTarget(position, ConsumeCount()), VimMotionKind.Linewise, jump: true); return true; + } case "z": PendingZ = true; return true; case "p" or "P": - { - var count = ConsumeCount(); - // The register is read once, so "a2p pastes a twice; characters go in as one run, as 2P keeps them in order. - var source = ActivePasteRegister(); - if (!source.IsLinewise && count > 1) - { - source = source with { Text = string.Concat(Enumerable.Repeat(source.Text, count)) }; - count = 1; - } - for (var i = 0; i < count; i++) - { - Paste(source, after: key == "p"); - } - return true; - } - - case "/": - CountPrefix = 0; - SetMode(VimMode.CommandLine, "/"); - return true; - case ":": - CountPrefix = 0; - SetMode(VimMode.CommandLine, ":"); + Paste(after: key == "p", ConsumeCount()); return true; case "u": @@ -622,22 +601,33 @@ private bool ProcessNormal(string key, bool shift) } default: - if (key == Escape) - { - PendingOperator = null; - CountPrefix = 0; - PendingG = false; - return true; - } - CountPrefix = 0; - PendingOperator = null; + CancelPending(); return true; } } + private static bool AcceptsAfterOperator(string key, VimOperator op) => s_keysAfterOperator.Contains(key) || key switch + { + "d" => op == VimOperator.Delete, + "y" => op == VimOperator.Yank, + "c" => op == VimOperator.Change, + ">" => op == VimOperator.Indent, + "<" => op == VimOperator.Outdent, + "~" => op == VimOperator.ToggleCase, + "u" => op == VimOperator.Lowercase, + "U" => op == VimOperator.Uppercase, + _ => false, + }; + private bool HandlePendingG(string key) { var buffer = _buffer; + // gi, gv and gJ are commands, not motions, so an operator before them ends. + if (PendingOperator is not null && key is "i" or "v" or "J") + { + CancelPending(); + return true; + } switch (key) { case "g": @@ -718,40 +708,36 @@ private bool HandlePendingG(string key) return true; } case "u": - if (PendingOperator == VimOperator.Lowercase) - { - ApplyCaseToLine(VimOperator.Lowercase, ConsumeCount()); - PendingOperator = null; - return true; - } - BeginOperator(VimOperator.Lowercase); - return true; + return HandleCaseOperator(VimOperator.Lowercase); case "U": - if (PendingOperator == VimOperator.Uppercase) - { - ApplyCaseToLine(VimOperator.Uppercase, ConsumeCount()); - PendingOperator = null; - return true; - } - BeginOperator(VimOperator.Uppercase); - return true; + return HandleCaseOperator(VimOperator.Uppercase); case "~": - if (PendingOperator == VimOperator.ToggleCase) - { - ApplyCaseToLine(VimOperator.ToggleCase, ConsumeCount()); - PendingOperator = null; - return true; - } - BeginOperator(VimOperator.ToggleCase); - return true; + return HandleCaseOperator(VimOperator.ToggleCase); default: - CountPrefix = 0; - OperatorCount = 0; - PendingOperator = null; + CancelPending(); return true; } } + // gu, gU and g~ doubled take lines; after another operator they end the command. + private bool HandleCaseOperator(VimOperator op) + { + if (PendingOperator == op) + { + ApplyCaseToLine(op, ConsumeCount()); + PendingOperator = null; + } + else if (PendingOperator is not null) + { + CancelPending(); + } + else + { + BeginOperator(op); + } + return true; + } + private bool HandleG() { var buffer = _buffer; @@ -777,13 +763,6 @@ private bool HandleG() // zo, zc and za fold at the caret, zR and zM every fold, zz, zt and zb scroll the caret's line. private void HandlePendingZ(string key) { - CountPrefix = 0; - OperatorCount = 0; - if (PendingOperator is not null) - { - PendingOperator = null; - return; - } var host = _buffer.Host; switch (key) { @@ -834,6 +813,29 @@ internal void ExecuteMotion(Action motion, bool inclusive = false) GoalColumn = null; } + // Moves to the target, or with an operator pending applies it from the cursor to the target. A motion that found + // nothing ends the command, as Vim's failed motions do. + internal void ApplyMotion(int? target, VimMotionKind kind, bool jump = false) + { + GoalColumn = null; + if (target is not { } destination) + { + CancelPending(); + return; + } + var origin = _buffer.SelectedRange.Location; + if (PendingOperator is { } op) + { + Operate(op, origin, destination, kind); + return; + } + _buffer.SetCaret(kind == VimMotionKind.Linewise ? destination : ClampToContentPosition(destination)); + if (jump) + { + LastJumpOrigin = origin; + } + } + // A closed fold at either end is taken whole, as Vim's linewise operators take it. internal void ExecuteLinewiseOperator(VimOperator op, int fromOffset, int toLine) { diff --git a/windows/src/TablePro.Editor.Model/Vim/VimEngine.Operators.cs b/windows/src/TablePro.Editor.Model/Vim/VimEngine.Operators.cs index 6c1fc2aee2..05154a5cd3 100644 --- a/windows/src/TablePro.Editor.Model/Vim/VimEngine.Operators.cs +++ b/windows/src/TablePro.Editor.Model/Vim/VimEngine.Operators.cs @@ -8,15 +8,84 @@ internal void ExecuteOperatorWithMotion(VimOperator op, Action motion, bool incl { var startPos = _buffer.SelectedRange.Location; motion(); - var endPos = _buffer.SelectedRange.Location; - var rangeStart = Math.Min(startPos, endPos); - var rangeEnd = Math.Max(startPos, endPos); - if (inclusive && rangeEnd < _buffer.Length && _buffer.CharAt(rangeEnd) != '\n') + var kind = inclusive ? VimMotionKind.Inclusive : VimMotionKind.Exclusive; + Operate(op, startPos, _buffer.SelectedRange.Location, kind); + } + + internal void Operate(VimOperator op, int origin, int target, VimMotionKind kind) + { + PendingOperator = null; + var start = Math.Min(origin, target); + var end = Math.Max(origin, target); + if (kind == VimMotionKind.Linewise) { - rangeEnd = CharacterEnd(rangeEnd); + ExecuteOperatorOnRange(op, WholeLines(start, end), linewise: true); + return; } - ExecuteOperatorOnRange(op, new VimRange(rangeStart, rangeEnd - rangeStart), linewise: false); - PendingOperator = null; + var rangeEnd = end; + if (kind == VimMotionKind.Inclusive && end < _buffer.Length && _buffer.CharAt(end) != '\n') + { + rangeEnd = CharacterEnd(end); + } + var startsInIndent = IsInIndent(start); + // :help exclusive: an exclusive motion that ends at the start of a later line stops at the end of the line + // before, and takes whole lines when it starts in the indent. + if (kind == VimMotionKind.Exclusive && end > start && _buffer.LineRange(end).Location == end) + { + if (startsInIndent) + { + ExecuteOperatorOnRange(op, WholeLines(start, end - 1), linewise: true); + return; + } + rangeEnd = CharacterStart(end - 1); + } + if (op is VimOperator.Indent or VimOperator.Outdent) + { + ExecuteOperatorOnRange(op, WholeLines(start, Math.Max(start, rangeEnd - 1)), linewise: true); + return; + } + // A delete over several lines from the indent to the end of a line takes the lines, as Vim's d does. + if (op == VimOperator.Delete && startsInIndent && rangeEnd > start + && _buffer.LineRange(start).Location != _buffer.LineRange(rangeEnd - 1).Location && IsBlankToLineEnd(rangeEnd)) + { + ExecuteOperatorOnRange(op, WholeLines(start, rangeEnd - 1), linewise: true); + return; + } + ExecuteOperatorOnRange(op, new VimRange(start, rangeEnd - start), linewise: false); + } + + // A closed fold at either end is taken whole. + internal VimRange WholeLines(int start, int end) + { + var first = _buffer.FoldedLineRange(start).Location; + var last = _buffer.FoldedLineRange(Math.Max(start, end)).End; + return new VimRange(first, last - first); + } + + // Only blanks come before the offset on its line. + private bool IsInIndent(int offset) + { + for (var scan = _buffer.LineRange(offset).Location; scan < offset; scan++) + { + if (_buffer.CharAt(scan) is not (' ' or '\t')) + { + return false; + } + } + return true; + } + + private bool IsBlankToLineEnd(int offset) + { + var lineEnd = ContentEnd(_buffer.LineRange(offset)); + for (var scan = offset; scan < lineEnd; scan++) + { + if (_buffer.CharAt(scan) is not (' ' or '\t' or '\r')) + { + return false; + } + } + return true; } internal void ExecuteOperatorOnRange(VimOperator op, VimRange proposed, bool linewise) @@ -32,20 +101,27 @@ internal void ExecuteOperatorOnRange(VimOperator op, VimRange proposed, bool lin switch (op) { case VimOperator.Delete: + { WriteToActiveRegister(_buffer.Text(range), linewise, asDelete: true); _buffer.Replace(range, string.Empty); - _buffer.SetCaret(ClampToContentPosition(range.Location)); + var landing = linewise ? FirstNonBlankOffset(range.Location) : range.Location; + _buffer.SetCaret(ClampToContentPosition(landing)); break; + } case VimOperator.Yank: WriteToActiveRegister(_buffer.Text(range), linewise, asDelete: false); _buffer.SetCaret(range.Location); break; case VimOperator.Change: + { WriteToActiveRegister(_buffer.Text(range), linewise, asDelete: true); - _buffer.Replace(range, string.Empty); + // A linewise change leaves one empty line to type on, as cc does. + var keepsBreak = linewise && _buffer.CharAt(range.End - 1) == '\n'; + _buffer.Replace(keepsBreak ? range with { Length = range.Length - 1 } : range, string.Empty); _buffer.SetCaret(range.Location); SetMode(VimMode.Insert); break; + } case VimOperator.Lowercase: _buffer.Replace(range, VimCase.Lower(_buffer.Text(range))); _buffer.SetCaret(range.Location); @@ -58,11 +134,12 @@ internal void ExecuteOperatorOnRange(VimOperator op, VimRange proposed, bool lin _buffer.Replace(range, VimCase.Toggle(_buffer.Text(range))); _buffer.SetCaret(range.Location); break; + // > and < shift whole lines, a text object's included. case VimOperator.Indent: - ApplyIndent(range, outdent: false); + ApplyIndent(linewise ? range : WholeLines(range.Location, range.End - 1), outdent: false); break; case VimOperator.Outdent: - ApplyIndent(range, outdent: true); + ApplyIndent(linewise ? range : WholeLines(range.Location, range.End - 1), outdent: true); break; } } @@ -138,41 +215,40 @@ internal void ChangeLine(int count) SetMode(VimMode.Insert); } - internal void Paste(VimRegister source, bool after) + // The register is read once, so a count pastes copies of the one register, and the copies go in as one run. + internal void Paste(bool after, int count) { + var source = ActivePasteRegister(); if (source.Text.Length == 0) { return; } + var copies = Math.Max(1, count); var pos = _buffer.SelectedRange.Location; if (source.IsLinewise) { + var line = source.Text.EndsWith('\n') ? source.Text : source.Text + "\n"; + var text = string.Concat(Enumerable.Repeat(line, copies)); // Below a closed fold, never between its lines. - var line = _buffer.FoldedLineRange(pos); - var text = source.Text.EndsWith('\n') ? source.Text : source.Text + "\n"; - var insertAt = after ? line.End : line.Location; - if (after && insertAt == _buffer.Length && insertAt > 0 && _buffer.CharAt(insertAt - 1) != '\n') + var lines = _buffer.FoldedLineRange(pos); + var insertAt = after ? lines.End : lines.Location; + var firstLine = insertAt; + // Below a last line with no line break, the break goes before the pasted lines. + if (after && insertAt == _buffer.Length && insertAt > lines.Location && _buffer.CharAt(insertAt - 1) != '\n') { - // The last line has no break of its own to paste after. - _buffer.Replace(new VimRange(insertAt, 0), "\n" + text[..^1]); - _buffer.SetCaret(insertAt + 1); - return; + text = "\n" + text[..^1]; + firstLine = insertAt + 1; } _buffer.Replace(new VimRange(insertAt, 0), text); - _buffer.SetCaret(insertAt); - } - else if (after) - { - // On an empty line the text goes before its break, not onto the next line. - var insertAt = _buffer.CharAt(pos) == '\n' ? pos : CharacterEnd(pos); - _buffer.Replace(new VimRange(insertAt, 0), source.Text); - _buffer.SetCaret(Math.Max(insertAt, insertAt + source.Text.Length - 1)); - } - else - { - _buffer.Replace(new VimRange(pos, 0), source.Text); - _buffer.SetCaret(Math.Max(pos, pos + source.Text.Length - 1)); + _buffer.SetCaret(FirstNonBlankOffset(firstLine)); + return; } + var run = string.Concat(Enumerable.Repeat(source.Text, copies)); + // On an empty line the cursor is on its break, and p puts the text before it. + var at = after && pos < ContentEnd(_buffer.LineRange(pos)) ? CharacterEnd(pos) : pos; + _buffer.Replace(new VimRange(at, 0), run); + // Text over several lines leaves the cursor at its start, a single line on its last character. + _buffer.SetCaret(run.Contains('\n', StringComparison.Ordinal) ? at : CharacterStart(at + run.Length - 1)); } internal void DeleteCharUnderCursor(int count) diff --git a/windows/src/TablePro.Editor.Model/Vim/VimEngine.Registers.cs b/windows/src/TablePro.Editor.Model/Vim/VimEngine.Registers.cs index 5a8d143ef4..ff0e746f62 100644 --- a/windows/src/TablePro.Editor.Model/Vim/VimEngine.Registers.cs +++ b/windows/src/TablePro.Editor.Model/Vim/VimEngine.Registers.cs @@ -62,38 +62,36 @@ internal VimRegister ActivePasteRegister() private static bool IsUppercaseLetter(string name) => name.Length == 1 && char.IsUpper(name[0]); + // ' goes to the first character of the mark's line and takes whole lines after an operator; ` goes to the mark + // itself. An unset mark ends the command. internal void JumpToMark(string name, bool exact) { - var length = _buffer.Length; - var origin = _buffer.SelectedRange.Location; - if (name is "'" or "`") + int? mark = name switch { - if (LastJumpOrigin is { } previous) - { - _buffer.SetCaret(Math.Clamp(previous, 0, length)); - LastJumpOrigin = origin; - } + "'" or "`" => LastJumpOrigin, + "<" => LastVisualStart, + ">" => LastVisualEnd, + _ => Marks.TryGetValue(name, out var offset) ? offset : null, + }; + if (mark is not { } found) + { + ApplyMotion(null, VimMotionKind.Exclusive); return; } - if (name == "<" && LastVisualStart is { } start) + var clamped = Math.Clamp(found, 0, _buffer.Length); + if (name is not ("'" or "`" or "<" or ">") && MarkColumns.TryGetValue(name, out var column)) { - _buffer.SetCaret(Math.Clamp(start, 0, length)); - LastJumpOrigin = origin; - return; + var line = _buffer.LineRange(clamped); + clamped = Math.Min(line.Location + column, Math.Max(line.Location, ContentEnd(line) - 1)); } - if (name == ">" && LastVisualEnd is { } end) + if (exact) { - _buffer.SetCaret(Math.Clamp(end, 0, length)); - LastJumpOrigin = origin; - return; + ApplyMotion(clamped, VimMotionKind.Exclusive, jump: true); } - if (!Marks.TryGetValue(name, out var offset)) + else { - return; + ApplyMotion(FirstNonBlankOffset(_buffer.LineRange(clamped).Location), VimMotionKind.Linewise, jump: true); } - var clamped = Math.Clamp(offset, 0, length); - _buffer.SetCaret(exact ? clamped : FirstNonBlankOffset(_buffer.LineRange(clamped).Location)); - LastJumpOrigin = origin; } internal void RecordVisualSelection(bool linewise) @@ -134,30 +132,154 @@ internal void ReselectLastVisual() } } - // Every change to the text, typed, pasted, undone or the engine's own, moves the marks with it. + internal void SetMark(string name, int offset) + { + Marks[name] = offset; + MarkColumns[name] = offset - _buffer.LineRange(offset).Location; + } + + // Every change to the text, typed, pasted, undone or the engine's own, moves the marks with it. Removing a named + // mark's line removes the mark, and the other positions go to where the lines were. Each edit is kept with the + // positions from before it, so the edit that reverses it, as undo does, puts them back, as Vim's undo restores its + // marks. private void OnDocumentChanged(object? sender, TextChange change) { - if (Marks.Count == 0 && LastJumpOrigin is null && LastInsertOffset is null) + bool? undoes = _buffer.Model.Document.Undo.IsReplaying ? ReplayUndoes() : null; + if (undoes is null) + { + _replayRedoCount = null; + } + var hasPositions = Marks.Count > 0 || LastJumpOrigin is not null || LastInsertOffset is not null + || LastVisualStart is not null || LastVisualEnd is not null; + if (!hasPositions && EditJournal.Count == 0) { return; } - foreach (var (key, offset) in Marks.ToList()) + var before = new VimPositionSnapshot( + new Dictionary(Marks, StringComparer.Ordinal), + new Dictionary(MarkColumns, StringComparer.Ordinal), + LastJumpOrigin, + LastInsertOffset, + LastVisualStart, + LastVisualEnd); + VimPositionSnapshot? restored = null; + // Only undo and redo reverse an edit; typing back what an earlier edit removed, past later edits, is a new edit. + var index = undoes is { } undo ? ReversedJournalIndex(change, reversesUndo: !undo) : -1; + if (index >= 0) { - Marks[key] = MapMark(offset, change); + restored = EditJournal[index].Positions; + for (var i = index; i < EditJournal.Count; i++) + { + EditJournalTextLength -= EditJournal[i].TextLength; + } + EditJournal.RemoveRange(index, EditJournal.Count - index); } - LastJumpOrigin = LastJumpOrigin is { } origin ? MapMark(origin, change) : null; - LastInsertOffset = LastInsertOffset is { } insert ? MapMark(insert, change) : null; + var edit = new VimMarkChange(change, _buffer); + foreach (var (name, offset) in Marks.ToList()) + { + var moved = edit.Map(offset, removable: true); + if (moved is not { KeepsColumn: true }) + { + MarkColumns.Remove(name); + } + if (moved is { } mapped) + { + Marks[name] = mapped.Offset; + } + else + { + Marks.Remove(name); + } + } + LastJumpOrigin = LastJumpOrigin is { } origin ? edit.Map(origin, removable: false)?.Offset : null; + LastInsertOffset = LastInsertOffset is { } insert ? edit.Map(insert, removable: false, boundary: true)?.Offset : null; + LastVisualStart = LastVisualStart is { } start ? edit.Map(start, removable: false)?.Offset : null; + LastVisualEnd = LastVisualEnd is { } end ? edit.Map(end, removable: false)?.Offset : null; + if (restored is not null) + { + RestorePositions(restored); + } + // Every edit is kept, in order, so an undo always finds the records of the step it reverses at the end. + var record = new VimEditRecord(change.Offset, change.RemovedText, change.InsertedText, before, undoes == true); + EditJournal.Add(record); + EditJournalTextLength += record.TextLength; + // An undo step can hold a long run of typing, so the journal keeps thousands of edits, bounded by the text they + // hold rather than their number. + while (EditJournal.Count > 10_000 || EditJournalTextLength > 1_000_000) + { + EditJournalTextLength -= EditJournal[0].TextLength; + EditJournal.RemoveAt(0); + } + } + + // Whether the undo history is undoing, not redoing. An edit empties the redo stack, so the first replay after one + // undoes; after that an undo takes a step onto the redo stack and a redo takes one off. + private bool ReplayUndoes() + { + var redoCount = _buffer.Model.Document.Undo.RedoCount; + if (_replayRedoCount is not { } seen) + { + _replayUndoes = true; + } + else if (redoCount != seen) + { + _replayUndoes = redoCount > seen; + } + _replayRedoCount = redoCount; + return _replayUndoes; + } + + // Undo reverses the newest step first, so only the newest records, folded together, can match: an undo reverses + // only edits, a redo only undos. The undo history joins a run of keys, such as backspaces, into one edit, which is + // why more than one record may be folded. Records of the other direction are passed over: each is an undo of an + // edit already gone from the journal, so the two cancel out. + private int ReversedJournalIndex(TextChange change, bool reversesUndo) + { + VimEditRecord? folded = null; + for (var i = EditJournal.Count - 1; i >= 0; i--) + { + var record = EditJournal[i]; + if (record.IsUndo != reversesUndo) + { + continue; + } + var combined = record; + if (folded is not null) + { + if (record.FollowedBy(folded) is not { } joined) + { + return -1; + } + combined = joined; + } + if (combined.IsReversedBy(change)) + { + return i; + } + folded = combined; + } + return -1; } - private static int MapMark(int offset, TextChange change) + // A mark set since the reversed edit keeps its place, as Vim restores only the marks its undo step saved. + private void RestorePositions(VimPositionSnapshot saved) { - var removedEnd = change.Offset + change.RemovedLength; - if (offset >= removedEnd) + foreach (var (name, offset) in saved.Marks) { - return offset + change.InsertedLength - change.RemovedLength; + Marks[name] = offset; + if (saved.MarkColumns.TryGetValue(name, out var column)) + { + MarkColumns[name] = column; + } + else + { + MarkColumns.Remove(name); + } } - // Inside replaced text a mark keeps its place where the new text reaches it, as a case change does. - return offset >= change.Offset ? Math.Min(offset, change.Offset + change.InsertedLength) : offset; + LastJumpOrigin = saved.LastJumpOrigin ?? LastJumpOrigin; + LastInsertOffset = saved.LastInsertOffset ?? LastInsertOffset; + LastVisualStart = saved.LastVisualStart ?? LastVisualStart; + LastVisualEnd = saved.LastVisualEnd ?? LastVisualEnd; } internal void NoteEdit(int offset) diff --git a/windows/src/TablePro.Editor.Model/Vim/VimEngine.Search.cs b/windows/src/TablePro.Editor.Model/Vim/VimEngine.Search.cs index acd5a2fddf..778fa43d99 100644 --- a/windows/src/TablePro.Editor.Model/Vim/VimEngine.Search.cs +++ b/windows/src/TablePro.Editor.Model/Vim/VimEngine.Search.cs @@ -2,43 +2,44 @@ namespace TablePro.Editor.Model.Vim; public sealed partial class VimEngine { - internal void RunSearch(string pattern, bool forward) + internal void RunSearch(string pattern, bool forward, int count = 1) { - if (pattern.Length == 0) - { - return; - } - LastSearchPattern = pattern; - LastSearchForward = forward; var origin = _buffer.SelectedRange.Location; - if (FindPattern(pattern, origin, forward, wholeWord: false) is { } target) + if (SearchTarget(pattern, forward, count) is { } target) { _buffer.SetCaret(target); LastJumpOrigin = origin; } } - internal void SearchNext(bool reverseDirection) + // Remembers the pattern for n and N, as a search does even when nothing matches. + internal int? SearchTarget(string pattern, bool forward, int count = 1) { - if (LastSearchPattern is not { } pattern) + if (pattern.Length == 0) { - return; + return null; } - var forward = reverseDirection ? !LastSearchForward : LastSearchForward; - var origin = _buffer.SelectedRange.Location; - if (FindPattern(pattern, origin, forward, wholeWord: false) is { } target) + LastSearchPattern = pattern; + LastSearchForward = forward; + return RepeatFind(pattern, _buffer.SelectedRange.Location, forward, wholeWord: false, count); + } + + internal int? SearchNextTarget(int count, bool reverseDirection) + { + if (LastSearchPattern is not { } pattern) { - _buffer.SetCaret(target); - LastJumpOrigin = origin; + return null; } + var forward = reverseDirection ? !LastSearchForward : LastSearchForward; + return RepeatFind(pattern, _buffer.SelectedRange.Location, forward, wholeWord: false, count); } - internal void SearchWordUnderCursor(bool forward) + internal int? SearchWordUnderCursorTarget(bool forward, int count) { var pos = _buffer.SelectedRange.Location; if (pos >= _buffer.Length) { - return; + return null; } var start = pos; while (start > 0 && VimTextBuffer.IsWordChar(_buffer.CharAt(start - 1))) @@ -52,16 +53,26 @@ internal void SearchWordUnderCursor(bool forward) } if (end <= start) { - return; + return null; } var word = _buffer.Text(new VimRange(start, end - start)); LastSearchPattern = word; LastSearchForward = forward; - if (FindPattern(word, pos, forward, wholeWord: true) is { } target) + return RepeatFind(word, pos, forward, wholeWord: true, count); + } + + private int? RepeatFind(string pattern, int origin, bool forward, bool wholeWord, int count) + { + var position = origin; + for (var i = 0; i < Math.Max(1, count); i++) { - _buffer.SetCaret(target); - LastJumpOrigin = pos; + if (FindPattern(pattern, position, forward, wholeWord) is not { } next) + { + return null; + } + position = next; } + return position; } // Literal and case-sensitive, wrapping past either end, as the macOS engine searches. diff --git a/windows/src/TablePro.Editor.Model/Vim/VimEngine.TextObjects.cs b/windows/src/TablePro.Editor.Model/Vim/VimEngine.TextObjects.cs index 932d0aa5bd..343b6d4900 100644 --- a/windows/src/TablePro.Editor.Model/Vim/VimEngine.TextObjects.cs +++ b/windows/src/TablePro.Editor.Model/Vim/VimEngine.TextObjects.cs @@ -10,17 +10,26 @@ internal bool ExecuteTextObject(string key, bool around) PendingOperator = null; return true; } + // A paragraph is whole lines, every other object characters, and Visual mode takes the object's kind. + var linewise = key == "p"; if (_mode.IsVisual()) { + if (range.Length == 0) + { + return true; + } // The selection's ends become Visual's anchor and cursor, so the next motion grows it from there. + if (linewise != (_mode == VimMode.VisualLine)) + { + SetMode(linewise ? VimMode.VisualLine : VimMode.Visual); + } VisualAnchor = range.Location; - CursorOffset = range.Length > 0 ? CharacterStart(range.End - 1) : range.Location; - _buffer.SetSelectedRange(range); + UpdateVisualSelection(range.End - 1, linewise); return true; } if (PendingOperator is { } op) { - ExecuteOperatorOnRange(op, range, linewise: false); + ExecuteOperatorOnRange(op, range, linewise); PendingOperator = null; } return true; @@ -276,37 +285,44 @@ int ClassAt(int offset) return around ? new VimRange(os, closeEnd - os) : new VimRange(oe + 1, closeStart - oe - 1); } + // Whole lines: the run of paragraph or blank lines at the cursor. ap adds the blank lines after a paragraph, or the + // paragraph after blank lines, and with nothing after it the blank lines before. private VimRange? ParagraphObject(int cursor, bool around) { + var lineCount = _buffer.LineCount; var (currentLine, _) = _buffer.LineAndColumn(cursor); + var blank = LineIsWhite(currentLine); var startLine = currentLine; - while (startLine > 0 && !LineIsBlank(startLine - 1)) + while (startLine > 0 && LineIsWhite(startLine - 1) == blank) { startLine--; } var endLine = currentLine; - while (endLine < _buffer.LineCount - 1 && !LineIsBlank(endLine + 1)) + while (endLine < lineCount - 1 && LineIsWhite(endLine + 1) == blank) { endLine++; } - var start = _buffer.Offset(startLine, 0); - var end = _buffer.LineRange(_buffer.Offset(endLine, 0)).End; - if (!around && end > start && _buffer.CharAt(end - 1) == '\n') - { - end--; - } if (around) { - var trailing = endLine; - while (trailing < _buffer.LineCount - 1 && LineIsBlank(trailing + 1)) + var next = endLine; + while (next < lineCount - 1 && LineIsWhite(next + 1) != blank) { - trailing++; + next++; } - if (trailing > endLine) + if (next > endLine) { - end = _buffer.LineRange(_buffer.Offset(trailing, 0)).End; + endLine = next; + } + else if (!blank) + { + while (startLine > 0 && LineIsWhite(startLine - 1)) + { + startLine--; + } } } + var start = _buffer.Offset(startLine, 0); + var end = _buffer.LineRange(_buffer.Offset(endLine, 0)).End; return new VimRange(start, end - start); } } diff --git a/windows/src/TablePro.Editor.Model/Vim/VimEngine.Visual.cs b/windows/src/TablePro.Editor.Model/Vim/VimEngine.Visual.cs index 0885682def..59c7ec441c 100644 --- a/windows/src/TablePro.Editor.Model/Vim/VimEngine.Visual.cs +++ b/windows/src/TablePro.Editor.Model/Vim/VimEngine.Visual.cs @@ -3,6 +3,17 @@ namespace TablePro.Editor.Model.Vim; public sealed partial class VimEngine { private bool ProcessVisual(string key, bool shift) + { + var consumed = ProcessVisualKey(key); + // A register named in Visual mode belongs to the command that ends it, used or not. + if (!_mode.IsVisual()) + { + SelectedRegister = null; + } + return consumed; + } + + private bool ProcessVisualKey(string key) { var buffer = _buffer; if (PendingReplaceCharForVisual) @@ -19,6 +30,15 @@ private bool ProcessVisual(string key, bool shift) PendingTextObject = false; return key == Escape || ExecuteTextObject(key, PendingTextObjectAround); } + if (PendingRegisterSelect) + { + PendingRegisterSelect = false; + if (key != Escape) + { + SelectedRegister = key == "\"" ? null : key; + } + return true; + } var linewise = _mode == VimMode.VisualLine; @@ -136,8 +156,11 @@ private bool ProcessVisual(string key, bool shift) buffer.SetCaret(Math.Min(buffer.SelectedRange.End, buffer.Length)); SetMode(VimMode.Insert); return true; + case "\"": + PendingRegisterSelect = true; + return true; case "p" or "P": - PasteOverVisualSelection(); + PasteOverVisualSelection(keepingRegister: key == "P", linewise); return true; case "d" or "x": { @@ -300,16 +323,22 @@ internal void ReplaceVisualSelectionWithChar(string key) SetMode(VimMode.Normal); } - internal void PasteOverVisualSelection() + // p puts the text it replaces in the unnamed register, P leaves the registers as they were. + internal void PasteOverVisualSelection(bool keepingRegister, bool linewise) { var selection = _buffer.SelectedRange; - var text = Register.Text; + var text = ActivePasteRegister().Text; if (selection.Length <= 0) { SetMode(VimMode.Normal); return; } + var replaced = _buffer.Text(selection); _buffer.Replace(selection, text); + if (!keepingRegister) + { + WriteToActiveRegister(replaced, linewise, asDelete: true); + } _buffer.SetCaret(Math.Max(selection.Location, selection.Location + text.Length - 1)); SetMode(VimMode.Normal); } diff --git a/windows/src/TablePro.Editor.Model/Vim/VimEngine.cs b/windows/src/TablePro.Editor.Model/Vim/VimEngine.cs index 96d1ed2f8c..8ae8b45add 100644 --- a/windows/src/TablePro.Editor.Model/Vim/VimEngine.cs +++ b/windows/src/TablePro.Editor.Model/Vim/VimEngine.cs @@ -17,6 +17,10 @@ public sealed partial class VimEngine : IDisposable private string _commandLine = string.Empty; private int _depth; private UndoMark? _insertMark; + // The redo count the last replayed change saw, or the engine found, which tells an undo from a redo; null once any + // other edit lands, as it empties the redo stack. + private int? _replayRedoCount; + private bool _replayUndoes; private (VimMode, string, string, string?) _shownStatus; public VimEngine(EditorModel model, IVimHost host, VimRegisters? registers = null) @@ -28,6 +32,8 @@ public VimEngine(EditorModel model, IVimHost host, VimRegisters? registers = nul model.Document.Reset += OnDocumentReset; model.Document.Changed += OnDocumentChanged; model.SelectionsChanged += OnSelectionsChanged; + // A document can come with steps already undone, so the first replay may be a redo. + _replayRedoCount = model.Document.Undo.RedoCount; _shownStatus = StatusKey(); } @@ -179,6 +185,17 @@ internal VimRegister Register internal List ReplaceModeEdits { get; } = []; + internal int SearchCount { get; set; } = 1; + + // The column each named mark was set at, kept past the end of a line that shrinks, as Vim keeps it. + internal Dictionary MarkColumns { get; private set; } = new(StringComparer.Ordinal); + + // Recent edits with the positions from before each, so undoing one puts them back. + internal List EditJournal { get; } = []; + + // The removed and inserted text the journal holds, in UTF-16 units. + internal int EditJournalTextLength { get; private set; } + public bool Process(char key, bool shift = false) => Process(key.ToString(), shift); // True when the engine took the key; false leaves it to the editor, as typing in Insert mode is. @@ -274,7 +291,8 @@ internal int ConsumeCount() return (int)Math.Min(motionCount * opCount, MaxCount); } - // Escape drops every prefix of a command still being typed, so nothing of it reaches the next key. + // Escape, leaving the command line or a motion that finds nothing ends the whole command, so no part of it + // reaches the next key. internal void CancelPending() { PendingOperator = null; @@ -293,6 +311,7 @@ internal void CancelPending() PendingMacroTarget = null; PendingMacroCount = 1; PendingBracket = null; + SearchCount = 1; } // A paste, a click or a menu command moves the selection Visual mode was built on, so the mode ends with it. @@ -308,6 +327,10 @@ private void OnSelectionsChanged(object? sender, EventArgs e) private void OnDocumentReset(object? sender, EventArgs e) { Marks = new Dictionary(StringComparer.Ordinal); + MarkColumns = new Dictionary(StringComparer.Ordinal); + EditJournal.Clear(); + EditJournalTextLength = 0; + _replayRedoCount = null; LastVisualStart = null; LastVisualEnd = null; LastVisualLinewise = false; @@ -319,10 +342,16 @@ private void OnDocumentReset(object? sender, EventArgs e) _insertMark = null; } - private bool HasPendingCommand => CountPrefix > 0 || OperatorCount > 0 || PendingOperator is not null || PendingG - || PendingFindChar is not null || PendingReplaceChar || PendingMarkSet || PendingMarkJumpExact is not null - || PendingRegisterSelect || SelectedRegister is not null || PendingReplaceCharForVisual || PendingZ - || PendingTextObject || PendingMacroTarget is not null || PendingBracket is not null; + private bool HasPendingCommand => WaitsForKey || CountPrefix > 0 || OperatorCount > 0 || SelectedRegister is not null; + + // A key still waits for the rest of its command, not counting a count or a register already typed. + private bool WaitsForKey => PendingOperator is not null || PendingG || PendingFindChar is not null || PendingReplaceChar + || PendingMarkSet || PendingMarkJumpExact is not null || PendingRegisterSelect || PendingReplaceCharForVisual + || PendingZ || PendingTextObject || PendingMacroTarget is not null || PendingBracket is not null; + + private bool TakesCharacterArgument => PendingFindChar is not null || PendingReplaceChar || PendingMarkSet + || PendingMarkJumpExact is not null || PendingZ || PendingTextObject || PendingMacroTarget is not null + || PendingBracket is not null; private void TrackPendingKeys(string key) { diff --git a/windows/src/TablePro.Editor.Model/Vim/VimMarkChange.cs b/windows/src/TablePro.Editor.Model/Vim/VimMarkChange.cs new file mode 100644 index 0000000000..198fe8f3ac --- /dev/null +++ b/windows/src/TablePro.Editor.Model/Vim/VimMarkChange.cs @@ -0,0 +1,167 @@ +namespace TablePro.Editor.Model.Vim; + +// One edit as Vim's line-based mark adjustment sees it (:help mark-motions), read from the change and the text after +// it. A mark keeps its line and column: lines added or removed before it move it, a join carries it with its text, and +// removing its whole line removes it. +internal readonly struct VimMarkChange +{ + private readonly int _location; + private readonly int _end; + private readonly int _delta; + private readonly string _removed; + private readonly string _inserted; + private readonly int _breaks; + private readonly bool _removesLineBreak; + // Whole lines removed or inserted at a line start, as dd, p and O and their undo make. + private readonly bool _isLinewise; + // As many line breaks go in as come out, so every line keeps its marks, as a shift or a case change does. + private readonly bool _keepsLines; + private readonly int _firstLineStart; + // Where the line that held the end of the removed text ended, in the old text. + private readonly int _endLineEnd; + // Where the line that holds the end of the inserted text ends, in the new text, before its break. + private readonly int _lastLineContentEnd; + + public VimMarkChange(TextChange change, VimTextBuffer buffer) + { + _location = change.Offset; + _end = change.Offset + change.RemovedLength; + _delta = change.InsertedLength - change.RemovedLength; + _removed = change.RemovedText; + _inserted = change.InsertedText; + _breaks = change.InsertedBreaks; + _removesLineBreak = change.RemovedBreaks > 0; + _keepsLines = change.RemovedBreaks == change.InsertedBreaks; + _firstLineStart = buffer.Model.Document.GetLineStart(change.StartLine); + var removedEndsWithBreak = _removed.Length == 0 || _removed[^1] == '\n'; + var insertedEndsWithBreak = _inserted.Length == 0 || _inserted[^1] == '\n'; + _isLinewise = _location == _firstLineStart && removedEndsWithBreak && insertedEndsWithBreak; + // The text after the edit is the text after the old end, so its line ends where the old one did. + var lastLine = buffer.LineRange(_location + change.InsertedLength); + var hasBreak = lastLine.Length > 0 && buffer.CharAt(lastLine.End - 1) == '\n'; + _endLineEnd = lastLine.End - _delta; + _lastLineContentEnd = hasBreak ? lastLine.End - 1 : lastLine.End; + } + + // Null when the edit removes the line of a removable mark. KeepsColumn is false where the mark moved onto another + // line's text, as a join moves it. A boundary sits between characters, as the last insert position does, so it can + // stay at the end of its line rather than on the last character. + public (int Offset, bool KeepsColumn)? Map(int offset, bool removable, bool boundary = false) + { + if (offset < _location) + { + return (offset, true); + } + if (offset >= _endLineEnd) + { + return (offset + _delta, true); + } + if (_keepsLines) + { + return (KeepLineAndColumn(offset, boundary), true); + } + if (_isLinewise) + { + return offset >= _end ? (offset + _delta, true) : removable ? null : (_location, false); + } + if (offset >= _end) + { + return _removesLineBreak ? (offset + _delta, false) : (KeepColumnOnFirstLine(offset, boundary), true); + } + if (_removesLineBreak && offset > _location && _removed.LastIndexOf('\n', offset - _location - 1) >= 0) + { + var nextBreak = _removed.IndexOf('\n', offset - _location); + var lineEnd = nextBreak >= 0 ? _location + nextBreak + 1 : _endLineEnd; + if (lineEnd <= _end) + { + return removable ? null : (_location, false); + } + return (_end + _delta, false); + } + return (KeepColumnOnFirstLine(offset, boundary), true); + } + + // The first line keeps its start, so the offset keeps its column, up to the line's new last character. + private int KeepColumnOnFirstLine(int offset, bool boundary) + { + var firstBreak = _inserted.IndexOf('\n'); + var contentEnd = firstBreak >= 0 ? _location + firstBreak : _lastLineContentEnd; + return Math.Min(offset, Math.Max(_firstLineStart, boundary ? contentEnd : contentEnd - 1)); + } + + // The mark's line is the same line of the new text, at the same column up to that line's last character. + private int KeepLineAndColumn(int offset, bool boundary) + { + var relative = Math.Min(offset - _location, _removed.Length); + var line = 0; + var lineStart = _firstLineStart; + for (var i = 0; i < relative; i++) + { + if (_removed[i] == '\n') + { + line++; + lineStart = _location + i + 1; + } + } + var column = offset - lineStart; + var newStart = line == 0 ? _firstLineStart : _location + NthBreak(_inserted, line) + 1; + var newContentEnd = line < _breaks ? _location + NthBreak(_inserted, line + 1) : _lastLineContentEnd; + return newStart + Math.Min(column, Math.Max(0, newContentEnd - newStart - (boundary ? 0 : 1))); + } + + private static int NthBreak(string text, int n) + { + var index = -1; + for (var i = 0; i < n; i++) + { + index = text.IndexOf('\n', index + 1); + } + return index; + } +} + +// Where the marks were before one edit. +internal sealed record VimPositionSnapshot( + Dictionary Marks, + Dictionary MarkColumns, + int? LastJumpOrigin, + int? LastInsertOffset, + int? LastVisualStart, + int? LastVisualEnd); + +// One edit and the positions from before it. Undo reverses edits newest first, so the reversing edit finds its record +// at the end of the journal. +// IsUndo marks an undo's own edit, which only a redo reverses. +internal sealed record VimEditRecord( + int Location, + string RemovedText, + string InsertedText, + VimPositionSnapshot Positions, + bool IsUndo) +{ + public int TextLength => RemovedText.Length + InsertedText.Length; + + public bool IsReversedBy(TextChange change) => change.Offset == Location && change.RemovedLength == InsertedText.Length + && string.Equals(change.InsertedText, RemovedText, StringComparison.Ordinal); + + // This edit and the next as one, when the next touches the text this one left, with this one's positions. + public VimEditRecord? FollowedBy(VimEditRecord next) + { + var end = Location + InsertedText.Length; + var nextEnd = next.Location + next.RemovedText.Length; + if (next.Location > end || nextEnd < Location) + { + return null; + } + var before = next.Location < Location ? next.RemovedText[..(Location - next.Location)] : string.Empty; + var after = nextEnd > end ? next.RemovedText[(end - next.Location)..] : string.Empty; + var keptHead = next.Location > Location ? InsertedText[..(next.Location - Location)] : string.Empty; + var keptTail = nextEnd < end ? InsertedText[(nextEnd - Location)..] : string.Empty; + return new VimEditRecord( + Math.Min(Location, next.Location), + before + RemovedText + after, + keptHead + next.InsertedText + keptTail, + Positions, + IsUndo); + } +} diff --git a/windows/src/TablePro.Editor.Model/Vim/VimTypes.cs b/windows/src/TablePro.Editor.Model/Vim/VimTypes.cs index 2557a8102a..692859b1c8 100644 --- a/windows/src/TablePro.Editor.Model/Vim/VimTypes.cs +++ b/windows/src/TablePro.Editor.Model/Vim/VimTypes.cs @@ -90,6 +90,14 @@ internal enum VimOperator Outdent, } +// :help exclusive, :help inclusive, :help linewise. +internal enum VimMotionKind +{ + Exclusive, + Inclusive, + Linewise, +} + internal sealed record VimFindCharRequest(bool Forward, bool Till); internal sealed record VimLastFindChar(string Char, bool Forward, bool Till); diff --git a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimCommandEdgeTests.cs b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimCommandEdgeTests.cs index 44891ea61a..202e4fd7f6 100644 --- a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimCommandEdgeTests.cs +++ b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimCommandEdgeTests.cs @@ -60,24 +60,24 @@ public void ACountedPasteFromARegisterPastesItEachTime() } [Fact] - public void AMarkMovesWithTextTypedBeforeIt() + public void AMarkKeepsItsColumnWhenTextIsTypedBeforeItOnItsLine() { var s = new VimSession("one two", caret: 4); s.Press("ma0i"); s.Type("X"); s.Escape(); s.Press("`a"); - Assert.Equal(5, s.Caret); + Assert.Equal(4, s.Caret); } [Fact] - public void AMarkMovesBackWithAnUndo() + public void AMarkKeepsItsColumnThroughAnUndoOnItsLine() { var s = new VimSession("one two", caret: 0); s.Press("x"); s.Press("wmau`a"); Assert.Equal("one two", s.Text); - Assert.Equal(4, s.Caret); + Assert.Equal(3, s.Caret); } [Fact] diff --git a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineCommandLineTests.cs b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineCommandLineTests.cs index a279dca4ce..94ae789fde 100644 --- a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineCommandLineTests.cs +++ b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineCommandLineTests.cs @@ -192,4 +192,80 @@ public void DisplayLabelShowsBufferInCommandLineMode() s.Press(":wq"); Assert.Equal(":wq", s.Engine.ModeLabel); } + + [Fact] + public void ASearchAfterAnOperatorIsItsMotion() + { + var s = new VimSession(Initial); + s.Press("d/sec"); + Enter(s); + Assert.Equal("second line\nthird line\n", s.Text); + Assert.Equal("hello world\n", s.Engine.Register.Text); + Assert.True(s.Engine.Register.IsLinewise); + Assert.Equal(VimMode.Normal, s.Mode); + } + + [Fact] + public void ABackwardSearchAfterAnOperatorDeletesBackToTheMatch() + { + var s = new VimSession(Initial, caret: 6); + s.Press("d?ll"); + Enter(s); + Assert.Equal("heworld\nsecond line\nthird line\n", s.Text); + } + + [Theory] + [InlineData("2d/x")] + [InlineData("d2/x")] + public void ACountWithASearchAfterAnOperatorDeletesUpToThatMatch(string keys) + { + var s = new VimSession("x one x two x three x\n"); + s.Press(keys); + Enter(s); + Assert.Equal("x three x\n", s.Text); + } + + [Fact] + public void ACountBeforeASearchGoesToThatMatch() + { + var s = new VimSession("x one x two x three x\n"); + s.Press("2/x"); + Enter(s); + Assert.Equal(12, s.Caret); + } + + [Fact] + public void LeavingTheCommandLineDropsTheSearchCount() + { + var s = new VimSession("x one x two x three x\n"); + s.Press("2/"); + s.Escape(); + s.Press("/x"); + Enter(s); + Assert.Equal(6, s.Caret); + } + + [Fact] + public void ASearchWithNoMatchAfterAnOperatorEndsTheCommand() + { + var s = new VimSession(Initial); + s.Press("d/zzz"); + Enter(s); + Assert.False(s.Engine.IsPending); + s.Press("w"); + Assert.Equal(Initial, s.Text); + Assert.Equal(6, s.Caret); + } + + [Fact] + public void AnExCommandAfterAnOperatorRunsAndDropsTheOperator() + { + var s = new VimSession(Initial); + s.Press("d:w"); + Enter(s); + Assert.Equal(["w"], s.Commands); + s.Press("w"); + Assert.Equal(Initial, s.Text); + Assert.Equal(6, s.Caret); + } } diff --git a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineCountPrefixTests.cs b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineCountPrefixTests.cs index 5b7f0a2ecf..c987639d3a 100644 --- a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineCountPrefixTests.cs +++ b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineCountPrefixTests.cs @@ -150,4 +150,41 @@ public void CountInsideInsertModePassesThrough() s.Press("i"); Assert.False(s.Key("3"), "Digits in insert mode must pass through to the text view"); } + + [Fact] + public void ACountBeforeACommandThatTakesNoneIsDropped() + { + var s = new VimSession("abcdef\n", caret: 0); + s.Press("3max"); + Assert.Equal("bcdef\n", s.Text); + } + + [Fact] + public void ARegisterBeforeAMotionIsDroppedWithIt() + { + var s = new VimSession("one two three\n", caret: 0); + s.Press("\"awyw"); + Assert.False(s.Engine.NamedRegisters.ContainsKey("a")); + Assert.Equal("two ", s.Engine.Register.Text); + } + + [Fact] + public void TwoQuotesNameTheUnnamedRegister() + { + var s = new VimSession("one two three\n", caret: 0); + s.Press("\"a\"\"yw"); + Assert.False(s.Engine.NamedRegisters.ContainsKey("a")); + Assert.Equal("one ", s.Engine.Register.Text); + } + + [Fact] + public void EscapeDropsARegisterTypedBeforeIt() + { + var s = new VimSession("one two\n", caret: 0); + s.Press("\"a"); + s.Escape(); + s.Press("yw"); + Assert.False(s.Engine.NamedRegisters.ContainsKey("a")); + Assert.Equal("one ", s.Engine.Register.Text); + } } diff --git a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineFindCharTests.cs b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineFindCharTests.cs index f0c4189d90..12e94ddf9b 100644 --- a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineFindCharTests.cs +++ b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineFindCharTests.cs @@ -284,4 +284,42 @@ public void FThenEscapeCancels() s.Press("l"); Assert.Equal(1, s.Caret); } + + [Fact] + public void DCapitalFStopsShortOfTheCharacterUnderTheCursor() + { + var s = new VimSession("abcdef\n", caret: 4); + s.Press("dFb"); + Assert.Equal("aef\n", s.Text); + Assert.Equal("bcd", s.Engine.Register.Text); + } + + [Fact] + public void DCapitalTKeepsTheTargetAndTheCharacterUnderTheCursor() + { + var s = new VimSession("abcdef\n", caret: 4); + s.Press("dTb"); + Assert.Equal("abef\n", s.Text); + Assert.Equal("cd", s.Engine.Register.Text); + } + + [Theory] + [InlineData("d;w")] + [InlineData("d,w")] + public void ARepeatedFindWithNothingToRepeatEndsTheCommand(string keys) + { + var s = new VimSession("one two three\n", caret: 0); + s.Press(keys); + Assert.Equal("one two three\n", s.Text); + Assert.Equal(4, s.Caret); + } + + [Fact] + public void AFailedRepeatedFindDropsTheOperator() + { + var s = At(0); + s.Press("fbd;w"); + Assert.Equal(Standard, s.Text); + Assert.Equal(20, s.Caret); + } } diff --git a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineIndentTests.cs b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineIndentTests.cs index fcecc0c6e6..b45f39f9f0 100644 --- a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineIndentTests.cs +++ b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineIndentTests.cs @@ -87,4 +87,21 @@ public void IndentMovesCursorToFirstNonBlank() s.Press(">>"); Assert.Equal(Indent.Length, s.Caret); } + + [Fact] + public void GreaterBAtTheStartOfTheTextShiftsNothing() + { + var s = new VimSession("abc\n", caret: 0); + s.Press(">b"); + Assert.Equal("abc\n", s.Text); + Assert.False(s.Engine.IsPending); + } + + [Fact] + public void GreaterHAtTheLineStartStillShiftsTheLine() + { + var s = new VimSession("abc\n", caret: 0); + s.Press(">h"); + Assert.Equal($"{Indent}abc\n", s.Text); + } } diff --git a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineInsertEntryTests.cs b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineInsertEntryTests.cs index ad769d2eeb..3d2ae9ecff 100644 --- a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineInsertEntryTests.cs +++ b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineInsertEntryTests.cs @@ -305,4 +305,17 @@ public void ModeChangeCallbackFiresOnInsertExit() s.Escape(); Assert.Equal(VimMode.Normal, captured); } + + [Fact] + public void GiAfterAnEditOnTheLineResumesAtTheLineEnd() + { + var s = new VimSession("abc\ntail\n", caret: 0); + s.Press("A"); + s.Type("X"); + s.Escape(); + s.Press("0rYgi"); + s.Type("Z"); + s.Escape(); + Assert.Equal("YbcXZ\ntail\n", s.Text); + } } diff --git a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineMarksAndRegistersTests.cs b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineMarksAndRegistersTests.cs index 824ea95d05..2405fc8b12 100644 --- a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineMarksAndRegistersTests.cs +++ b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineMarksAndRegistersTests.cs @@ -1,3 +1,5 @@ +using TablePro.Editor.Model.Vim; + namespace TablePro.Editor.Model.Tests.Vim; public sealed class VimEngineMarksAndRegistersTests @@ -158,4 +160,297 @@ public void UppercaseRegisterAppends() s.Press("\"ap"); Assert.Contains("hello world\nsecond line\nhello world\nsecond line\n", s.Text, StringComparison.Ordinal); } + + [Fact] + public void ALineTypedAboveAMarkMovesItDownWithItsLine() + { + var s = new VimSession(Initial, caret: 25); + s.Press("maggO"); + s.Type("new"); + s.Escape(); + s.Press("`a"); + Assert.Equal(29, s.Caret); + } + + [Fact] + public void TextTypedBeforeAMarkOnItsLineKeepsItsColumn() + { + var s = new VimSession(Initial, caret: 6); + s.Press("ma0i"); + s.Type("XX"); + s.Escape(); + s.Press("`a"); + Assert.Equal(6, s.Caret); + } + + [Fact] + public void ALinePastedAboveAMarkMovesItDown() + { + var s = new VimSession(Initial, caret: 25); + s.Press("maggyyP`a"); + Assert.Equal(37, s.Caret); + } + + [Fact] + public void ALineBroughtBackByUndoAboveAMarkMovesItDown() + { + var s = new VimSession(Initial, caret: 0); + s.Press("ddjmau`a"); + Assert.Equal(Initial, s.Text); + Assert.Equal(24, s.Caret); + } + + [Fact] + public void DeletingTheMarkedLineRemovesTheMark() + { + var s = new VimSession(Initial, caret: 13); + s.Press("madd"); + Assert.False(s.Engine.Marks.ContainsKey("a")); + } + + [Fact] + public void UndoingTheDeleteBringsTheMarkBackOverOneSetSince() + { + var s = new VimSession(Initial, caret: 13); + s.Press("maddggmau"); + s.SetCaret(0); + s.Press("`a"); + Assert.Equal(13, s.Caret); + } + + [Fact] + public void UndoingTheDeleteOfAMarkedLineBringsTheMarkBack() + { + var s = new VimSession(Initial, caret: 13); + s.Press("madd"); + Assert.False(s.Engine.Marks.ContainsKey("a")); + s.Press("u"); + s.SetCaret(0); + s.Press("`a"); + Assert.Equal(Initial, s.Text); + Assert.Equal(13, s.Caret); + } + + [Fact] + public void UndoingAPasteOverTheMarkedLinesBringsTheMarkBack() + { + var s = new VimSession("foo\nbar\ntail\n", caret: 5); + s.Press("ma"); + s.Engine.Register = new VimRegister("new\n", IsLinewise: true); + s.SetCaret(0); + s.Press("Vjp"); + Assert.Equal("new\ntail\n", s.Text); + Assert.False(s.Engine.Marks.ContainsKey("a")); + s.Press("u"); + s.SetCaret(0); + s.Press("`a"); + Assert.Equal("foo\nbar\ntail\n", s.Text); + Assert.Equal(5, s.Caret); + } + + [Fact] + public void AMarkKeepsItsColumnThroughALineThatShrinksAndGrowsBack() + { + var s = new VimSession("abcdef\ntail\n", caret: 0); + s.Press("$ma0xxxi"); + s.Type("abc"); + s.Escape(); + s.Press("`a"); + Assert.Equal("abcdef\ntail\n", s.Text); + Assert.Equal(5, s.Caret); + } + + [Fact] + public void AJoinCarriesTheMarkWithItsText() + { + var s = new VimSession("hello world\n second\n", caret: 16); + s.Press("maggJ`a"); + Assert.Equal("hello world second\n", s.Text); + Assert.Equal(12, s.Caret); + } + + [Fact] + public void UndoingAnEditOnAJoinedLineAndTheJoinPutsTheMarkBack() + { + var s = new VimSession("aaa\nbbb\nccc\n", caret: 6); + s.Press("maggJ05xuu"); + s.SetCaret(0); + s.Press("`a"); + Assert.Equal("aaa\nbbb\nccc\n", s.Text); + Assert.Equal(6, s.Caret); + } + + [Fact] + public void UndoingBackspacesTheHistoryJoinedPutsTheMarkBack() + { + var s = new VimSession("aaa\nbbb\n", caret: 6); + s.Press("ma"); + s.SetCaret(4); + s.Press("i"); + // The editor deletes what Backspace takes in Insert mode, and its history joins the two into one step. + s.Model.Backspace(word: false); + s.Model.Backspace(word: false); + s.Escape(); + Assert.Equal("aabbb\n", s.Text); + s.Press("u"); + s.SetCaret(0); + s.Press("`a"); + Assert.Equal("aaa\nbbb\n", s.Text); + Assert.Equal(6, s.Caret); + } + + [Fact] + public void UndoingJoinedBackspacesAfterAnotherUndoPutsTheMarkBack() + { + var s = new VimSession("aaa\nbbb\n", caret: 6); + s.Press("ma"); + s.SetCaret(4); + s.Press("i"); + s.Model.Backspace(word: false); + s.Model.Backspace(word: false); + s.Escape(); + s.Press("0rXuu"); + s.SetCaret(0); + s.Press("`a"); + Assert.Equal("aaa\nbbb\n", s.Text); + Assert.Equal(6, s.Caret); + } + + [Fact] + public void UndoingARunOfFiftyOneBackspacesPutsTheMarkBack() + { + var text = new string('a', 60) + "\nbbb\n"; + var s = new VimSession(text, caret: 63); + s.Press("ma"); + s.SetCaret(61); + s.Press("i"); + for (var i = 0; i < 51; i++) + { + s.Model.Backspace(word: false); + } + s.Escape(); + s.Press("u"); + s.SetCaret(0); + s.Press("`a"); + Assert.Equal(text, s.Text); + Assert.Equal(63, s.Caret); + } + + [Fact] + public void UndoingALaterDeleteOfTheSameTextLeavesTheDeletedMarkUnset() + { + var s = new VimSession("aaa\nbbb\nccc\n", caret: 0); + s.Press("jmaddkpdd"); + s.Press("u"); + Assert.Equal("aaa\nbbb\nccc\n", s.Text); + Assert.False(s.Engine.Marks.ContainsKey("a")); + } + + [Fact] + public void AnUndoMatchesOnlyTheNewestEdits() + { + var s = new VimSession("aaaa\n", caret: 3); + s.Press("ma02xi"); + s.Type("aa"); + s.Escape(); + s.Press("0mai"); + // Two Delete presses the history joins into one change, the same text the earlier 2x removed. + s.Model.Delete(word: false); + s.Model.Delete(word: false); + s.Escape(); + s.Press("u"); + Assert.Equal("aaaa\n", s.Text); + Assert.Equal(0, s.Engine.Marks["a"]); + } + + [Fact] + public void AnEngineOnADocumentWithStepsUndoneTellsARedoFromAnUndo() + { + var s = new VimSession("aaa\nbbb\n"); + s.Engine.Dispose(); + s.Model.Document.Replace(4, 4, string.Empty); + s.Model.Undo(); + var engine = new VimEngine(s.Model, s, new VimRegisters()); + s.SetCaret(5); + engine.Process("m"); + engine.Process("a"); + s.Model.Redo(); + Assert.Equal("aaa\n", s.Text); + Assert.False(engine.Marks.ContainsKey("a")); + s.Model.Undo(); + Assert.Equal("aaa\nbbb\n", s.Text); + Assert.Equal(5, engine.Marks["a"]); + } + + [Fact] + public void UndoingAChangeWithALongInsertPutsTheMarkBack() + { + var s = new VimSession(Initial, caret: 25); + s.Press("maggcG"); + s.Type(new string('x', 150)); + s.Escape(); + s.Press("u"); + s.SetCaret(0); + s.Press("`a"); + Assert.Equal(Initial, s.Text); + Assert.Equal(25, s.Caret); + } + + [Fact] + public void ASecondUndoSkipsTheRecordTheFirstUndoMade() + { + var s = new VimSession("aaa\nbbb\n", caret: 6); + s.Press("magggJ"); + // A typed newline where the join took one out, so the first undo makes the edit the join made. + s.Model.NewLine(); + Assert.Equal("aaa\nbbb\n", s.Text); + s.Press("uu"); + s.SetCaret(0); + s.Press("`a"); + Assert.Equal("aaa\nbbb\n", s.Text); + Assert.Equal(6, s.Caret); + } + + [Fact] + public void UndoingAJoinPutsTheMarkBackOnItsLine() + { + var s = new VimSession("hello world\n second\n", caret: 16); + s.Press("maggJu"); + s.SetCaret(0); + s.Press("`a"); + Assert.Equal("hello world\n second\n", s.Text); + Assert.Equal(16, s.Caret); + } + + [Fact] + public void AShiftedLineKeepsItsMark() + { + var s = new VimSession("one\ntwo\n", caret: 5); + s.Press("ma>>`a"); + Assert.Equal(5, s.Caret); + s.Press("u`a"); + Assert.Equal(5, s.Caret); + } + + [Fact] + public void ThePreviousPositionMovesWithALineOpenedAboveIt() + { + var s = new VimSession(Initial, caret: 25); + s.Press("GO"); + s.Escape(); + s.Press("``"); + Assert.Equal(26, s.Caret); + } + + [Fact] + public void TheLastVisualSelectionMovesWithALineOpenedAboveIt() + { + var s = new VimSession("aa\nbb\ncc\n", caret: 3); + s.Press("vl"); + s.Escape(); + s.Press("ggO"); + s.Escape(); + s.Press("`<"); + Assert.Equal(4, s.Caret); + } } diff --git a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineNormalMotionsTests.cs b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineNormalMotionsTests.cs index c6ad64962a..9b0b72cae5 100644 --- a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineNormalMotionsTests.cs +++ b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineNormalMotionsTests.cs @@ -546,4 +546,55 @@ public void MotionsOnEmptyBufferDoNotCrash() Assert.Equal(0, s.Caret); Assert.Equal("", s.Text); } + + [Fact] + public void ACountBeforePercentGoesThatFarThroughTheText() + { + var s = At(0, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n"); + s.Press("50%"); + Assert.Equal(8, s.Caret); + } + + [Fact] + public void ACountAboveAHundredBeforePercentDoesNotMove() + { + var s = At(2, "a\nb\n"); + s.Press("101%"); + Assert.Equal(2, s.Caret); + Assert.False(s.Engine.IsPending); + } + + [Fact] + public void ACountBeforeHGoesToThatLineFromTheTop() + { + var s = At(6, "a\nb\nc\nd\n"); + s.Press("2H"); + Assert.Equal(2, s.Caret); + } + + [Fact] + public void ACountBeforeLGoesToThatLineFromTheBottom() + { + var s = At(0, "a\nb\nc\nd\n"); + s.Press("2L"); + Assert.Equal(4, s.Caret); + } + + [Fact] + public void ACountBeforeStarGoesToThatMatch() + { + var s = At(0, "foo x foo y foo z\n"); + s.Press("2*"); + Assert.Equal(12, s.Caret); + } + + [Fact] + public void PercentSetsThePreviousPosition() + { + var s = At(0, "(a) b\n"); + s.Press("%"); + Assert.Equal(2, s.Caret); + s.Press("``"); + Assert.Equal(0, s.Caret); + } } diff --git a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineOperatorsTests.cs b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineOperatorsTests.cs index 5eb5ed7ecf..ea9521eb6a 100644 --- a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineOperatorsTests.cs +++ b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineOperatorsTests.cs @@ -309,12 +309,12 @@ public void CCWithCount() } [Fact] - public void CWChangesWord() + public void CWChangesToTheWordEnd() { var s = new VimSession(Initial, caret: 0); s.Press("cw"); Assert.Equal(VimMode.Insert, s.Mode); - Assert.Equal("world\nsecond line\nthird line\n", s.Text); + Assert.Equal(" world\nsecond line\nthird line\n", s.Text); } [Fact] @@ -400,4 +400,309 @@ public void DeleteAndPasteRoundTrip() s.Key("P", shift: true); Assert.Equal(Initial, s.Text); } + + [Fact] + public void AKeyThatIsNotAMotionEndsTheOperator() + { + var s = new VimSession("one two\n", caret: 0); + s.Press("dxw"); + Assert.Equal("one two\n", s.Text); + Assert.Equal(4, s.Caret); + } + + [Theory] + [InlineData("dgi")] + [InlineData("dgv")] + [InlineData("dgJ")] + [InlineData("dgu")] + public void AGCommandThatIsNotAMotionEndsTheOperator(string keys) + { + var s = new VimSession("one\ntwo\n", caret: 0); + s.Press(keys); + Assert.Equal(VimMode.Normal, s.Mode); + Assert.False(s.Engine.IsPending); + s.Press("w"); + Assert.Equal("one\ntwo\n", s.Text); + Assert.Equal(4, s.Caret); + } + + [Fact] + public void DPercentDeletesThroughTheMatchingBracket() + { + var s = new VimSession("a (b c) d\n", caret: 2); + s.Press("d%"); + Assert.Equal("a d\n", s.Text); + Assert.Equal("(b c)", s.Engine.Register.Text); + } + + [Fact] + public void CPercentChangesTheBracketedText() + { + var s = new VimSession("a (b c) d\n", caret: 2); + s.Press("c%"); + Assert.Equal("a d\n", s.Text); + Assert.Equal(VimMode.Insert, s.Mode); + Assert.Equal(2, s.Caret); + } + + [Fact] + public void DPercentWithNoBracketEndsTheCommand() + { + var s = new VimSession("a b c d\n", caret: 0); + s.Press("d%w"); + Assert.Equal("a b c d\n", s.Text); + Assert.Equal(2, s.Caret); + } + + [Fact] + public void DCountPercentTakesTheLinesThatFarThrough() + { + var s = new VimSession("a\nb\nc\nd\n", caret: 0); + s.Press("d50%"); + Assert.Equal("c\nd\n", s.Text); + Assert.True(s.Engine.Register.IsLinewise); + } + + [Fact] + public void DnDeletesUpToTheNextMatch() + { + var s = new VimSession("foo bar foo baz\n", caret: 0); + s.Press("/foo\r0dn"); + Assert.Equal("foo baz\n", s.Text); + Assert.Equal("foo bar ", s.Engine.Register.Text); + } + + [Fact] + public void DStarDeletesUpToTheNextMatchOfTheWord() + { + var s = new VimSession("foo x foo y\n", caret: 0); + s.Press("d*"); + Assert.Equal("foo y\n", s.Text); + } + + [Fact] + public void DRightParenDeletesUpToTheNextSentence() + { + var s = new VimSession("One. Two. Three.\n", caret: 0); + s.Press("d)"); + Assert.Equal("Two. Three.\n", s.Text); + } + + [Fact] + public void DSectionDeletesUpToTheNextSection() + { + var s = new VimSession("x\n{\ny\n}\n", caret: 0); + s.Press("d]]"); + Assert.Equal("{\ny\n}\n", s.Text); + } + + [Fact] + public void DQuoteMarkTakesTheLinesThroughTheMark() + { + var s = new VimSession("aaa\nbbb\nccc\n", caret: 8); + s.Press("magg"); + s.Press("d'a"); + Assert.Equal(string.Empty, s.Text); + Assert.Equal("aaa\nbbb\nccc\n", s.Engine.Register.Text); + } + + [Fact] + public void DBacktickMarkDeletesUpToTheMark() + { + var s = new VimSession("aaa\nbbb\nccc\n", caret: 5); + s.Press("magg"); + s.Press("d`a"); + Assert.Equal("bb\nccc\n", s.Text); + } + + [Fact] + public void DQuoteOnAnUnsetMarkEndsTheCommand() + { + var s = new VimSession("aaa bbb\n", caret: 0); + s.Press("d'aw"); + Assert.Equal("aaa bbb\n", s.Text); + Assert.Equal(4, s.Caret); + } + + [Fact] + public void DLTakesTheLinesToTheLastOnScreen() + { + var s = new VimSession("aaa\nbbb\nccc\n", caret: 0); + s.Press("dL"); + Assert.Equal(string.Empty, s.Text); + } + + [Fact] + public void DjOnTheLastLineDeletesNothing() + { + var s = new VimSession("aaa\nbbb\n", caret: 4); + s.Press("djx"); + Assert.Equal("aaa\nbb\n", s.Text); + } + + [Fact] + public void DMinusOnTheFirstLineDeletesNothing() + { + var s = new VimSession("a\nb\n", caret: 0); + s.Press("d-x"); + Assert.Equal("\nb\n", s.Text); + } + + [Fact] + public void DPlusTakesTheLineAndTheNext() + { + var s = new VimSession("a\nb\nc\n", caret: 0); + s.Press("d+"); + Assert.Equal("c\n", s.Text); + } + + [Fact] + public void DbAtALineStartKeepsTheLineBreak() + { + var s = new VimSession("foo bar\nbaz\n", caret: 8); + s.Press("db"); + Assert.Equal("foo \nbaz\n", s.Text); + Assert.Equal("bar", s.Engine.Register.Text); + } + + [Fact] + public void DBraceFromTheIndentTakesTheParagraphsLines() + { + var s = new VimSession("aaa\nbbb\n\nccc\n", caret: 0); + s.Press("d}"); + Assert.Equal("\nccc\n", s.Text); + Assert.Equal("aaa\nbbb\n", s.Engine.Register.Text); + Assert.True(s.Engine.Register.IsLinewise); + } + + [Fact] + public void DBraceFromInsideALineStopsBeforeTheLineBreak() + { + var s = new VimSession("aaa\nbbb\n\nccc\n", caret: 1); + s.Press("d}"); + Assert.Equal("a\n\nccc\n", s.Text); + Assert.Equal("aa\nbbb", s.Engine.Register.Text); + Assert.False(s.Engine.Register.IsLinewise); + } + + [Fact] + public void DBraceOnTheLastParagraphTakesItsLines() + { + var s = new VimSession("aaa\nbbb\n", caret: 0); + s.Press("d}"); + Assert.Equal(string.Empty, s.Text); + Assert.True(s.Engine.Register.IsLinewise); + } + + [Fact] + public void DSearchFromTheIndentTakesWholeLines() + { + var s = new VimSession("hello world\nsecond line\n", caret: 0); + s.Press("d/sec\r"); + Assert.Equal("second line\n", s.Text); + Assert.True(s.Engine.Register.IsLinewise); + } + + [Fact] + public void DwOnTheLastWordStopsAtTheLineEnd() + { + var s = new VimSession("foo bar\nbaz\n", caret: 4); + s.Press("dw"); + Assert.Equal("foo \nbaz\n", s.Text); + } + + [Fact] + public void DBigWOnTheLastWordStopsAtTheLineEnd() + { + var s = new VimSession("foo b.r\n baz\n", caret: 4); + s.Press("dW"); + Assert.Equal("foo \n baz\n", s.Text); + } + + [Fact] + public void DwOnAnEmptyLineDeletesTheLine() + { + var s = new VimSession("aaa\n\nbbb\n", caret: 4); + s.Press("dw"); + Assert.Equal("aaa\nbbb\n", s.Text); + } + + [Fact] + public void DwOnAnEmptyLastLineDeletesNothing() + { + var s = new VimSession("aaa\n\n", caret: 4); + s.Press("dwk"); + Assert.Equal("aaa\n\n", s.Text); + Assert.Equal(0, s.Caret); + } + + [Fact] + public void CwWithACountChangesToTheLastWordsEnd() + { + var s = new VimSession("foo bar baz\n", caret: 0); + s.Press("2cw"); + Assert.Equal(" baz\n", s.Text); + Assert.Equal(VimMode.Insert, s.Mode); + } + + [Fact] + public void CwOnBlanksChangesThemUpToTheNextWord() + { + var s = new VimSession("foo bar\n", caret: 4); + s.Press("cw"); + Assert.Equal("foo bar\n", s.Text); + } + + [Fact] + public void CBigWChangesToTheBigWordsEnd() + { + var s = new VimSession("a.b c\n", caret: 0); + s.Press("cW"); + Assert.Equal(" c\n", s.Text); + } + + [Fact] + public void CjLeavesOneEmptyLineToTypeOn() + { + var s = new VimSession("a\nb\nc\n", caret: 0); + s.Press("cj"); + Assert.Equal("\nc\n", s.Text); + Assert.Equal(VimMode.Insert, s.Mode); + Assert.Equal(0, s.Caret); + Assert.Equal("a\nb\n", s.Engine.Register.Text); + } + + [Fact] + public void CBraceFromTheIndentLeavesOneEmptyLine() + { + var s = new VimSession("aaa\nbbb\n\nccc\n", caret: 0); + s.Press("c}"); + Assert.Equal("\n\nccc\n", s.Text); + Assert.Equal(VimMode.Insert, s.Mode); + } + + [Fact] + public void CGLeavesOneEmptyLine() + { + var s = new VimSession("a\nb\nc\n", caret: 2); + s.Press("cG"); + Assert.Equal("a\n\n", s.Text); + Assert.Equal(2, s.Caret); + } + + [Fact] + public void IndentWithACharacterMotionShiftsTheWholeLine() + { + var s = new VimSession("hello world\n", caret: 6); + s.Press(">w"); + Assert.Equal(" hello world\n", s.Text); + } + + [Fact] + public void IndentWithAWordObjectShiftsTheWholeLine() + { + var s = new VimSession("hello world\n", caret: 6); + s.Press(">iw"); + Assert.Equal(" hello world\n", s.Text); + } } diff --git a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEnginePasteTests.cs b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEnginePasteTests.cs index 56eced5731..550b4f6e9b 100644 --- a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEnginePasteTests.cs +++ b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEnginePasteTests.cs @@ -155,4 +155,31 @@ public void PasteInVisualReplacesSelectionWithRegister() Assert.Equal("hello hello ld\nsecond line\nthird line\n", s.Text); Assert.Equal(VimMode.Normal, s.Mode); } + + [Fact] + public void ALinewisePasteLeavesTheCursorOnTheFirstNonBlank() + { + var s = new VimSession(" ab\ncd\n", caret: 0); + s.Press("yyjp"); + Assert.Equal(" ab\ncd\n ab\n", s.Text); + Assert.Equal(10, s.Caret); + } + + [Fact] + public void PBelowALastLineWithNoBreakAddsTheBreakFirst() + { + var s = new VimSession("a\nb", caret: 2); + s.Press("yyp"); + Assert.Equal("a\nb\nb", s.Text); + Assert.Equal(4, s.Caret); + } + + [Fact] + public void APasteOverSeveralLinesLeavesTheCursorAtItsStart() + { + var s = new VimSession("ab cd\nef\n", caret: 1); + s.Press("vjy$p"); + Assert.Equal("ab cdb cd\nef\nef\n", s.Text); + Assert.Equal(5, s.Caret); + } } diff --git a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineSentenceParagraphTests.cs b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineSentenceParagraphTests.cs index 8d3f0c7c17..5519ca761c 100644 --- a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineSentenceParagraphTests.cs +++ b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineSentenceParagraphTests.cs @@ -105,4 +105,46 @@ public void SentenceBoundaryWithQuestion() s.Press(")"); Assert.Equal(5, s.Caret); } + + [Fact] + public void RightParenOnTheLastSentenceStopsOnTheLastCharacter() + { + var s = new VimSession("abc", caret: 0); + s.Press(")"); + Assert.Equal(2, s.Caret); + } + + [Fact] + public void DRightParenOnTheLastSentenceDeletesToTheEndOfTheText() + { + var s = new VimSession("abc", caret: 0); + s.Press("d)"); + Assert.Equal(string.Empty, s.Text); + } + + [Fact] + public void RightBraceOnTheLastParagraphStopsOnItsLastCharacter() + { + var s = new VimSession("aaa\nbbb\n", caret: 0); + s.Press("}"); + Assert.Equal(6, s.Caret); + } + + [Fact] + public void DoubleRightBracketWithCountGoesThatManySections() + { + var s = new VimSession("{\n a\n}\n{\n b\n}\n{\n c\n}\n", caret: 0); + s.Press("2]]"); + Assert.Equal(14, s.Caret); + } + + [Fact] + public void ParagraphAndSentenceMotionsSetThePreviousPosition() + { + var s = new VimSession("One. Two.\n\nThree.\n", caret: 0); + s.Press("}``"); + Assert.Equal(0, s.Caret); + s.Press(")``"); + Assert.Equal(0, s.Caret); + } } diff --git a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineTextObjectsTests.cs b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineTextObjectsTests.cs index 202ed27856..7830732c16 100644 --- a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineTextObjectsTests.cs +++ b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineTextObjectsTests.cs @@ -179,7 +179,8 @@ public void DIPDeletesInnerParagraph() { var s = new VimSession("para one\nstill one\n\npara two\n", caret: 3); s.Press("dip"); - Assert.Equal("\n\npara two\n", s.Text); + Assert.Equal("\npara two\n", s.Text); + Assert.True(s.Engine.Register.IsLinewise); } [Fact] @@ -229,4 +230,80 @@ public void DIParenWithCursorOnCloseParen() s.Press("di("); Assert.Equal("f()\n", s.Text); } + + [Fact] + public void YIPOnTheLastParagraphYanksItsLines() + { + var s = new VimSession("a\n\nb\nc", caret: 5); + s.Press("yip"); + Assert.Equal("b\nc", s.Engine.Register.Text); + Assert.True(s.Engine.Register.IsLinewise); + Assert.Equal(3, s.Caret); + } + + [Fact] + public void DIPOnTheLastParagraphDeletesItsLines() + { + var s = new VimSession("a\n\nb\nc", caret: 5); + s.Press("dip"); + Assert.Equal("a\n\n", s.Text); + } + + [Fact] + public void CIPLeavesOneEmptyLineToTypeOn() + { + var s = new VimSession("a\nb\n\nc\n", caret: 0); + s.Press("cip"); + Assert.Equal("\n\nc\n", s.Text); + Assert.Equal(VimMode.Insert, s.Mode); + } + + [Fact] + public void ALineOfOnlySpacesEndsTheParagraphForDIP() + { + var s = new VimSession("SELECT 1;\n \nSELECT 2;\n", caret: 0); + s.Press("dip"); + Assert.Equal(" \nSELECT 2;\n", s.Text); + } + + [Fact] + public void DAPTakesALineOfOnlySpacesAsTheBlankLineAfter() + { + var s = new VimSession("a\n \nb\n", caret: 0); + s.Press("dap"); + Assert.Equal("b\n", s.Text); + } + + [Fact] + public void DIPOnBlankLinesDeletesTheBlankLines() + { + var s = new VimSession("a\n\n\nb\n", caret: 2); + s.Press("dip"); + Assert.Equal("a\nb\n", s.Text); + } + + [Fact] + public void DAPOnBlankLinesDeletesThemAndTheParagraphAfter() + { + var s = new VimSession("a\n\n\nb\nc\n\nd\n", caret: 2); + s.Press("dap"); + Assert.Equal("a\n\nd\n", s.Text); + } + + [Fact] + public void DAPOnTheLastParagraphTakesTheBlankLinesBeforeIt() + { + var s = new VimSession("a\n\nb\nc\n", caret: 3); + s.Press("dap"); + Assert.Equal("a\n", s.Text); + } + + [Fact] + public void VisualIPSwitchesToVisualLine() + { + var s = new VimSession("a\nb\n\nc\n", caret: 0); + s.Press("vip"); + Assert.Equal(VimMode.VisualLine, s.Mode); + Assert.Equal((0, 4), s.Selection); + } } diff --git a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineVisualModeTests.cs b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineVisualModeTests.cs index 0b0c2a003e..dcb52e01dc 100644 --- a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineVisualModeTests.cs +++ b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineVisualModeTests.cs @@ -434,4 +434,68 @@ public void VisualLineDisplayLabel() s.Key("V", shift: true); Assert.Equal("VISUAL LINE", s.Engine.ModeLabel); } + + [Fact] + public void ARegisterBeforeYInVisualModeTakesTheYank() + { + var s = new VimSession("abc def\n", caret: 0); + s.Press("viw\"ay"); + Assert.Equal("abc", s.Engine.NamedRegisters["a"].Text); + } + + [Fact] + public void ARegisterBeforeDInVisualModeTakesTheDelete() + { + var s = new VimSession("abc def\n", caret: 0); + s.Press("viw\"bd"); + Assert.Equal(" def\n", s.Text); + Assert.Equal("abc", s.Engine.NamedRegisters["b"].Text); + } + + [Fact] + public void InnerWordInVisualLineModeSelectsTheWordCharacterwise() + { + var s = new VimSession("hello world\nfoo\n", caret: 0); + s.Press("Viwd"); + Assert.Equal(" world\nfoo\n", s.Text); + } + + [Fact] + public void PasteOverASelectionPutsTheReplacedTextInTheUnnamedRegister() + { + var s = new VimSession("abc def\n", caret: 0); + s.Press("yiwwviwp"); + Assert.Equal("abc abc\n", s.Text); + Assert.Equal("def", s.Engine.Register.Text); + } + + [Fact] + public void CapitalPOverASelectionLeavesTheRegisters() + { + var s = new VimSession("abc def\n", caret: 0); + s.Press("yiwwviwP"); + Assert.Equal("abc abc\n", s.Text); + Assert.Equal("abc", s.Engine.Register.Text); + } + + [Fact] + public void PasteOverASelectionFromANamedRegister() + { + var s = new VimSession("abc def\n", caret: 0); + s.Press("\"ayiwwviw\"ap"); + Assert.Equal("abc abc\n", s.Text); + Assert.Equal("abc", s.Engine.NamedRegisters["a"].Text); + Assert.Equal("def", s.Engine.Register.Text); + } + + [Fact] + public void EscapeDropsARegisterTypedInVisualMode() + { + var s = new VimSession("abc def\n", caret: 0); + s.Press("v\"a"); + s.Escape(); + s.Press("yiw"); + Assert.False(s.Engine.NamedRegisters.ContainsKey("a")); + Assert.Equal("abc", s.Engine.Register.Text); + } } diff --git a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineVisualReselectionTests.cs b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineVisualReselectionTests.cs index 36f1c2d4f4..04848cb09f 100644 --- a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineVisualReselectionTests.cs +++ b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimEngineVisualReselectionTests.cs @@ -80,4 +80,14 @@ public void GVWithNoPriorSelectionIsNoOp() s.Press("gv"); Assert.Equal(VimMode.Normal, s.Mode); } + + [Fact] + public void GVAfterUndoingAVisualDeleteReselectsTheDeletedLine() + { + var s = new VimSession("aaa\nbbb\nccc\n", caret: 0); + s.Press("jVdugv"); + Assert.Equal("aaa\nbbb\nccc\n", s.Text); + Assert.Equal(VimMode.VisualLine, s.Mode); + Assert.Equal((4, 4), s.Selection); + } } diff --git a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimUndoAndStatusTests.cs b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimUndoAndStatusTests.cs index a019ecfd1e..a69f355924 100644 --- a/windows/tests/TablePro.Editor.Model.Tests/Vim/VimUndoAndStatusTests.cs +++ b/windows/tests/TablePro.Editor.Model.Tests/Vim/VimUndoAndStatusTests.cs @@ -10,9 +10,8 @@ public sealed class VimUndoAndStatusTests public void AChangeAndTheTextTypedAfterItUndoAsOneStep() { var s = new VimSession("select name from t\n", caret: 7); - // cw takes the space after the word, as the macOS engine's does. s.Press("cw"); - s.Type("id, title "); + s.Type("id, title"); s.Escape(); Assert.Equal("select id, title from t\n", s.Text); s.Press("u");