@jadelclemens/pi-vim 0.0.0-stage → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/search.ts ADDED
@@ -0,0 +1,295 @@
1
+ /**
2
+ * Search system for vim.
3
+ *
4
+ * Supports:
5
+ * - `/pattern` forward search
6
+ * - `?pattern` backward search
7
+ * - `n` / `N` repeat search forward / backward
8
+ * - `*` / `#` search word under cursor forward / backward
9
+ *
10
+ * Search can also be used as a motion with operators (e.g., d/pattern).
11
+ */
12
+
13
+ import { matchesKey } from "@mariozechner/pi-tui";
14
+ import type { MotionFn, MotionResult, Position } from "./motions.js";
15
+
16
+ export interface SearchState {
17
+ /** Last search pattern (string, not regex) */
18
+ lastPattern: string | null;
19
+ /** Direction of the last search */
20
+ lastDirection: "forward" | "backward";
21
+ /** Current command-line input buffer for / or ? */
22
+ inputBuffer: string;
23
+ /** Whether we're currently in search command-line mode */
24
+ active: boolean;
25
+ /** The prompt character (/ or ?) */
26
+ prompt: string;
27
+ /** Mode to return to after search completes (normal or visual/visual-line) */
28
+ returnMode: "normal" | "visual" | "visual-line";
29
+ }
30
+
31
+ /** Global search state */
32
+ const searchState: SearchState = {
33
+ lastPattern: null,
34
+ lastDirection: "forward",
35
+ inputBuffer: "",
36
+ active: false,
37
+ prompt: "/",
38
+ returnMode: "normal",
39
+ };
40
+
41
+ export function getSearchState(): SearchState {
42
+ return searchState;
43
+ }
44
+
45
+ /**
46
+ * Begin a search command-line session.
47
+ */
48
+ export function beginSearch(
49
+ direction: "forward" | "backward",
50
+ returnMode: "normal" | "visual" | "visual-line" = "normal",
51
+ ): void {
52
+ searchState.active = true;
53
+ searchState.inputBuffer = "";
54
+ searchState.prompt = direction === "forward" ? "/" : "?";
55
+ searchState.lastDirection = direction;
56
+ searchState.returnMode = returnMode;
57
+ }
58
+
59
+ /**
60
+ * Handle a key during search command-line input.
61
+ * Returns:
62
+ * "continue" - keep accepting input
63
+ * "confirm" - user pressed Enter, execute the search
64
+ * "cancel" - user pressed Escape, cancel
65
+ */
66
+ export function handleSearchInput(data: string): "continue" | "confirm" | "cancel" {
67
+ // Escape or Ctrl+[ → cancel search
68
+ if (matchesKey(data, "escape") || data === "\x1b" || data === "\x1b[") {
69
+ searchState.active = false;
70
+ searchState.inputBuffer = "";
71
+ return "cancel";
72
+ }
73
+
74
+ // Enter → confirm search
75
+ if (data === "\r" || data === "\n") {
76
+ if (searchState.inputBuffer.length > 0) {
77
+ searchState.lastPattern = searchState.inputBuffer;
78
+ }
79
+ searchState.active = false;
80
+ return "confirm";
81
+ }
82
+
83
+ // Backspace
84
+ if (data === "\x7f") {
85
+ if (searchState.inputBuffer.length > 0) {
86
+ searchState.inputBuffer = searchState.inputBuffer.slice(0, -1);
87
+ } else {
88
+ // Backspace on empty input cancels search
89
+ searchState.active = false;
90
+ return "cancel";
91
+ }
92
+ return "continue";
93
+ }
94
+
95
+ // Ctrl+U → clear input
96
+ if (data === "\x15") {
97
+ searchState.inputBuffer = "";
98
+ return "continue";
99
+ }
100
+
101
+ // Printable character
102
+ if (data.length === 1 && data.charCodeAt(0) >= 32) {
103
+ searchState.inputBuffer += data;
104
+ return "continue";
105
+ }
106
+
107
+ // Ignore other control sequences
108
+ return "continue";
109
+ }
110
+
111
+ /**
112
+ * Get the current search prompt string for rendering (e.g., "/pattern").
113
+ */
114
+ export function getSearchPrompt(): string {
115
+ return searchState.prompt + searchState.inputBuffer;
116
+ }
117
+
118
+ /**
119
+ * Find all matches of a pattern in the text lines.
120
+ * Returns positions of all match starts.
121
+ */
122
+ function findAllMatches(lines: string[], pattern: string): Position[] {
123
+ if (!pattern) return [];
124
+
125
+ const matches: Position[] = [];
126
+ // Escape regex special chars for literal search
127
+ const escaped = pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
128
+ let regex: RegExp;
129
+ try {
130
+ regex = new RegExp(escaped, "gi");
131
+ } catch {
132
+ return [];
133
+ }
134
+
135
+ for (let line = 0; line < lines.length; line++) {
136
+ const text = lines[line] || "";
137
+ let m: RegExpExecArray | null;
138
+ regex.lastIndex = 0;
139
+ while ((m = regex.exec(text)) !== null) {
140
+ matches.push({ line, col: m.index });
141
+ // Prevent infinite loop on zero-length matches
142
+ if (m[0].length === 0) regex.lastIndex++;
143
+ }
144
+ }
145
+
146
+ return matches;
147
+ }
148
+
149
+ /**
150
+ * Find the next match after the given cursor position in the given direction.
151
+ * Wraps around the buffer.
152
+ */
153
+ export function findNextMatch(
154
+ lines: string[],
155
+ cursor: Position,
156
+ pattern: string,
157
+ direction: "forward" | "backward",
158
+ ): Position | null {
159
+ const matches = findAllMatches(lines, pattern);
160
+ if (matches.length === 0) return null;
161
+
162
+ if (direction === "forward") {
163
+ // Find first match strictly after cursor
164
+ for (const m of matches) {
165
+ if (m.line > cursor.line || (m.line === cursor.line && m.col > cursor.col)) {
166
+ return m;
167
+ }
168
+ }
169
+ // Wrap: return first match
170
+ return matches[0]!;
171
+ } else {
172
+ // Find last match strictly before cursor
173
+ for (let i = matches.length - 1; i >= 0; i--) {
174
+ const m = matches[i]!;
175
+ if (m.line < cursor.line || (m.line === cursor.line && m.col < cursor.col)) {
176
+ return m;
177
+ }
178
+ }
179
+ // Wrap: return last match
180
+ return matches[matches.length - 1]!;
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Get the word under the cursor (for * and # commands).
186
+ * A word is a sequence of word characters [a-zA-Z0-9_].
187
+ */
188
+ export function getWordUnderCursor(lines: string[], cursor: Position): string | null {
189
+ const line = lines[cursor.line] || "";
190
+ if (cursor.col >= line.length) return null;
191
+
192
+ const ch = line[cursor.col]!;
193
+ // Must be on a word character
194
+ if (!/[a-zA-Z0-9_]/.test(ch)) return null;
195
+
196
+ // Expand left
197
+ let start = cursor.col;
198
+ while (start > 0 && /[a-zA-Z0-9_]/.test(line[start - 1]!)) start--;
199
+
200
+ // Expand right
201
+ let end = cursor.col;
202
+ while (end < line.length - 1 && /[a-zA-Z0-9_]/.test(line[end + 1]!)) end++;
203
+
204
+ return line.substring(start, end + 1);
205
+ }
206
+
207
+ // --- Motion functions for search ---
208
+
209
+ /**
210
+ * Create a motion for `n` (repeat last search).
211
+ */
212
+ export const searchNext: MotionFn = (lines, cursor, count) => {
213
+ if (!searchState.lastPattern) {
214
+ return { position: cursor, linewise: false, inclusive: false };
215
+ }
216
+
217
+ let pos = cursor;
218
+ for (let i = 0; i < count; i++) {
219
+ const result = findNextMatch(lines, pos, searchState.lastPattern, searchState.lastDirection);
220
+ if (result) {
221
+ pos = result;
222
+ } else {
223
+ break;
224
+ }
225
+ }
226
+
227
+ return { position: pos, linewise: false, inclusive: false };
228
+ };
229
+
230
+ /**
231
+ * Create a motion for `N` (repeat last search in reverse direction).
232
+ */
233
+ export const searchPrev: MotionFn = (lines, cursor, count) => {
234
+ if (!searchState.lastPattern) {
235
+ return { position: cursor, linewise: false, inclusive: false };
236
+ }
237
+
238
+ const reverseDir = searchState.lastDirection === "forward" ? "backward" : "forward";
239
+
240
+ let pos = cursor;
241
+ for (let i = 0; i < count; i++) {
242
+ const result = findNextMatch(lines, pos, searchState.lastPattern, reverseDir);
243
+ if (result) {
244
+ pos = result;
245
+ } else {
246
+ break;
247
+ }
248
+ }
249
+
250
+ return { position: pos, linewise: false, inclusive: false };
251
+ };
252
+
253
+ /**
254
+ * Execute the confirmed search as a motion.
255
+ * Uses the pattern from the search state.
256
+ */
257
+ export function executeSearchMotion(
258
+ lines: string[],
259
+ cursor: Position,
260
+ ): MotionResult {
261
+ if (!searchState.lastPattern) {
262
+ return { position: cursor, linewise: false, inclusive: false };
263
+ }
264
+
265
+ const result = findNextMatch(lines, cursor, searchState.lastPattern, searchState.lastDirection);
266
+ if (result) {
267
+ return { position: result, linewise: false, inclusive: false };
268
+ }
269
+
270
+ return { position: cursor, linewise: false, inclusive: false };
271
+ }
272
+
273
+ /**
274
+ * Set up search for word under cursor (* or #).
275
+ */
276
+ export function searchWordUnderCursor(
277
+ lines: string[],
278
+ cursor: Position,
279
+ direction: "forward" | "backward",
280
+ ): MotionResult {
281
+ const word = getWordUnderCursor(lines, cursor);
282
+ if (!word) {
283
+ return { position: cursor, linewise: false, inclusive: false };
284
+ }
285
+
286
+ searchState.lastPattern = word;
287
+ searchState.lastDirection = direction;
288
+
289
+ const result = findNextMatch(lines, cursor, word, direction);
290
+ if (result) {
291
+ return { position: result, linewise: false, inclusive: false };
292
+ }
293
+
294
+ return { position: cursor, linewise: false, inclusive: false };
295
+ }
package/state.ts ADDED
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Vim state machine - tracks current mode, pending operations, and repeat info.
3
+ */
4
+
5
+ export type VimMode = "normal" | "insert" | "replace" | "visual" | "visual-line" | "command-line" | "operator-pending";
6
+
7
+ export interface RecordedChange {
8
+ /** The keys that triggered this change */
9
+ keys: string[];
10
+ /** Text inserted during insert mode (for dot-repeat) */
11
+ insertedText: string;
12
+ }
13
+
14
+ export interface VimState {
15
+ mode: VimMode;
16
+ /** Numeric prefix accumulator (0 = none) */
17
+ count: number;
18
+ /** Pending operator: 'd', 'c', 'y', '>', '<', etc. */
19
+ pendingOperator: string | null;
20
+ /** Count supplied before the pending operator (multiplied by motion count). */
21
+ pendingOperatorCount: number;
22
+ /** Current register ('"' = default) */
23
+ register: string;
24
+ /** Last recorded change for dot-repeat */
25
+ lastChange: RecordedChange | null;
26
+ /** Anchor position for visual mode */
27
+ visualAnchor: { line: number; col: number } | null;
28
+ /** Whether we're accumulating digits for a count */
29
+ countStarted: boolean;
30
+ /** Pending character motion: 'f', 'F', 't', 'T', or 'r' (waiting for next char) */
31
+ pendingCharMotion: string | null;
32
+ /** Whether we're waiting for the second key after 'g' (e.g., gg) */
33
+ pendingG: boolean;
34
+ /** Pending text object prefix: 'i' or 'a' (waiting for object key like w, ", (, etc.) */
35
+ pendingTextObjectPrefix: string | null;
36
+ /** Whether we're waiting for a register name after `"` */
37
+ pendingRegister: boolean;
38
+ /** Whether we're replaying a dot-repeat (suppress recording) */
39
+ isReplaying: boolean;
40
+ /** Remaining copies for a counted `O` insertion. */
41
+ openLineRepeatCount: number;
42
+ }
43
+
44
+ export function createInitialState(): VimState {
45
+ return {
46
+ mode: "insert",
47
+ count: 0,
48
+ pendingOperator: null,
49
+ pendingOperatorCount: 1,
50
+ register: '"',
51
+ lastChange: null,
52
+ visualAnchor: null,
53
+ countStarted: false,
54
+ pendingCharMotion: null,
55
+ pendingG: false,
56
+ pendingTextObjectPrefix: null,
57
+ pendingRegister: false,
58
+ isReplaying: false,
59
+ openLineRepeatCount: 1,
60
+ };
61
+ }
62
+
63
+ export function resetOperatorState(state: VimState): void {
64
+ state.count = 0;
65
+ state.countStarted = false;
66
+ state.pendingOperator = null;
67
+ state.pendingOperatorCount = 1;
68
+ state.pendingCharMotion = null;
69
+ state.pendingG = false;
70
+ state.pendingTextObjectPrefix = null;
71
+ state.pendingRegister = false;
72
+ state.register = '"';
73
+ }
74
+
75
+ export function modeDisplayName(mode: VimMode): string {
76
+ switch (mode) {
77
+ case "normal": return "NORMAL";
78
+ case "insert": return "INSERT";
79
+ case "replace": return "REPLACE";
80
+ case "visual": return "VISUAL";
81
+ case "visual-line": return "V-LINE";
82
+ case "command-line": return "COMMAND";
83
+ case "operator-pending": return "OP-PENDING";
84
+ }
85
+ }