@rse/ink-editor 0.0.0-stage → 0.9.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.
Files changed (63) hide show
  1. package/.claude/CLAUDE.md +1 -0
  2. package/AGENTS.md +99 -0
  3. package/CHANGELOG.md +9 -0
  4. package/README.md +116 -2
  5. package/dst-stage1/ink-editor-cli.d.ts +2 -0
  6. package/dst-stage1/ink-editor-cli.js +174 -0
  7. package/dst-stage1/ink-editor-engine-emacs.d.ts +103 -0
  8. package/dst-stage1/ink-editor-engine-emacs.js +1530 -0
  9. package/dst-stage1/ink-editor-engine-nano.d.ts +78 -0
  10. package/dst-stage1/ink-editor-engine-nano.js +884 -0
  11. package/dst-stage1/ink-editor-engine-vim.d.ts +124 -0
  12. package/dst-stage1/ink-editor-engine-vim.js +2220 -0
  13. package/dst-stage1/ink-editor-engine-vscode.d.ts +79 -0
  14. package/dst-stage1/ink-editor-engine-vscode.js +850 -0
  15. package/dst-stage1/ink-editor-mode-emacs.d.ts +12 -0
  16. package/dst-stage1/ink-editor-mode-emacs.js +143 -0
  17. package/dst-stage1/ink-editor-mode-nano.d.ts +12 -0
  18. package/dst-stage1/ink-editor-mode-nano.js +140 -0
  19. package/dst-stage1/ink-editor-mode-vim.d.ts +12 -0
  20. package/dst-stage1/ink-editor-mode-vim.js +230 -0
  21. package/dst-stage1/ink-editor-mode-vscode.d.ts +12 -0
  22. package/dst-stage1/ink-editor-mode-vscode.js +133 -0
  23. package/dst-stage1/ink-editor-mode.d.ts +72 -0
  24. package/dst-stage1/ink-editor-mode.js +24 -0
  25. package/dst-stage1/ink-editor-syntax.d.ts +14 -0
  26. package/dst-stage1/ink-editor-syntax.js +149 -0
  27. package/dst-stage1/ink-editor-text.d.ts +38 -0
  28. package/dst-stage1/ink-editor-text.js +177 -0
  29. package/dst-stage1/ink-editor-widget.d.ts +15 -0
  30. package/dst-stage1/ink-editor-widget.js +132 -0
  31. package/dst-stage1/ink-editor.d.ts +13 -0
  32. package/dst-stage1/ink-editor.js +37 -0
  33. package/dst-stage1/tsc.tsbuildinfo +1 -0
  34. package/dst-stage2/ink-editor-cli.esm.js +177 -0
  35. package/dst-stage2/ink-editor.esm.js +5972 -0
  36. package/etc/c8.json +17 -0
  37. package/etc/eslint.mts +84 -0
  38. package/etc/knip.jsonc +51 -0
  39. package/etc/stx.conf +103 -0
  40. package/etc/tsc.json +29 -0
  41. package/etc/vite.mts +79 -0
  42. package/package.d/@typescript-eslint+typescript-estree+8.74.0.patch +12 -0
  43. package/package.d/vite+8.4.1.patch +12 -0
  44. package/package.json +79 -5
  45. package/src/ink-editor-cli.ts +200 -0
  46. package/src/ink-editor-engine-emacs.ts +1648 -0
  47. package/src/ink-editor-engine-nano.ts +978 -0
  48. package/src/ink-editor-engine-vim.ts +2203 -0
  49. package/src/ink-editor-engine-vscode.ts +938 -0
  50. package/src/ink-editor-mode-emacs.ts +137 -0
  51. package/src/ink-editor-mode-nano.ts +135 -0
  52. package/src/ink-editor-mode-vim.ts +223 -0
  53. package/src/ink-editor-mode-vscode.ts +129 -0
  54. package/src/ink-editor-mode.ts +137 -0
  55. package/src/ink-editor-syntax.ts +176 -0
  56. package/src/ink-editor-text.ts +205 -0
  57. package/src/ink-editor-widget.ts +182 -0
  58. package/src/ink-editor.ts +48 -0
  59. package/tst/ink-editor-1-vim.spec.ts +177 -0
  60. package/tst/ink-editor-2-emacs.spec.ts +211 -0
  61. package/tst/ink-editor-3-nano.spec.ts +187 -0
  62. package/tst/ink-editor-4-vscode.spec.ts +187 -0
  63. package/tst/tsc.json +27 -0
@@ -0,0 +1,2220 @@
1
+ /*
2
+ ** Ink-Editor -- Text Editor with Exchangeable Editing Modes for Ink
3
+ ** Copyright (c) 2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
4
+ **
5
+ ** Permission is hereby granted, free of charge, to any person obtaining
6
+ ** a copy of this software and associated documentation files (the
7
+ ** "Software"), to deal in the Software without restriction, including
8
+ ** without limitation the rights to use, copy, modify, merge, publish,
9
+ ** distribute, sublicense, and/or sell copies of the Software, and to
10
+ ** permit persons to whom the Software is furnished to do so, subject to
11
+ ** the following conditions:
12
+ **
13
+ ** The above copyright notice and this permission notice shall be included
14
+ ** in all copies or substantial portions of the Software.
15
+ **
16
+ ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ ** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20
+ ** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
+ ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22
+ ** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
+ */
24
+ /* Vim editing engine, operating on a plain string value and key tokens
25
+ (dependency-free: it knows nothing about React, Ink, or any terminal) */
26
+ /* internal dependencies */
27
+ import { lineStart, lineEnd, lineNo, lineAt, toCursor, toOffset, isSpace, isIdent } from "./ink-editor-text";
28
+ /* the command vocabulary */
29
+ const MOTIONS = new Set([
30
+ "h", "j", "k", "l", "w", "b", "e", "W", "B", "E", "ge", "gE", "0", "^", "$", "g_", "|",
31
+ "G", "gg", "{", "}", "%", "f", "F", "t", "T", ";", ",", "n", "N", "*", "#", "+", "-", "_",
32
+ "`", "'", "<Left>", "<Right>", "<Up>", "<Down>", "<Home>", "<End>", "<BS>", "<C-h>", " ",
33
+ "<CR>", "<C-n>", "<C-p>", "<C-j>"
34
+ ]);
35
+ const NORMAL = new Set([
36
+ "x", "X", "D", "C", "s", "S", "Y", "p", "P", "J", "gJ", "u", "<C-r>", ".", "i", "a", "I", "A",
37
+ "gI", "gi", "o", "O", "R", "v", "V", "gv", "<C-v>", ":", "/", "?", "~", "&", "r", "m", "q",
38
+ "@", "ZZ", "ZQ", "zz", "zt", "zb", "z.", "z<CR>", "z-", "<C-d>", "<C-u>", "<C-f>", "<C-b>",
39
+ "<PageDown>", "<PageUp>", "<C-e>", "<C-y>", "<C-g>", "<C-a>", "<C-x>", "<C-c>", "<C-l>", "<Del>"
40
+ ]);
41
+ const VISUAL = new Set([
42
+ "d", "x", "X", "D", "<Del>", "y", "Y", "c", "s", "C", "S", "R", "r", "~", "u", "U", ">", "<",
43
+ "J", "gJ", "p", "P", "o", "O", "I", "A", ":", "v", "V", "<C-v>", "<Esc>", "<C-c>", "/", "?"
44
+ ]);
45
+ const OPERATORS = new Set(["d", "c", "y", "<", ">", "gu", "gU", "g~"]);
46
+ const ARGS = new Set(["f", "F", "t", "T", "`", "'", "r", "m", "q", "@"]);
47
+ const PREFIXES = new Set(["g", "Z", "z"]);
48
+ const JUMPS = new Set(["G", "gg", "{", "}", "%", "n", "N", "*", "#", "`", "'"]);
49
+ const OBJECT = /^[ia][wWp"'`()bB{}[\]<>]$/;
50
+ const PASSABLE = new Set(["<CR>", "<BS>", "<Del>", "<C-w>", "<Left>", "<Right>", "<Up>", "<Down>", "<Home>", "<End>"]);
51
+ const PAIRS = {
52
+ "(": ["(", ")"], ")": ["(", ")"], "b": ["(", ")"],
53
+ "{": ["{", "}"], "}": ["{", "}"], "B": ["{", "}"],
54
+ "[": ["[", "]"], "]": ["[", "]"],
55
+ "<": ["<", ">"], ">": ["<", ">"]
56
+ };
57
+ /* line geometry of a text */
58
+ const lineEndNl = (v, o) => { const e = lineEnd(v, o); return e < v.length ? e + 1 : e; };
59
+ const lastLine = (v) => lineNo(v, v.length);
60
+ const isEmpty = (v, l) => { const s = lineAt(v, l); return lineEnd(v, s) === s; };
61
+ /* grapheme stepping (a newline is always a grapheme of its own, so segment within lines only) */
62
+ const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
63
+ const prevGrapheme = (v, o) => {
64
+ if (o <= 0)
65
+ return 0;
66
+ const s = lineStart(v, o);
67
+ if (s === o)
68
+ return o - 1;
69
+ let last = s;
70
+ for (const { index } of segmenter.segment(v.slice(s, o)))
71
+ last = s + index;
72
+ return last;
73
+ };
74
+ const nextGrapheme = (v, o) => {
75
+ if (o >= v.length)
76
+ return v.length;
77
+ const e = lineEnd(v, o);
78
+ if (e === o)
79
+ return o + 1;
80
+ const first = segmenter.segment(v.slice(o, e))[Symbol.iterator]().next().value;
81
+ return o + (first ? first.segment.length : 1);
82
+ };
83
+ const firstNonBlank = (v, o) => {
84
+ let i = lineStart(v, o);
85
+ const e = lineEnd(v, i);
86
+ while (i < e && isSpace(v[i]))
87
+ i++;
88
+ return i;
89
+ };
90
+ /* character classes of word motions: 0 = blank, 1 = punctuation, 2 = keyword */
91
+ const cls = (c, big = false) => c === undefined || /\s/.test(c) ? 0 : big ? 1 : isIdent(c) ? 2 : 1;
92
+ const emptyAt = (v, i) => (i === v.length || v[i] === "\n") && (i === 0 || v[i - 1] === "\n");
93
+ /* word motions "w", "e", "b", and "ge" */
94
+ const wordFwd = (v, o, big) => {
95
+ let i = o;
96
+ const c = cls(v[i], big);
97
+ if (c !== 0)
98
+ while (i < v.length && cls(v[i], big) === c)
99
+ i++;
100
+ while (i < v.length && cls(v[i], big) === 0) {
101
+ if (i > o && emptyAt(v, i))
102
+ break;
103
+ i++;
104
+ }
105
+ return i;
106
+ };
107
+ const wordEnd = (v, o, big) => {
108
+ let i = o + 1;
109
+ while (i < v.length && cls(v[i], big) === 0)
110
+ i++;
111
+ if (i >= v.length)
112
+ return Math.max(0, v.length - 1);
113
+ const c = cls(v[i], big);
114
+ while (i + 1 < v.length && cls(v[i + 1], big) === c)
115
+ i++;
116
+ return i;
117
+ };
118
+ const wordBack = (v, o, big) => {
119
+ let i = o - 1;
120
+ while (i > 0 && cls(v[i], big) === 0 && !emptyAt(v, i))
121
+ i--;
122
+ if (i <= 0 || emptyAt(v, i))
123
+ return Math.max(0, i);
124
+ const c = cls(v[i], big);
125
+ while (i > 0 && cls(v[i - 1], big) === c)
126
+ i--;
127
+ return i;
128
+ };
129
+ const wordEndBack = (v, o, big) => {
130
+ let i = o;
131
+ const c = cls(v[i], big);
132
+ if (c !== 0)
133
+ while (i >= 0 && cls(v[i], big) === c)
134
+ i--;
135
+ while (i >= 0 && cls(v[i], big) === 0) {
136
+ if (i < o && emptyAt(v, i))
137
+ return i;
138
+ i--;
139
+ }
140
+ return Math.max(0, i);
141
+ };
142
+ /* the bracket matching of "%" */
143
+ const matchPair = (v, i) => {
144
+ const [open, close] = PAIRS[v[i]];
145
+ const fwd = v[i] === open;
146
+ let depth = 0;
147
+ for (let j = i; fwd ? j < v.length : j >= 0; j += fwd ? 1 : -1) {
148
+ if (v[j] === v[i])
149
+ depth++;
150
+ else if (v[j] === (fwd ? close : open) && --depth === 0)
151
+ return j;
152
+ }
153
+ return -1;
154
+ };
155
+ /* case conversion of "~" and "g~" */
156
+ const swapCase = (s) => s.replace(/\p{L}/gu, (c) => c === c.toUpperCase() ? c.toLowerCase() : c.toUpperCase());
157
+ /* conversion of a Vim "magic" pattern into a JavaScript regular expression */
158
+ export const toRegExp = (pattern, icase = false) => {
159
+ let flags = icase ? "gmi" : "gm";
160
+ let src = "";
161
+ let brace = false;
162
+ for (let i = 0; i < pattern.length; i++) {
163
+ const c = pattern[i];
164
+ if (c === "\\" && i + 1 < pattern.length) {
165
+ const d = pattern[++i];
166
+ if (d === "<" || d === ">") {
167
+ /* Unicode-aware word boundaries, consistent with "isIdent" */
168
+ const w = "[\\p{L}\\p{N}_]";
169
+ src += d === "<" ? `(?<!${w})(?=${w})` : `(?<=${w})(?!${w})`;
170
+ flags = flags.includes("u") ? flags : flags + "u";
171
+ }
172
+ else if (d === "=")
173
+ src += "?";
174
+ else if ("(|)+?{}".includes(d)) {
175
+ src += d;
176
+ brace = d === "{";
177
+ }
178
+ else if (d === "c")
179
+ flags = flags.includes("i") ? flags : flags + "i";
180
+ else if (d === "C")
181
+ flags = flags.replace("i", "");
182
+ else
183
+ src += "\\" + d;
184
+ }
185
+ else if (c === "}" && brace) {
186
+ src += c;
187
+ brace = false;
188
+ }
189
+ else if ("(|)+?{}".includes(c))
190
+ src += "\\" + c;
191
+ else
192
+ src += c;
193
+ }
194
+ try {
195
+ return new RegExp(src, flags);
196
+ }
197
+ catch {
198
+ return null;
199
+ }
200
+ };
201
+ /* escaping of a literal text for a Vim pattern */
202
+ const escapeVim = (s) => s.replace(/[\\/.*$^~[\]]/g, (c) => "\\" + c);
203
+ /* expansion of a ":s" replacement (with "&", "\0"-"\9", "\n", and "\t") */
204
+ const expandRep = (rep, args) => {
205
+ const idx = args.findIndex((a, i) => i > 0 && typeof a === "number");
206
+ const groups = (idx > 0 ? args.slice(0, idx) : [args[0]]);
207
+ let out = "";
208
+ for (let i = 0; i < rep.length; i++) {
209
+ const c = rep[i];
210
+ if (c === "\\" && i + 1 < rep.length) {
211
+ const d = rep[++i];
212
+ if (/[0-9]/.test(d))
213
+ out += groups[parseInt(d, 10)] ?? "";
214
+ else if (d === "n" || d === "r")
215
+ out += "\n";
216
+ else if (d === "t")
217
+ out += "\t";
218
+ else
219
+ out += d;
220
+ }
221
+ else if (c === "&")
222
+ out += groups[0] ?? "";
223
+ else
224
+ out += c;
225
+ }
226
+ return out;
227
+ };
228
+ /* splitting of a ":s" body at its unescaped delimiters */
229
+ const splitDelim = (body, delim) => {
230
+ const parts = [""];
231
+ for (let i = 0; i < body.length; i++) {
232
+ if (body[i] === "\\" && body[i + 1] === delim)
233
+ parts[parts.length - 1] += body[++i];
234
+ else if (body[i] === "\\" && i + 1 < body.length)
235
+ parts[parts.length - 1] += body[i] + body[++i];
236
+ else if (body[i] === delim)
237
+ parts.push("");
238
+ else
239
+ parts[parts.length - 1] += body[i];
240
+ }
241
+ return parts;
242
+ };
243
+ /* the start of the word before an offset, past any blanks in between (insert mode "<C-w>") */
244
+ const wordStartBack = (v, o) => {
245
+ let i = o;
246
+ while (i > 0 && cls(v[i - 1]) === 0)
247
+ i--;
248
+ const c = cls(v[i - 1]);
249
+ while (i > 0 && c !== 0 && cls(v[i - 1]) === c)
250
+ i--;
251
+ return i;
252
+ };
253
+ /* whether a token is a printable text (a character or a bracketed paste) */
254
+ const isText = (t) => [...t].length === 1 || t.startsWith("\u0000");
255
+ /* the default text operations, for a front end without its own */
256
+ export const defaultOps = {
257
+ previous: prevGrapheme,
258
+ next: nextGrapheme,
259
+ wordStart: wordStartBack,
260
+ vertical: (v, o, direction) => {
261
+ const [l, c] = toCursor(v, o);
262
+ const t = l + direction;
263
+ return t < 0 ? 0 : t > lastLine(v) ? v.length : toOffset(v, [t, c]);
264
+ }
265
+ };
266
+ /* the Vim editing engine, operating on a plain string value and a cursor offset */
267
+ export class Vim {
268
+ constructor(value, message = "", ops = defaultOps) {
269
+ /* bindings to the outside */
270
+ this.emit = () => { };
271
+ this.host = () => undefined;
272
+ this.clip = () => { };
273
+ this.height = 24;
274
+ /* editing state */
275
+ this.mode = "normal";
276
+ this.off = 0;
277
+ this.want = 0;
278
+ this.anchor = 0;
279
+ this.pend = [];
280
+ this.message = "";
281
+ this.error = false;
282
+ this.cmdKind = ":";
283
+ this.cmdText = "";
284
+ this.cmdFrom = "normal";
285
+ this.cmdHist = [];
286
+ this.cmdIdx = -1;
287
+ this.search = null;
288
+ this.hlsearch = true;
289
+ this.ignorecase = false;
290
+ this.smartcase = false;
291
+ this.recording = "";
292
+ this.cur = [0, 0];
293
+ this.regs = new Map();
294
+ this.marks = new Map();
295
+ this.macros = new Map();
296
+ this.macro = [];
297
+ this.lastMacro = "";
298
+ this.lastEx = "";
299
+ this.lastFind = null;
300
+ this.lastSub = null;
301
+ this.lastVisual = null;
302
+ this.lastInsert = 0;
303
+ this.undos = [];
304
+ this.redos = [];
305
+ this.redoSave = [];
306
+ this.change = [];
307
+ this.recChange = false;
308
+ this.lastChange = [];
309
+ this.insCount = 1;
310
+ this.insOpen = false;
311
+ this.insTokens = [];
312
+ this.replaced = [];
313
+ this.depth = 0;
314
+ this.failed = false;
315
+ this.value = value;
316
+ this.seen = value;
317
+ this.message = message;
318
+ this.ops = ops;
319
+ }
320
+ /* the offset of the last character of a line, and an offset clamped onto a character */
321
+ lastChar(v, o) {
322
+ const s = lineStart(v, o);
323
+ const e = lineEnd(v, o);
324
+ return e > s ? this.ops.previous(v, e) : s;
325
+ }
326
+ clampLine(v, o) {
327
+ return Math.max(lineStart(v, o), Math.min(o, this.lastChar(v, o)));
328
+ }
329
+ /* ==== EXTERNAL INTERFACE ==== */
330
+ /* take over an externally changed value */
331
+ sync(value) {
332
+ if (value === this.seen)
333
+ return;
334
+ this.seen = value;
335
+ if (value === this.value)
336
+ return;
337
+ this.value = value;
338
+ this.off = this.clampLine(value, Math.min(this.off, value.length));
339
+ this.pend = [];
340
+ }
341
+ /* handle the key tokens of a key press (like [ "x" ] or [ "<C-r>" ]); with "delegate",
342
+ plain insert mode keys are left to the front end, signaled by returning false */
343
+ keys(tokens, delegate = false) {
344
+ if (this.recording)
345
+ this.macro.push(...tokens);
346
+ if (tokens.length === 1)
347
+ return this.feed(tokens[0], delegate);
348
+ for (const t of tokens)
349
+ this.feed(t, false);
350
+ return true;
351
+ }
352
+ /* handle a bracketed paste */
353
+ paste(text) {
354
+ const t = "\u0000" + text;
355
+ if (this.recording)
356
+ this.macro.push(t);
357
+ this.feed(t, false);
358
+ }
359
+ /* take over a text change of the front end (typing in insert mode) */
360
+ onText(value) {
361
+ this.value = value;
362
+ this.off = toOffset(value, this.cur);
363
+ this.emit(value);
364
+ }
365
+ /* take over a cursor change of the front end (typing or mouse click) */
366
+ onCursor(cursor) {
367
+ this.cur = cursor;
368
+ this.off = toOffset(this.value, cursor);
369
+ if (this.mode === "normal" || this.mode === "visual" || this.mode === "vline") {
370
+ this.off = this.clampLine(this.value, this.off);
371
+ this.want = this.off - lineStart(this.value, this.off);
372
+ }
373
+ }
374
+ /* take over a mouse selection as a visual selection */
375
+ onSelect(sel) {
376
+ if (!sel || sel[0] === sel[1] || !(this.mode === "normal" || this.mode === "visual"))
377
+ return false;
378
+ this.mode = "visual";
379
+ this.anchor = sel[0];
380
+ this.off = this.clampLine(this.value, sel[1] > sel[0] ? this.ops.previous(this.value, sel[1]) : sel[1]);
381
+ return true;
382
+ }
383
+ /* the visual selection to be drawn */
384
+ selection() {
385
+ if (this.mode !== "visual" && this.mode !== "vline")
386
+ return null;
387
+ const r = this.selRange();
388
+ return [r.start, r.end];
389
+ }
390
+ /* whether a pattern has to be matched ignoring case */
391
+ icase(pattern) {
392
+ return this.ignorecase && !(this.smartcase && /[A-Z]/.test(pattern));
393
+ }
394
+ /* ==== KEY DISPATCHING ==== */
395
+ /* dispatch a key token by the mode (false for a key left to the front end) */
396
+ feed(t, live = false) {
397
+ if (this.mode === "insert" || this.mode === "replace")
398
+ return this.feedInsert(t, live);
399
+ if (this.mode === "cmdline")
400
+ this.feedCmdline(t);
401
+ else
402
+ this.feedNormal(t);
403
+ return true;
404
+ }
405
+ /* handle a key token in insert and replace mode */
406
+ feedInsert(t, live) {
407
+ if (this.recChange)
408
+ this.change.push(t);
409
+ this.insTokens.push(t);
410
+ /* a pending "<C-r>" inserts a register (recorded as its text), a pending "<C-o>" is refused */
411
+ if (this.pend.length > 0) {
412
+ const p = this.pend[0];
413
+ this.pend = [];
414
+ this.insTokens.splice(-2);
415
+ if (this.recChange)
416
+ this.change.splice(-2);
417
+ const reg = p === "<C-r>" ? this.getReg(t) : undefined;
418
+ if (p === "<C-o>")
419
+ this.fail("<C-o> is not supported");
420
+ else if (reg) {
421
+ const tok = "\u0000" + reg.text;
422
+ this.insTokens.push(tok);
423
+ if (this.recChange)
424
+ this.change.push(tok);
425
+ this.insertKey(tok);
426
+ }
427
+ return true;
428
+ }
429
+ if (t === "<Esc>" || t === "<C-c>" || t === "<C-[>") {
430
+ this.leaveInsert();
431
+ return true;
432
+ }
433
+ if (t === "<C-o>" || t === "<C-r>") {
434
+ this.pend = [t];
435
+ return true;
436
+ }
437
+ if (t === "<C-z>" || t === "<C-y>")
438
+ return true;
439
+ /* leave plain typing to the front end, unless replaying */
440
+ if (live && this.mode === "insert" && (t.length === 1 || PASSABLE.has(t)))
441
+ return false;
442
+ this.insertKey(t);
443
+ return true;
444
+ }
445
+ /* handle a key token on the command line */
446
+ feedCmdline(t) {
447
+ const text = this.cmdText;
448
+ switch (t) {
449
+ case "<Esc>":
450
+ case "<C-c>":
451
+ this.mode = this.cmdFrom;
452
+ break;
453
+ case "<CR>":
454
+ case "<C-j>":
455
+ case "<C-m>":
456
+ this.mode = this.cmdFrom;
457
+ if (text !== "" && this.cmdHist[this.cmdHist.length - 1] !== text)
458
+ this.cmdHist.push(text);
459
+ if (this.cmdKind === ":") {
460
+ const [v, o] = [this.value, this.off];
461
+ this.ex(text);
462
+ if (this.off !== o || this.value !== v)
463
+ this.want = this.off - lineStart(this.value, this.off);
464
+ }
465
+ else
466
+ this.searchCmd(text);
467
+ break;
468
+ case "<BS>":
469
+ case "<C-h>":
470
+ if (text === "")
471
+ this.mode = this.cmdFrom;
472
+ else
473
+ this.cmdText = text.slice(0, this.ops.previous(text, text.length));
474
+ break;
475
+ case "<C-u>":
476
+ this.cmdText = "";
477
+ break;
478
+ case "<C-w>":
479
+ this.cmdText = text.replace(/([\p{L}\p{N}_]+|[^\p{L}\p{N}_\s]+)\s*$/u, "");
480
+ break;
481
+ case "<Up>":
482
+ case "<Down>": {
483
+ const n = this.cmdHist.length;
484
+ if (n === 0)
485
+ break;
486
+ const i = this.cmdIdx < 0 ? n : this.cmdIdx;
487
+ this.cmdIdx = Math.max(0, Math.min(n, i + (t === "<Up>" ? -1 : 1)));
488
+ this.cmdText = this.cmdHist[this.cmdIdx] ?? "";
489
+ break;
490
+ }
491
+ default:
492
+ if (t.startsWith("\u0000"))
493
+ this.cmdText += t.slice(1).split("\n")[0];
494
+ else if (t === "<Tab>")
495
+ this.cmdText += "\t";
496
+ else if (isText(t))
497
+ this.cmdText += t;
498
+ }
499
+ }
500
+ /* collect the key tokens of a normal or visual mode command and execute it once complete */
501
+ feedNormal(t) {
502
+ /* a bracketed paste is inserted before the cursor at once */
503
+ if (t.startsWith("\u0000")) {
504
+ if (this.mode !== "normal")
505
+ this.leaveVisual();
506
+ this.pend = [];
507
+ this.begin();
508
+ this.insertText(t.slice(1));
509
+ this.off = this.clampLine(this.value, this.ops.previous(this.value, this.off));
510
+ this.end();
511
+ return;
512
+ }
513
+ if (t === "<Esc>" && this.pend.length > 0) {
514
+ this.pend = [];
515
+ return;
516
+ }
517
+ if (t === "<Esc>" && this.mode === "normal")
518
+ return;
519
+ this.pend.push(t);
520
+ const c = this.parse(this.pend);
521
+ if (c === "more")
522
+ return;
523
+ this.pend = [];
524
+ if (c === "bad")
525
+ return;
526
+ const v = this.value;
527
+ const o = this.off;
528
+ this.exec(c);
529
+ /* a moving non-motion command sets the wanted column (motions do it themselves) */
530
+ if ((this.off !== o || this.value !== v) && !MOTIONS.has(c.op)
531
+ && !(c.op === "@" && c.arg !== ":") && c.op !== "<C-e>" && c.op !== "<C-y>"
532
+ && (this.mode === "normal" || this.mode === "visual" || this.mode === "vline"))
533
+ this.want = this.off - lineStart(this.value, this.off);
534
+ }
535
+ /* parse "[\"x][count]cmd[arg]" resp. "[\"x][count]op[count]motion[arg]" */
536
+ parse(t) {
537
+ const visual = this.mode === "visual" || this.mode === "vline";
538
+ const digits = (i) => {
539
+ let s = "";
540
+ while (i < t.length && /^[0-9]$/.test(t[i]) && (t[i] !== "0" || s !== ""))
541
+ s += t[i++];
542
+ return [s, i];
543
+ };
544
+ /* a count may stand before and after the register (and both multiply) */
545
+ const [c0, i0] = digits(0);
546
+ let i = i0;
547
+ let reg = "";
548
+ if (t[i] === "\"") {
549
+ if (i + 1 >= t.length)
550
+ return "more";
551
+ reg = t[i + 1];
552
+ i += 2;
553
+ }
554
+ const [c1, i1] = digits(i);
555
+ i = i1;
556
+ if (i >= t.length)
557
+ return "more";
558
+ let k = t[i++];
559
+ if (PREFIXES.has(k) || (visual && (k === "i" || k === "a"))) {
560
+ if (i >= t.length)
561
+ return "more";
562
+ k += t[i++];
563
+ }
564
+ let arg = "";
565
+ if (ARGS.has(k) && !(k === "q" && this.recording !== "")) {
566
+ if (i >= t.length)
567
+ return "more";
568
+ arg = t[i++];
569
+ }
570
+ const cmd = {
571
+ reg, count: c0 || c1 ? Math.max(1, +c0) * Math.max(1, +c1) : 0, count2: 0,
572
+ op: k, arg, motion: "", marg: "", tokens: t.slice()
573
+ };
574
+ if (visual)
575
+ return MOTIONS.has(k) || OBJECT.test(k) || VISUAL.has(k) || k === "gv" ? cmd : "bad";
576
+ if (OPERATORS.has(k)) {
577
+ const [c2, i2] = digits(i);
578
+ i = i2;
579
+ if (i >= t.length)
580
+ return "more";
581
+ let m = t[i++];
582
+ if (m === "g" || m === "i" || m === "a") {
583
+ if (i >= t.length)
584
+ return "more";
585
+ m += t[i++];
586
+ }
587
+ if (m === k || m === k.slice(-1))
588
+ m = "line";
589
+ else if (!MOTIONS.has(m) && !OBJECT.test(m))
590
+ return "bad";
591
+ else if (ARGS.has(m)) {
592
+ if (i >= t.length)
593
+ return "more";
594
+ cmd.marg = t[i];
595
+ }
596
+ cmd.motion = m;
597
+ cmd.count2 = c2 ? parseInt(c2, 10) : 0;
598
+ return cmd;
599
+ }
600
+ return MOTIONS.has(k) || NORMAL.has(k) ? cmd : "bad";
601
+ }
602
+ /* ==== COMMAND EXECUTION ==== */
603
+ /* execute a parsed normal mode command */
604
+ exec(c) {
605
+ const n = Math.max(1, c.count) * Math.max(1, c.count2);
606
+ const given = c.count > 0 || c.count2 > 0;
607
+ if (this.mode === "visual" || this.mode === "vline") {
608
+ this.execVisual(c, n, given);
609
+ return;
610
+ }
611
+ const v = this.value;
612
+ const o = this.off;
613
+ /* a change is recorded for "." until it is finished */
614
+ const chg = (fn) => {
615
+ this.change = c.tokens.slice();
616
+ this.recChange = true;
617
+ fn();
618
+ if (this.mode !== "insert" && this.mode !== "replace") {
619
+ this.lastChange = this.change;
620
+ this.recChange = false;
621
+ }
622
+ };
623
+ if (OPERATORS.has(c.op)) {
624
+ if (c.op === "y")
625
+ this.operate(c.op, c.motion, c.marg, n, given, c.reg);
626
+ else
627
+ chg(() => this.operate(c.op, c.motion, c.marg, n, given, c.reg));
628
+ return;
629
+ }
630
+ switch (c.op) {
631
+ case "x":
632
+ case "<Del>":
633
+ chg(() => this.operate("d", "l", "", n, given, c.reg));
634
+ return;
635
+ case "X":
636
+ chg(() => this.operate("d", "h", "", n, given, c.reg));
637
+ return;
638
+ case "D":
639
+ chg(() => this.operate("d", "$", "", n, given, c.reg));
640
+ return;
641
+ case "C":
642
+ chg(() => this.operate("c", "$", "", n, given, c.reg));
643
+ return;
644
+ case "s":
645
+ chg(() => this.operate("c", "l", "", n, given, c.reg));
646
+ return;
647
+ case "S":
648
+ chg(() => this.operate("c", "line", "", n, given, c.reg));
649
+ return;
650
+ case "Y":
651
+ this.operate("y", "line", "", n, given, c.reg);
652
+ return;
653
+ case "p":
654
+ case "P":
655
+ chg(() => this.put(c.reg, n, c.op === "P"));
656
+ return;
657
+ case "r":
658
+ chg(() => this.replaceChars(c.arg, n));
659
+ return;
660
+ case "~":
661
+ chg(() => this.toggleCase(n));
662
+ return;
663
+ case "<C-a>":
664
+ chg(() => this.increment(n));
665
+ return;
666
+ case "<C-x>":
667
+ chg(() => this.increment(-n));
668
+ return;
669
+ case "&":
670
+ chg(() => {
671
+ if (this.lastSub)
672
+ this.substitute(lineNo(v, o), lineNo(v, o), "\u0001", `${this.lastSub.pat}\u0001${this.lastSub.rep}\u0001`);
673
+ });
674
+ return;
675
+ case "J":
676
+ case "gJ":
677
+ chg(() => {
678
+ this.begin();
679
+ this.join(lineNo(v, o), Math.max(2, n), c.op === "J");
680
+ this.end();
681
+ });
682
+ return;
683
+ case "i":
684
+ case "a":
685
+ case "I":
686
+ case "A":
687
+ case "gI":
688
+ case "gi":
689
+ case "o":
690
+ case "O":
691
+ chg(() => {
692
+ if (c.op === "a")
693
+ this.off = o < lineEnd(v, o) ? this.ops.next(v, o) : o;
694
+ else if (c.op === "I")
695
+ this.off = firstNonBlank(v, o);
696
+ else if (c.op === "gI")
697
+ this.off = lineStart(v, o);
698
+ else if (c.op === "A")
699
+ this.off = lineEnd(v, o);
700
+ else if (c.op === "gi")
701
+ this.off = Math.min(this.lastInsert, v.length);
702
+ this.begin();
703
+ if (c.op === "o") {
704
+ const e = lineEnd(v, o);
705
+ this.replace(e, e, "\n");
706
+ this.off = e + 1;
707
+ }
708
+ else if (c.op === "O") {
709
+ const s = lineStart(v, o);
710
+ this.replace(s, s, "\n");
711
+ this.off = s;
712
+ }
713
+ this.enterInsert(n, c.op === "o" || c.op === "O");
714
+ });
715
+ return;
716
+ case "R":
717
+ chg(() => {
718
+ this.begin();
719
+ this.enterInsert(n, false);
720
+ this.mode = "replace";
721
+ });
722
+ return;
723
+ case "u":
724
+ this.undo(n);
725
+ return;
726
+ case "<C-r>":
727
+ this.redo(n);
728
+ return;
729
+ case ".":
730
+ this.dot(c);
731
+ return;
732
+ case "v":
733
+ case "V":
734
+ this.mode = c.op === "v" ? "visual" : "vline";
735
+ this.anchor = o;
736
+ this.message = "";
737
+ return;
738
+ case "gv":
739
+ if (this.lastVisual) {
740
+ this.mode = this.lastVisual.mode;
741
+ this.anchor = Math.min(this.lastVisual.anchor, v.length);
742
+ this.off = this.clampLine(v, Math.min(this.lastVisual.off, v.length));
743
+ }
744
+ return;
745
+ case "<C-v>":
746
+ this.fail("visual block mode is not supported");
747
+ return;
748
+ case ":":
749
+ this.openCmd(":", given ? (n > 1 ? `.,.+${n - 1}` : ".") : "");
750
+ return;
751
+ case "/":
752
+ case "?":
753
+ this.openCmd(c.op, "");
754
+ return;
755
+ case "m":
756
+ if (/^[a-zA-Z]$/.test(c.arg))
757
+ this.marks.set(c.arg, o);
758
+ return;
759
+ case "q":
760
+ this.macroRecord(c.arg);
761
+ return;
762
+ case "@":
763
+ this.macroPlay(c.arg, n);
764
+ return;
765
+ case "ZZ":
766
+ this.runHost("x");
767
+ return;
768
+ case "ZQ":
769
+ this.runHost("q!");
770
+ return;
771
+ case "<C-g>":
772
+ this.runHost("file");
773
+ return;
774
+ case "<C-c>":
775
+ this.say("Type :qa! and press <Enter> to abandon all changes and exit Vim");
776
+ return;
777
+ case "<C-d>":
778
+ case "<C-u>":
779
+ case "<C-f>":
780
+ case "<C-b>":
781
+ case "<PageDown>":
782
+ case "<PageUp>":
783
+ case "<C-e>":
784
+ case "<C-y>":
785
+ this.scroll(c.op, n, given);
786
+ return;
787
+ case "zz":
788
+ case "zt":
789
+ case "zb":
790
+ case "z.":
791
+ case "z<CR>":
792
+ case "z-":
793
+ case "<C-l>":
794
+ return;
795
+ }
796
+ const m = this.motion(c.op, c.arg, n, given, false);
797
+ if (m)
798
+ this.go(m, JUMPS.has(c.op));
799
+ else
800
+ this.failed = true;
801
+ }
802
+ /* execute a parsed visual mode command */
803
+ execVisual(c, n, given) {
804
+ const k = c.op;
805
+ const v = this.value;
806
+ if (MOTIONS.has(k)) {
807
+ const m = this.motion(k, c.arg, n, given, false);
808
+ if (m)
809
+ this.go(m, JUMPS.has(k));
810
+ else
811
+ this.failed = true;
812
+ return;
813
+ }
814
+ if (OBJECT.test(k)) {
815
+ const r = this.object(k, n);
816
+ if (r) {
817
+ this.anchor = r.start;
818
+ this.off = r.end > r.start ? this.ops.previous(v, r.end) : r.start;
819
+ if (r.linewise)
820
+ this.mode = "vline";
821
+ }
822
+ return;
823
+ }
824
+ switch (k) {
825
+ case "<Esc>":
826
+ case "<C-c>":
827
+ this.leaveVisual();
828
+ return;
829
+ case "v":
830
+ case "V": {
831
+ const mode = k === "v" ? "visual" : "vline";
832
+ if (this.mode === mode)
833
+ this.leaveVisual();
834
+ else
835
+ this.mode = mode;
836
+ return;
837
+ }
838
+ case "<C-v>":
839
+ this.fail("visual block mode is not supported");
840
+ return;
841
+ case "o":
842
+ case "O":
843
+ [this.anchor, this.off] = [this.off, this.anchor];
844
+ return;
845
+ case "gv":
846
+ return;
847
+ case ":":
848
+ this.leaveVisual();
849
+ this.openCmd(":", "'<,'>");
850
+ return;
851
+ case "/":
852
+ case "?":
853
+ this.openCmd(k, "");
854
+ return;
855
+ }
856
+ /* operators act on the selection at once */
857
+ const r = this.selRange();
858
+ const lines = { start: lineStart(v, r.start), end: lineEndNl(v, Math.max(r.start, r.end - 1)), linewise: true };
859
+ const vline = this.mode === "vline";
860
+ this.leaveVisual();
861
+ /* a change is recorded for "." with a selection of the same extent from the cursor */
862
+ this.change = [...this.selKeys(r, vline), ...c.tokens];
863
+ this.recChange = k !== "y" && k !== "Y";
864
+ switch (k) {
865
+ case "d":
866
+ case "x":
867
+ case "<Del>":
868
+ this.apply("d", r, c.reg);
869
+ break;
870
+ case "X":
871
+ case "D":
872
+ this.apply("d", lines, c.reg);
873
+ break;
874
+ case "y":
875
+ this.apply("y", r, c.reg);
876
+ break;
877
+ case "Y":
878
+ this.apply("y", lines, c.reg);
879
+ break;
880
+ case "c":
881
+ case "s":
882
+ this.apply("c", r, c.reg);
883
+ break;
884
+ case "C":
885
+ case "S":
886
+ case "R":
887
+ this.apply("c", lines, c.reg);
888
+ break;
889
+ case ">":
890
+ case "<":
891
+ this.apply(k, lines, c.reg, n);
892
+ break;
893
+ case "~":
894
+ this.apply("g~", r, c.reg);
895
+ break;
896
+ case "u":
897
+ this.apply("gu", r, c.reg);
898
+ break;
899
+ case "U":
900
+ this.apply("gU", r, c.reg);
901
+ break;
902
+ case "J":
903
+ case "gJ": {
904
+ const l1 = lineNo(v, r.start), l2 = lineNo(v, Math.max(r.start, r.end - 1));
905
+ this.begin();
906
+ this.join(l1, Math.max(2, l2 - l1 + 1), k === "J");
907
+ this.end();
908
+ break;
909
+ }
910
+ case "r": {
911
+ const ch = c.arg === "<Tab>" ? "\t" : c.arg;
912
+ if (!isText(ch) || ch.startsWith("\u0000"))
913
+ break;
914
+ this.begin();
915
+ let out = "";
916
+ for (let i = r.start; i < r.end; i = this.ops.next(v, i))
917
+ out += v[i] === "\n" ? "\n" : ch;
918
+ this.replace(r.start, r.end, out);
919
+ this.off = this.clampLine(this.value, r.start);
920
+ this.end();
921
+ break;
922
+ }
923
+ case "p":
924
+ case "P": {
925
+ const reg = this.getReg(c.reg);
926
+ if (!reg) {
927
+ this.fail(`E353: Nothing in register ${c.reg || "\""}`);
928
+ break;
929
+ }
930
+ this.begin();
931
+ /* a linewise selection up to the text end lacks its final newline */
932
+ const old = v.slice(r.start, r.end);
933
+ const tail = r.linewise && !old.endsWith("\n");
934
+ this.setReg("", tail ? old + "\n" : old, r.linewise, "delete");
935
+ let text = r.linewise
936
+ ? (reg.linewise ? reg.text : reg.text + "\n")
937
+ : (reg.linewise ? "\n" + reg.text : reg.text);
938
+ if (tail)
939
+ text = text.slice(0, -1);
940
+ this.replace(r.start, r.end, text);
941
+ this.off = this.clampLine(this.value, r.start + (r.linewise || !reg.linewise ? 0 : 1));
942
+ this.end();
943
+ break;
944
+ }
945
+ case "I":
946
+ this.begin();
947
+ this.off = vline ? firstNonBlank(v, r.start) : r.start;
948
+ this.enterInsert(1, false);
949
+ break;
950
+ case "A":
951
+ this.begin();
952
+ this.off = vline ? lineEnd(v, Math.max(r.start, r.end - 1)) : Math.min(r.end, lineEnd(v, Math.max(r.start, r.end - 1)));
953
+ this.enterInsert(1, false);
954
+ break;
955
+ }
956
+ if (this.recChange && this.mode !== "insert") {
957
+ this.lastChange = this.change;
958
+ this.recChange = false;
959
+ }
960
+ }
961
+ /* the keys re-creating a visual selection of the same extent from the cursor (for ".") */
962
+ selKeys(r, vline) {
963
+ const v = this.value;
964
+ const e = Math.max(r.start, r.end - 1);
965
+ const dl = lineNo(v, e) - lineNo(v, r.start);
966
+ const keys = [vline ? "V" : "v"];
967
+ if (dl > 0)
968
+ keys.push(...String(dl), "j");
969
+ if (vline)
970
+ return keys;
971
+ if (v[e] === "\n")
972
+ keys.push("$");
973
+ else {
974
+ let n = 0;
975
+ for (let i = dl > 0 ? lineStart(v, e) : r.start; i < e; i = this.ops.next(v, i))
976
+ n++;
977
+ if (dl > 0)
978
+ keys.push("0");
979
+ if (n > 0)
980
+ keys.push(...String(n), "l");
981
+ }
982
+ return keys;
983
+ }
984
+ /* ==== MOTIONS AND TEXT OBJECTS ==== */
985
+ /* the target of a motion from the cursor (with "op" for an operator-pending motion) */
986
+ motion(k, arg, n, given, op) {
987
+ const v = this.value;
988
+ const o = this.off;
989
+ const ls = lineStart(v, o);
990
+ const le = lineEnd(v, o);
991
+ const ex = (to) => ({ to, linewise: false, inclusive: false });
992
+ const inc = (to) => ({ to, linewise: false, inclusive: true });
993
+ const lines = (to) => ({ to, linewise: true, inclusive: false });
994
+ switch (k) {
995
+ case "h":
996
+ case "<Left>":
997
+ case "<BS>":
998
+ case "<C-h>": {
999
+ if (o <= ls)
1000
+ return null;
1001
+ let p = o;
1002
+ for (let i = 0; i < n && p > ls; i++)
1003
+ p = this.ops.previous(v, p);
1004
+ return ex(p);
1005
+ }
1006
+ case "l":
1007
+ case "<Right>":
1008
+ case " ": {
1009
+ let p = o;
1010
+ for (let i = 0; i < n && p < le; i++)
1011
+ p = this.ops.next(v, p);
1012
+ if (!op)
1013
+ p = Math.min(p, this.lastChar(v, o));
1014
+ return p === o ? null : ex(p);
1015
+ }
1016
+ case "j":
1017
+ case "<Down>":
1018
+ case "<C-n>":
1019
+ case "<C-j>":
1020
+ case "k":
1021
+ case "<Up>":
1022
+ case "<C-p>": {
1023
+ const down = k === "j" || k === "<Down>" || k === "<C-n>" || k === "<C-j>";
1024
+ const l = lineNo(v, o);
1025
+ const t = down ? Math.min(lastLine(v), l + n) : Math.max(0, l - n);
1026
+ if (t === l)
1027
+ return null;
1028
+ return { to: this.column(v, t, this.want), linewise: true, inclusive: false, vertical: true };
1029
+ }
1030
+ case "+":
1031
+ case "<CR>":
1032
+ case "-":
1033
+ case "_": {
1034
+ const t = lineNo(v, o) + (k === "_" ? n - 1 : k === "-" ? -n : n);
1035
+ if (t < 0 || t > lastLine(v))
1036
+ return null;
1037
+ return lines(firstNonBlank(v, lineAt(v, t)));
1038
+ }
1039
+ case "0":
1040
+ case "<Home>":
1041
+ return ex(ls);
1042
+ case "^":
1043
+ return ex(firstNonBlank(v, o));
1044
+ case "$":
1045
+ case "<End>":
1046
+ case "g_": {
1047
+ const s = lineAt(v, Math.min(lastLine(v), lineNo(v, o) + n - 1));
1048
+ let e = lineEnd(v, s);
1049
+ if (k === "g_") {
1050
+ while (e > s && isSpace(v[e - 1]))
1051
+ e--;
1052
+ return inc(e > s ? this.ops.previous(v, e) : s);
1053
+ }
1054
+ return { to: op ? e : (e > s ? this.ops.previous(v, e) : s), linewise: false, inclusive: false, want: Infinity };
1055
+ }
1056
+ case "|":
1057
+ return ex(Math.min(ls + n - 1, this.lastChar(v, o)));
1058
+ case "w":
1059
+ case "W":
1060
+ case "e":
1061
+ case "E":
1062
+ case "b":
1063
+ case "B":
1064
+ case "ge":
1065
+ case "gE":
1066
+ return this.wordMotion(k, n, op);
1067
+ case "G":
1068
+ case "gg": {
1069
+ const l = given ? Math.min(n - 1, lastLine(v)) : k === "G" ? lastLine(v) : 0;
1070
+ return lines(firstNonBlank(v, lineAt(v, l)));
1071
+ }
1072
+ case "f":
1073
+ case "F":
1074
+ case "t":
1075
+ case "T":
1076
+ case ";":
1077
+ case ",":
1078
+ return this.findMotion(k, arg, n);
1079
+ case "%": {
1080
+ let i = o;
1081
+ while (i < le && !"()[]{}".includes(v[i]))
1082
+ i++;
1083
+ if (i >= le)
1084
+ return null;
1085
+ const q = matchPair(v, i);
1086
+ return q < 0 ? null : inc(q);
1087
+ }
1088
+ case "}":
1089
+ case "{":
1090
+ return this.paragraphMotion(k === "}", n);
1091
+ case "n":
1092
+ case "N":
1093
+ case "*":
1094
+ case "#":
1095
+ return this.searchMotion(k, n);
1096
+ case "`":
1097
+ case "'": {
1098
+ const p = this.marks.get(arg === "`" ? "'" : arg);
1099
+ if (p === undefined) {
1100
+ this.fail("E20: Mark not set");
1101
+ return null;
1102
+ }
1103
+ const q = Math.min(p, v.length);
1104
+ return k === "`" ? ex(q) : lines(firstNonBlank(v, q));
1105
+ }
1106
+ }
1107
+ return null;
1108
+ }
1109
+ /* the word motions "w", "W", "e", "E", "b", "B", "ge", and "gE" */
1110
+ wordMotion(k, n, op) {
1111
+ const v = this.value;
1112
+ const o = this.off;
1113
+ const big = k === "W" || k === "E" || k === "B" || k === "gE";
1114
+ let p = o;
1115
+ if (k === "w" || k === "W") {
1116
+ let q = o;
1117
+ for (let i = 0; i < n && p < v.length; i++) {
1118
+ q = p;
1119
+ p = wordFwd(v, p, big);
1120
+ }
1121
+ if (p === o)
1122
+ return null;
1123
+ /* "dw" on the last word of a line stops at its end */
1124
+ if (op && lineNo(v, p) > lineNo(v, q) && !emptyAt(v, q))
1125
+ p = lineEnd(v, q);
1126
+ return { to: p, linewise: false, inclusive: false };
1127
+ }
1128
+ const step = k === "e" || k === "E" ? wordEnd : k === "b" || k === "B" ? wordBack : wordEndBack;
1129
+ for (let i = 0; i < n; i++) {
1130
+ const q = step(v, p, big);
1131
+ if (q === p)
1132
+ break;
1133
+ p = q;
1134
+ }
1135
+ return p === o ? null : { to: p, linewise: false, inclusive: k !== "b" && k !== "B" };
1136
+ }
1137
+ /* the character find motions "f", "F", "t", "T", ";", and "," */
1138
+ findMotion(k, arg, n) {
1139
+ const v = this.value;
1140
+ const o = this.off;
1141
+ let cmd = k;
1142
+ let ch = arg === "<Tab>" ? "\t" : arg;
1143
+ const repeat = k === ";" || k === ",";
1144
+ if (repeat) {
1145
+ if (!this.lastFind)
1146
+ return null;
1147
+ ch = this.lastFind.ch;
1148
+ cmd = this.lastFind.cmd;
1149
+ if (k === ",")
1150
+ cmd = cmd === cmd.toLowerCase() ? cmd.toUpperCase() : cmd.toLowerCase();
1151
+ }
1152
+ else if (isText(ch) && !ch.startsWith("\u0000"))
1153
+ this.lastFind = { cmd: k, ch };
1154
+ else
1155
+ return null;
1156
+ const fwd = cmd === "f" || cmd === "t";
1157
+ const till = cmd === "t" || cmd === "T";
1158
+ const ls = lineStart(v, o);
1159
+ const le = lineEnd(v, o);
1160
+ let p = o;
1161
+ for (let i = 0; i < n; i++) {
1162
+ const skip = i === 0 && repeat && till ? 2 : 1;
1163
+ const start = fwd ? p + skip : p - skip;
1164
+ if (start < 0)
1165
+ return null;
1166
+ const q = fwd ? v.indexOf(ch, start) : v.lastIndexOf(ch, start);
1167
+ if (q < 0 || (fwd ? q >= le : q < ls))
1168
+ return null;
1169
+ p = q;
1170
+ }
1171
+ if (till)
1172
+ p = fwd ? this.ops.previous(v, p) : p + ch.length;
1173
+ return { to: p, linewise: false, inclusive: fwd };
1174
+ }
1175
+ /* the paragraph motions "}" and "{" */
1176
+ paragraphMotion(fwd, n) {
1177
+ const v = this.value;
1178
+ const last = lastLine(v);
1179
+ let l = lineNo(v, this.off);
1180
+ for (let i = 0; i < n && (fwd ? l < last : l > 0); i++) {
1181
+ while (fwd ? l < last : l > 0) {
1182
+ if (!isEmpty(v, l))
1183
+ break;
1184
+ l += fwd ? 1 : -1;
1185
+ }
1186
+ while (fwd ? l < last : l > 0) {
1187
+ l += fwd ? 1 : -1;
1188
+ if (isEmpty(v, l))
1189
+ break;
1190
+ }
1191
+ }
1192
+ const to = isEmpty(v, l) ? lineAt(v, l) : fwd ? v.length : 0;
1193
+ return to === this.off ? null : { to, linewise: false, inclusive: false };
1194
+ }
1195
+ /* the search motions "n", "N", "*", and "#" */
1196
+ searchMotion(k, n) {
1197
+ let p = this.off;
1198
+ if (k === "*" || k === "#") {
1199
+ const [w, s] = this.wordUnder();
1200
+ if (!w) {
1201
+ this.fail("E348: No string under cursor");
1202
+ return null;
1203
+ }
1204
+ this.search = { pattern: `\\<${escapeVim(w)}\\>`, forward: k === "*" };
1205
+ this.hlsearch = true;
1206
+ p = s;
1207
+ }
1208
+ if (!this.search) {
1209
+ this.fail("E35: No previous regular expression");
1210
+ return null;
1211
+ }
1212
+ const fwd = k === "N" ? !this.search.forward : k === "n" ? this.search.forward : k === "*";
1213
+ this.say((fwd ? "/" : "?") + this.search.pattern);
1214
+ for (let i = 0; i < n; i++) {
1215
+ const q = this.find(this.search.pattern, p, fwd);
1216
+ if (q === null)
1217
+ return null;
1218
+ p = q;
1219
+ }
1220
+ return { to: p, linewise: false, inclusive: false };
1221
+ }
1222
+ /* the offset on a line closest to a wanted column */
1223
+ column(v, line, want) {
1224
+ const s = lineAt(v, line);
1225
+ const e = lineEnd(v, s);
1226
+ if (e === s)
1227
+ return s;
1228
+ const t = Math.min(s + want, this.ops.previous(v, e));
1229
+ return this.ops.next(v, this.ops.previous(v, t)) === t ? t : this.ops.previous(v, t);
1230
+ }
1231
+ /* move the cursor by a motion */
1232
+ go(m, jump) {
1233
+ if (jump)
1234
+ this.marks.set("'", this.off);
1235
+ this.off = this.clampLine(this.value, Math.min(m.to, this.value.length));
1236
+ if (m.want !== undefined)
1237
+ this.want = m.want;
1238
+ else if (!m.vertical)
1239
+ this.want = this.off - lineStart(this.value, this.off);
1240
+ }
1241
+ /* the keyword under or after the cursor and its start (for "*" and "#") */
1242
+ wordUnder() {
1243
+ const v = this.value;
1244
+ let s = this.off;
1245
+ const e = lineEnd(v, s);
1246
+ while (s < e && cls(v[s]) !== 2)
1247
+ s++;
1248
+ if (s >= e)
1249
+ return ["", s];
1250
+ while (s > 0 && cls(v[s - 1]) === 2)
1251
+ s--;
1252
+ let t = s;
1253
+ while (t < e && cls(v[t]) === 2)
1254
+ t++;
1255
+ return [v.slice(s, t), s];
1256
+ }
1257
+ /* the text objects "iw", "aw", "i\"", "a(", "ip", etc. */
1258
+ object(k, n) {
1259
+ const v = this.value;
1260
+ const o = this.off;
1261
+ const inner = k[0] === "i";
1262
+ const t = k[1];
1263
+ const ls = lineStart(v, o);
1264
+ const le = lineEnd(v, o);
1265
+ const outer = (s, e) => {
1266
+ let e2 = e;
1267
+ while (e2 < le && isSpace(v[e2]))
1268
+ e2++;
1269
+ if (e2 > e)
1270
+ e = e2;
1271
+ else
1272
+ while (s > ls && isSpace(v[s - 1]))
1273
+ s--;
1274
+ return { start: s, end: e, linewise: false };
1275
+ };
1276
+ if (t === "w" || t === "W") {
1277
+ if (le === ls)
1278
+ return null;
1279
+ const big = t === "W";
1280
+ const c = cls(v[o], big);
1281
+ let s = o, e = o;
1282
+ while (s > ls && cls(v[s - 1], big) === c)
1283
+ s--;
1284
+ while (e < le && cls(v[e], big) === c)
1285
+ e++;
1286
+ for (let i = 1; i < n && e < le; i++) {
1287
+ const c2 = cls(v[e], big);
1288
+ while (e < le && cls(v[e], big) === c2)
1289
+ e++;
1290
+ }
1291
+ if (inner)
1292
+ return { start: s, end: e, linewise: false };
1293
+ if (c === 0) {
1294
+ const c2 = cls(v[e], big);
1295
+ while (e < le && c2 !== 0 && cls(v[e], big) === c2)
1296
+ e++;
1297
+ return { start: s, end: e, linewise: false };
1298
+ }
1299
+ return outer(s, e);
1300
+ }
1301
+ if (t === "\"" || t === "'" || t === "`") {
1302
+ const qs = [];
1303
+ for (let i = ls; i < le; i++)
1304
+ if (v[i] === t && v[i - 1] !== "\\")
1305
+ qs.push(i);
1306
+ let pair = null;
1307
+ for (let i = 0; i + 1 < qs.length && !pair; i += 2)
1308
+ if (qs[i] <= o && o <= qs[i + 1])
1309
+ pair = [qs[i], qs[i + 1]];
1310
+ for (let i = 0; i + 1 < qs.length && !pair; i += 2)
1311
+ if (qs[i] > o)
1312
+ pair = [qs[i], qs[i + 1]];
1313
+ if (!pair)
1314
+ return null;
1315
+ return inner ? { start: pair[0] + 1, end: pair[1], linewise: false } : outer(pair[0], pair[1] + 1);
1316
+ }
1317
+ if (t === "p") {
1318
+ const last = lastLine(v);
1319
+ const empty = isEmpty(v, lineNo(v, o));
1320
+ let a = lineNo(v, o), b = a;
1321
+ while (a > 0 && isEmpty(v, a - 1) === empty)
1322
+ a--;
1323
+ while (b < last && isEmpty(v, b + 1) === empty)
1324
+ b++;
1325
+ if (!inner)
1326
+ while (b < last && isEmpty(v, b + 1) !== empty)
1327
+ b++;
1328
+ return { start: lineAt(v, a), end: lineEndNl(v, lineAt(v, b)), linewise: true };
1329
+ }
1330
+ const pair = PAIRS[t];
1331
+ return pair ? this.pairObject(pair, n, inner) : null;
1332
+ }
1333
+ /* the bracket text objects "i(", "a)", "iB", "a<", etc. */
1334
+ pairObject([open, close], n, inner) {
1335
+ const v = this.value;
1336
+ const o = this.off;
1337
+ let a = o;
1338
+ for (let i = 0; i < n; i++) {
1339
+ let depth = 0;
1340
+ let j = i === 0 ? a : a - 1;
1341
+ for (; j >= 0; j--) {
1342
+ if (v[j] === close && !(i === 0 && j === o))
1343
+ depth++;
1344
+ else if (v[j] === open) {
1345
+ if (depth === 0)
1346
+ break;
1347
+ depth--;
1348
+ }
1349
+ }
1350
+ if (j < 0)
1351
+ return null;
1352
+ a = j;
1353
+ }
1354
+ let b = -1;
1355
+ let depth = 0;
1356
+ for (let j = a; j < v.length && b < 0; j++) {
1357
+ if (v[j] === open)
1358
+ depth++;
1359
+ else if (v[j] === close && --depth === 0)
1360
+ b = j;
1361
+ }
1362
+ if (b < 0)
1363
+ return null;
1364
+ if (!inner)
1365
+ return { start: a, end: b + 1, linewise: false };
1366
+ let s = a + 1, e = b;
1367
+ if (v[s] === "\n")
1368
+ s++;
1369
+ const lb = lineStart(v, b);
1370
+ if (lb > s && v.slice(lb, b).trim() === "")
1371
+ e = lb;
1372
+ return { start: s, end: Math.max(s, e), linewise: false };
1373
+ }
1374
+ /* the range of a motion, with the exclusive/linewise rules of Vim */
1375
+ rangeOf(m) {
1376
+ const v = this.value;
1377
+ const s = Math.min(this.off, m.to);
1378
+ const e = Math.max(this.off, m.to);
1379
+ if (m.linewise)
1380
+ return { start: lineStart(v, s), end: lineEndNl(v, e), linewise: true };
1381
+ if (m.inclusive)
1382
+ return { start: s, end: Math.min(v.length, this.ops.next(v, e)), linewise: false };
1383
+ if (e > s && e === lineStart(v, e) && lineNo(v, e) > lineNo(v, s)) {
1384
+ if (s <= firstNonBlank(v, s))
1385
+ return { start: lineStart(v, s), end: e, linewise: true };
1386
+ return { start: s, end: e - 1, linewise: false };
1387
+ }
1388
+ return { start: s, end: e, linewise: false };
1389
+ }
1390
+ /* the range of "n" whole lines from the cursor */
1391
+ lineRange(n) {
1392
+ const v = this.value;
1393
+ const l = lineNo(v, this.off);
1394
+ const e = Math.min(lastLine(v), l + n - 1);
1395
+ return { start: lineAt(v, l), end: lineEndNl(v, lineAt(v, e)), linewise: true };
1396
+ }
1397
+ /* the current visual selection range */
1398
+ selRange() {
1399
+ const v = this.value;
1400
+ const a = Math.min(this.anchor, this.off);
1401
+ const b = Math.max(this.anchor, this.off);
1402
+ if (this.mode === "vline")
1403
+ return { start: lineStart(v, a), end: lineEndNl(v, b), linewise: true };
1404
+ /* after "$" the selection includes the line end (with its newline) */
1405
+ const end = b < v.length ? this.ops.next(v, b) : b;
1406
+ return { start: a, end: b === this.off && this.want === Infinity ? Math.max(end, lineEndNl(v, b)) : end, linewise: false };
1407
+ }
1408
+ /* leave visual mode, remembering the selection for "'<", "'>", and "gv" */
1409
+ leaveVisual() {
1410
+ const r = this.selRange();
1411
+ this.marks.set("<", r.start);
1412
+ this.marks.set(">", Math.max(r.start, r.end - 1));
1413
+ this.lastVisual = { mode: this.mode, anchor: this.anchor, off: this.off };
1414
+ this.mode = "normal";
1415
+ this.off = this.clampLine(this.value, this.off);
1416
+ }
1417
+ /* ==== OPERATORS ==== */
1418
+ /* apply an operator onto the range of a motion or text object */
1419
+ operate(op, key, marg, n, given, reg) {
1420
+ const v = this.value;
1421
+ const o = this.off;
1422
+ let r = null;
1423
+ if (key === "line")
1424
+ r = this.lineRange(n);
1425
+ else if (OBJECT.test(key))
1426
+ r = this.object(key, n);
1427
+ else if (op === "c" && (key === "w" || key === "W") && cls(v[o]) !== 0) {
1428
+ /* "cw" on a word acts like "ce", but stays on the current word */
1429
+ const big = key === "W";
1430
+ let p = o;
1431
+ while (p + 1 < v.length && cls(v[p + 1], big) === cls(v[p], big))
1432
+ p++;
1433
+ for (let i = 1; i < n; i++)
1434
+ p = wordEnd(v, p, big);
1435
+ r = { start: o, end: Math.min(v.length, this.ops.next(v, p)), linewise: false };
1436
+ }
1437
+ else {
1438
+ const m = this.motion(key, marg, n, given, true);
1439
+ if (m)
1440
+ r = this.rangeOf(m);
1441
+ }
1442
+ if (r)
1443
+ this.apply(op, r, reg);
1444
+ else if (op === "c" && key === "l" && lineEnd(v, o) === o) {
1445
+ /* "cl" resp. "s" on an empty line just starts inserting */
1446
+ this.begin();
1447
+ this.enterInsert(1, false);
1448
+ }
1449
+ }
1450
+ /* apply an operator onto a range (with "n" as the shift count) */
1451
+ apply(op, r, reg, n = 1) {
1452
+ const v = this.value;
1453
+ const text = v.slice(r.start, r.end);
1454
+ const regText = r.linewise && !text.endsWith("\n") ? text + "\n" : text;
1455
+ const nlines = r.linewise ? regText.split("\n").length - 1 : 0;
1456
+ if (op === "y") {
1457
+ this.setReg(reg, regText, r.linewise, "yank");
1458
+ if (nlines > 2)
1459
+ this.say(`${nlines} lines yanked`);
1460
+ if (!r.linewise || lineNo(v, r.start) !== lineNo(v, this.off))
1461
+ this.off = this.clampLine(v, r.start);
1462
+ return;
1463
+ }
1464
+ this.begin();
1465
+ if (op === "d") {
1466
+ this.setReg(reg, regText, r.linewise, "delete");
1467
+ if (r.linewise && r.end === v.length && !text.endsWith("\n") && r.start > 0) {
1468
+ this.replace(r.start - 1, r.end, "");
1469
+ this.off = firstNonBlank(this.value, r.start - 1);
1470
+ }
1471
+ else {
1472
+ this.replace(r.start, r.end, "");
1473
+ this.off = r.linewise ? firstNonBlank(this.value, r.start) : r.start;
1474
+ }
1475
+ this.off = this.clampLine(this.value, Math.min(this.off, this.value.length));
1476
+ if (nlines > 2)
1477
+ this.say(`${nlines} fewer lines`);
1478
+ }
1479
+ else if (op === "c") {
1480
+ this.setReg(reg, regText, r.linewise, "delete");
1481
+ this.replace(r.start, r.end, r.linewise && text.endsWith("\n") ? "\n" : "");
1482
+ this.off = r.start;
1483
+ this.enterInsert(1, false);
1484
+ return;
1485
+ }
1486
+ else if (op === ">" || op === "<") {
1487
+ const l1 = lineNo(v, r.start);
1488
+ const l2 = lineNo(v, Math.max(r.start, r.end - 1));
1489
+ const ls = v.split("\n");
1490
+ for (let l = l1; l <= l2; l++)
1491
+ for (let i = 0; i < n; i++)
1492
+ ls[l] = op === ">" ? (ls[l] !== "" ? "\t" + ls[l] : ls[l]) : ls[l].replace(/^(\t| {1,8})/, "");
1493
+ this.setText(ls.join("\n"));
1494
+ this.off = firstNonBlank(this.value, lineAt(this.value, l1));
1495
+ if (l2 - l1 + 1 > 2)
1496
+ this.say(`${l2 - l1 + 1} lines ${op}ed ${n} time${n > 1 ? "s" : ""}`);
1497
+ }
1498
+ else {
1499
+ const t = op === "gu" ? text.toLowerCase() : op === "gU" ? text.toUpperCase() : swapCase(text);
1500
+ this.replace(r.start, r.end, t);
1501
+ this.off = this.clampLine(this.value, r.start);
1502
+ }
1503
+ this.want = this.off - lineStart(this.value, this.off);
1504
+ this.end();
1505
+ }
1506
+ /* ==== SIMPLE CHANGES ==== */
1507
+ /* put a register after or before the cursor ("p" and "P") */
1508
+ put(reg, n, before) {
1509
+ const r = this.getReg(reg);
1510
+ if (!r) {
1511
+ this.fail(`E353: Nothing in register ${reg || "\""}`);
1512
+ return;
1513
+ }
1514
+ if (r.text.length * n > 100_000_000) {
1515
+ this.fail("E1240: Resulting text too long");
1516
+ return;
1517
+ }
1518
+ const v = this.value;
1519
+ const o = this.off;
1520
+ const text = r.text.repeat(n);
1521
+ this.begin();
1522
+ if (r.linewise) {
1523
+ let at = lineStart(v, o);
1524
+ let ins = text;
1525
+ if (!before) {
1526
+ const e = lineEnd(v, o);
1527
+ if (e === v.length) {
1528
+ at = e;
1529
+ ins = "\n" + text.slice(0, -1);
1530
+ }
1531
+ else
1532
+ at = e + 1;
1533
+ }
1534
+ this.replace(at, at, ins);
1535
+ this.off = firstNonBlank(this.value, ins.startsWith("\n") ? at + 1 : at);
1536
+ }
1537
+ else {
1538
+ const at = before || lineEnd(v, o) === o ? o : this.ops.next(v, o);
1539
+ this.replace(at, at, text);
1540
+ this.off = text.includes("\n") ? at : Math.max(at, this.ops.previous(this.value, at + text.length));
1541
+ }
1542
+ this.end();
1543
+ }
1544
+ /* replace the characters under the cursor ("r") */
1545
+ replaceChars(arg, n) {
1546
+ const ch = arg === "<Tab>" ? "\t" : arg === "<CR>" ? "\n" : arg;
1547
+ if (!isText(ch) || ch.startsWith("\u0000"))
1548
+ return;
1549
+ const v = this.value;
1550
+ const o = this.off;
1551
+ const le = lineEnd(v, o);
1552
+ let e = o;
1553
+ for (let i = 0; i < n; i++) {
1554
+ if (e >= le)
1555
+ return;
1556
+ e = this.ops.next(v, e);
1557
+ }
1558
+ this.begin();
1559
+ if (ch === "\n") {
1560
+ this.replace(o, e, "\n");
1561
+ this.off = o + 1;
1562
+ }
1563
+ else {
1564
+ this.replace(o, e, ch.repeat(n));
1565
+ this.off = o + ch.length * (n - 1);
1566
+ }
1567
+ this.end();
1568
+ }
1569
+ /* toggle the case of the characters under the cursor ("~") */
1570
+ toggleCase(n) {
1571
+ const v = this.value;
1572
+ const o = this.off;
1573
+ const le = lineEnd(v, o);
1574
+ let e = o;
1575
+ for (let i = 0; i < n && e < le; i++)
1576
+ e = this.ops.next(v, e);
1577
+ if (e === o)
1578
+ return;
1579
+ this.begin();
1580
+ this.replace(o, e, swapCase(v.slice(o, e)));
1581
+ this.off = this.clampLine(this.value, e);
1582
+ this.end();
1583
+ }
1584
+ /* add to the number under or after the cursor ("<C-a>" and "<C-x>") */
1585
+ increment(n) {
1586
+ const v = this.value;
1587
+ const ls = lineStart(v, this.off);
1588
+ const line = v.slice(ls, lineEnd(v, this.off));
1589
+ const col = this.off - ls;
1590
+ for (const m of line.matchAll(/-?\d+/g)) {
1591
+ const s = m.index;
1592
+ const e = s + m[0].length;
1593
+ if (e <= col)
1594
+ continue;
1595
+ const out = String(BigInt(m[0]) + BigInt(n));
1596
+ this.begin();
1597
+ this.replace(ls + s, ls + e, out);
1598
+ this.off = ls + s + out.length - 1;
1599
+ this.end();
1600
+ return;
1601
+ }
1602
+ }
1603
+ /* join lines, with or without inserting spaces ("J" and "gJ") */
1604
+ join(l, count, spaces) {
1605
+ let v = this.value;
1606
+ const s0 = lineAt(v, l);
1607
+ let pos = -1;
1608
+ for (let i = 1; i < count; i++) {
1609
+ const le = lineEnd(v, s0);
1610
+ if (le >= v.length)
1611
+ break;
1612
+ let k = le + 1;
1613
+ if (spaces)
1614
+ while (k < v.length && isSpace(v[k]))
1615
+ k++;
1616
+ const sep = spaces && k < v.length && v[k] !== "\n" && v[k] !== ")" && le > s0 && !isSpace(v[le - 1]) ? " " : "";
1617
+ v = v.slice(0, le) + sep + v.slice(k);
1618
+ pos = le;
1619
+ }
1620
+ if (pos < 0)
1621
+ return;
1622
+ this.setText(v);
1623
+ this.off = this.clampLine(v, pos);
1624
+ }
1625
+ /* move the cursor by lines, half pages, or pages (the scroll commands) */
1626
+ scroll(k, n, given) {
1627
+ const v = this.value;
1628
+ const half = Math.max(1, Math.floor(this.height / 2));
1629
+ const page = Math.max(1, this.height - 2);
1630
+ const amount = k === "<C-d>" || k === "<C-u>" ? (given ? n : half)
1631
+ : k === "<C-e>" || k === "<C-y>" ? n : page * n;
1632
+ const down = k === "<C-d>" || k === "<C-f>" || k === "<PageDown>" || k === "<C-e>";
1633
+ const l = lineNo(v, this.off);
1634
+ const t = Math.max(0, Math.min(lastLine(v), l + (down ? amount : -amount)));
1635
+ if (t === l)
1636
+ return;
1637
+ if (k === "<C-e>" || k === "<C-y>")
1638
+ this.off = this.column(v, t, this.want);
1639
+ else {
1640
+ this.off = firstNonBlank(v, lineAt(v, t));
1641
+ this.want = this.off - lineAt(v, t);
1642
+ }
1643
+ }
1644
+ /* ==== INSERT MODE ==== */
1645
+ /* enter insert mode, with a count and whether the count repeats on new lines */
1646
+ enterInsert(count, open) {
1647
+ this.mode = "insert";
1648
+ this.insCount = count;
1649
+ this.insOpen = open;
1650
+ this.insTokens = [];
1651
+ this.replaced = [];
1652
+ this.message = "";
1653
+ }
1654
+ /* leave insert mode, repeating the inserted keys for a count */
1655
+ leaveInsert() {
1656
+ if (this.insCount > 1) {
1657
+ const tokens = this.insTokens.filter((t) => t !== "<Esc>" && t !== "<C-c>" && t !== "<C-[>");
1658
+ for (let i = 1; i < this.insCount; i++) {
1659
+ if (this.insOpen)
1660
+ this.insertKey("<CR>");
1661
+ for (const t of tokens)
1662
+ this.insertKey(t);
1663
+ }
1664
+ }
1665
+ const v = this.value;
1666
+ this.mode = "normal";
1667
+ this.lastInsert = this.off;
1668
+ if (this.off > lineStart(v, this.off))
1669
+ this.off = this.ops.previous(v, this.off);
1670
+ this.off = this.clampLine(v, this.off);
1671
+ this.want = this.off - lineStart(v, this.off);
1672
+ this.end();
1673
+ if (this.recChange) {
1674
+ this.lastChange = this.change;
1675
+ this.recChange = false;
1676
+ }
1677
+ }
1678
+ /* perform an insert mode key ourselves (when replaying or not handled by the front end) */
1679
+ insertKey(t) {
1680
+ const v = this.value;
1681
+ const o = this.off;
1682
+ if (t.startsWith("\u0000")) {
1683
+ this.insertText(t.slice(1));
1684
+ return;
1685
+ }
1686
+ if (isText(t)) {
1687
+ if (this.mode === "replace")
1688
+ this.overwrite(t);
1689
+ else
1690
+ this.insertText(t);
1691
+ return;
1692
+ }
1693
+ switch (t) {
1694
+ case "<CR>":
1695
+ case "<C-j>":
1696
+ case "<C-m>":
1697
+ this.insertText("\n");
1698
+ break;
1699
+ case "<Tab>":
1700
+ case "<C-i>":
1701
+ if (this.mode === "replace")
1702
+ this.overwrite("\t");
1703
+ else
1704
+ this.insertText("\t");
1705
+ break;
1706
+ case "<BS>":
1707
+ case "<C-h>": {
1708
+ const r = this.mode === "replace" ? this.replaced.pop() : undefined;
1709
+ if (r) {
1710
+ this.replace(r.off, r.off + r.len, r.orig);
1711
+ this.off = r.off;
1712
+ }
1713
+ else if (o > 0) {
1714
+ const p = this.ops.previous(v, o);
1715
+ if (this.mode !== "replace")
1716
+ this.replace(p, o, "");
1717
+ this.off = p;
1718
+ }
1719
+ break;
1720
+ }
1721
+ case "<Del>":
1722
+ if (o < v.length)
1723
+ this.replace(o, this.ops.next(v, o), "");
1724
+ break;
1725
+ case "<C-w>": {
1726
+ const p = this.ops.wordStart(v, o);
1727
+ this.replace(p, o, "");
1728
+ this.off = p;
1729
+ break;
1730
+ }
1731
+ case "<C-u>": {
1732
+ const f = firstNonBlank(v, o);
1733
+ const p = o > f ? f : lineStart(v, o);
1734
+ this.replace(p, o, "");
1735
+ this.off = p;
1736
+ break;
1737
+ }
1738
+ case "<Left>":
1739
+ this.off = o > lineStart(v, o) ? this.ops.previous(v, o) : o;
1740
+ break;
1741
+ case "<Right>":
1742
+ this.off = o < lineEnd(v, o) ? this.ops.next(v, o) : o;
1743
+ break;
1744
+ case "<Home>":
1745
+ this.off = lineStart(v, o);
1746
+ break;
1747
+ case "<End>":
1748
+ this.off = lineEnd(v, o);
1749
+ break;
1750
+ case "<Up>":
1751
+ case "<Down>":
1752
+ this.off = this.ops.vertical(v, o, t === "<Up>" ? -1 : 1);
1753
+ break;
1754
+ }
1755
+ }
1756
+ /* insert a text at the cursor and move the cursor behind it */
1757
+ insertText(text) {
1758
+ const o = this.off;
1759
+ this.replace(o, o, text);
1760
+ this.off = o + text.length;
1761
+ }
1762
+ /* overwrite the character under the cursor (replace mode) */
1763
+ overwrite(ch) {
1764
+ const v = this.value;
1765
+ const o = this.off;
1766
+ const e = o < lineEnd(v, o) ? this.ops.next(v, o) : o;
1767
+ this.replaced.push({ off: o, orig: v.slice(o, e), len: ch.length });
1768
+ this.replace(o, e, ch);
1769
+ this.off = o + ch.length;
1770
+ }
1771
+ /* ==== COMMAND LINE ==== */
1772
+ /* open the command line for an Ex command or a search */
1773
+ openCmd(kind, text) {
1774
+ this.cmdFrom = this.mode;
1775
+ this.mode = "cmdline";
1776
+ this.cmdKind = kind;
1777
+ this.cmdText = text;
1778
+ this.cmdIdx = -1;
1779
+ this.message = "";
1780
+ this.error = false;
1781
+ }
1782
+ /* execute a search command line ("/" and "?") */
1783
+ searchCmd(text) {
1784
+ const pattern = text || this.search?.pattern;
1785
+ if (!pattern) {
1786
+ this.fail("E35: No previous regular expression");
1787
+ return;
1788
+ }
1789
+ const forward = this.cmdKind === "/";
1790
+ this.search = { pattern, forward };
1791
+ this.hlsearch = true;
1792
+ this.say(this.cmdKind + pattern);
1793
+ const q = this.find(pattern, this.off, forward);
1794
+ if (q !== null)
1795
+ this.go({ to: q, linewise: false, inclusive: false }, true);
1796
+ }
1797
+ /* find the next match of a pattern, wrapping around the text end */
1798
+ find(pattern, from, fwd) {
1799
+ const re = toRegExp(pattern, this.icase(pattern));
1800
+ if (!re) {
1801
+ this.fail(`E486: Pattern not found: ${pattern}`);
1802
+ return null;
1803
+ }
1804
+ const all = [...this.value.matchAll(re)].map((m) => m.index);
1805
+ if (all.length === 0) {
1806
+ this.fail(`E486: Pattern not found: ${pattern}`);
1807
+ return null;
1808
+ }
1809
+ if (fwd) {
1810
+ const q = all.find((i) => i > from);
1811
+ if (q !== undefined)
1812
+ return q;
1813
+ this.fail("search hit BOTTOM, continuing at TOP", false);
1814
+ return all[0];
1815
+ }
1816
+ const q = all.findLast((i) => i < from);
1817
+ if (q !== undefined)
1818
+ return q;
1819
+ this.fail("search hit TOP, continuing at BOTTOM", false);
1820
+ return all[all.length - 1];
1821
+ }
1822
+ /* parse a line address like "12", ".", "$", "'a", or ".+3" */
1823
+ addr(s, i) {
1824
+ const v = this.value;
1825
+ const rest = s.slice(i);
1826
+ let line = null;
1827
+ let m = /^(\d+|\.|\$|'[a-zA-Z<>'])/.exec(rest);
1828
+ if (m) {
1829
+ if (m[1] === ".")
1830
+ line = lineNo(v, this.off);
1831
+ else if (m[1] === "$")
1832
+ line = lastLine(v);
1833
+ else if (m[1].startsWith("'")) {
1834
+ const p = this.marks.get(m[1][1]);
1835
+ if (p === undefined)
1836
+ return null;
1837
+ line = lineNo(v, Math.min(p, v.length));
1838
+ }
1839
+ else
1840
+ line = parseInt(m[1], 10) - 1;
1841
+ }
1842
+ let len = m ? m[0].length : 0;
1843
+ m = /^([+-])(\d*)/.exec(rest.slice(len));
1844
+ if (m) {
1845
+ line = (line ?? lineNo(v, this.off)) + (m[1] === "+" ? 1 : -1) * (m[2] ? parseInt(m[2], 10) : 1);
1846
+ len += m[0].length;
1847
+ }
1848
+ return line === null ? null : [line, i + len];
1849
+ }
1850
+ /* execute an Ex command line */
1851
+ ex(input) {
1852
+ this.lastEx = input;
1853
+ const v = this.value;
1854
+ const last = lastLine(v);
1855
+ let s = input.replace(/^[\s:]+/, "");
1856
+ let from = lineNo(v, this.off);
1857
+ let to = from;
1858
+ let ranged = false;
1859
+ if (s.startsWith("%")) {
1860
+ from = 0;
1861
+ to = last;
1862
+ ranged = true;
1863
+ s = s.slice(1);
1864
+ }
1865
+ else {
1866
+ const a = this.addr(s, 0);
1867
+ if (a) {
1868
+ from = to = a[0];
1869
+ ranged = true;
1870
+ let i = a[1];
1871
+ if (s[i] === "," || s[i] === ";") {
1872
+ const b = this.addr(s, i + 1);
1873
+ if (b) {
1874
+ to = b[0];
1875
+ i = b[1];
1876
+ }
1877
+ }
1878
+ s = s.slice(i);
1879
+ }
1880
+ }
1881
+ s = s.trim();
1882
+ if (from > to)
1883
+ [from, to] = [to, from];
1884
+ if (from < 0 || to > last) {
1885
+ this.fail("E16: Invalid range");
1886
+ return;
1887
+ }
1888
+ if (s === "") {
1889
+ if (ranged)
1890
+ this.go({ to: firstNonBlank(v, lineAt(v, to)), linewise: true, inclusive: false }, true);
1891
+ return;
1892
+ }
1893
+ const sub = /^(?:s|substitute)([^\w\s"|])(.*)$/.exec(s);
1894
+ if (sub) {
1895
+ this.substitute(from, to, sub[1], sub[2]);
1896
+ return;
1897
+ }
1898
+ const m = /^([a-zA-Z]+|[<>&]+)(!?)\s*(.*)$/.exec(s);
1899
+ const name = m ? m[1] : s;
1900
+ const arg = m ? m[3] : "";
1901
+ const lines = { start: lineAt(v, from), end: lineEndNl(v, lineAt(v, to)), linewise: true };
1902
+ switch (name) {
1903
+ case "d":
1904
+ case "de":
1905
+ case "del":
1906
+ case "delete":
1907
+ this.apply("d", lines, arg);
1908
+ return;
1909
+ case "y":
1910
+ case "ya":
1911
+ case "yank": {
1912
+ const o = this.off;
1913
+ this.apply("y", lines, arg);
1914
+ this.off = o;
1915
+ return;
1916
+ }
1917
+ case "j":
1918
+ case "join":
1919
+ this.begin();
1920
+ this.join(from, Math.max(2, to - from + 1), m?.[2] !== "!");
1921
+ this.end();
1922
+ return;
1923
+ case "u":
1924
+ case "undo":
1925
+ this.undo(1);
1926
+ return;
1927
+ case "red":
1928
+ case "redo":
1929
+ this.redo(1);
1930
+ return;
1931
+ case "noh":
1932
+ case "nohl":
1933
+ case "nohlsearch":
1934
+ this.hlsearch = false;
1935
+ return;
1936
+ case "&":
1937
+ case "&&":
1938
+ if (this.lastSub)
1939
+ this.substitute(from, to, "\u0001", `${this.lastSub.pat}\u0001${this.lastSub.rep}\u0001${name === "&&" ? this.lastSub.flags : ""}`);
1940
+ return;
1941
+ case "set":
1942
+ case "se":
1943
+ this.setOption(arg);
1944
+ return;
1945
+ case "reg":
1946
+ case "registers":
1947
+ case "di":
1948
+ case "display":
1949
+ this.say([...this.regs.entries()]
1950
+ .map(([k, r]) => `"${k} ${JSON.stringify(r.text).slice(1, -1).slice(0, 29)}`).join(" ") || "no registers");
1951
+ return;
1952
+ }
1953
+ if (/^[<>]+$/.test(name)) {
1954
+ this.apply(name[0], lines, "", name.length);
1955
+ return;
1956
+ }
1957
+ this.runHost(s);
1958
+ }
1959
+ /* pass an Ex command to the host and show its result */
1960
+ runHost(command) {
1961
+ const res = this.host(command);
1962
+ if (res === undefined)
1963
+ this.fail(`E492: Not an editor command: ${command}`);
1964
+ else if (res !== null) {
1965
+ if (/^E\d+:/.test(res))
1966
+ this.fail(res);
1967
+ else
1968
+ this.say(res);
1969
+ }
1970
+ }
1971
+ /* set the options of ":set" */
1972
+ setOption(arg) {
1973
+ for (const opt of arg.split(/\s+/).filter((o) => o !== "")) {
1974
+ const on = !opt.startsWith("no");
1975
+ const name = on ? opt : opt.slice(2);
1976
+ if (name === "hlsearch" || name === "hls")
1977
+ this.hlsearch = on;
1978
+ else if (name === "ignorecase" || name === "ic")
1979
+ this.ignorecase = on;
1980
+ else if (name === "smartcase" || name === "scs")
1981
+ this.smartcase = on;
1982
+ else {
1983
+ this.fail(`E518: Unknown option: ${opt}`);
1984
+ return;
1985
+ }
1986
+ }
1987
+ }
1988
+ /* substitute a pattern on a line range (":s") */
1989
+ substitute(from, to, delim, body) {
1990
+ const [p = "", rep = "", flags = ""] = splitDelim(body, delim);
1991
+ const pat = p || this.search?.pattern || "";
1992
+ if (!pat) {
1993
+ this.fail("E35: No previous regular expression");
1994
+ return;
1995
+ }
1996
+ if (flags.includes("c")) {
1997
+ this.fail("confirm flag \"c\" is not supported");
1998
+ return;
1999
+ }
2000
+ this.lastSub = { pat, rep, flags };
2001
+ this.search = { pattern: pat, forward: true };
2002
+ this.hlsearch = true;
2003
+ const icase = flags.includes("I") ? false : flags.includes("i") || this.icase(pat);
2004
+ const re = toRegExp(pat, icase);
2005
+ if (!re) {
2006
+ this.fail(`E486: Pattern not found: ${pat}`);
2007
+ return;
2008
+ }
2009
+ const once = new RegExp(re.source, re.flags.replace("g", ""));
2010
+ const lines = this.value.split("\n");
2011
+ let subs = 0, changed = 0, lastL = -1;
2012
+ for (let l = from; l <= to; l++) {
2013
+ let hit = false;
2014
+ const out = lines[l].replace(flags.includes("g") ? re : once, (...args) => {
2015
+ subs++;
2016
+ hit = true;
2017
+ return expandRep(rep, args);
2018
+ });
2019
+ if (hit) {
2020
+ lines[l] = out;
2021
+ changed++;
2022
+ lastL = l;
2023
+ }
2024
+ }
2025
+ if (subs === 0) {
2026
+ this.fail(`E486: Pattern not found: ${pat}`);
2027
+ return;
2028
+ }
2029
+ /* the "n" flag just reports the number of matches */
2030
+ if (flags.includes("n")) {
2031
+ this.say(`${subs} match${subs > 1 ? "es" : ""} on ${changed} line${changed > 1 ? "s" : ""}`);
2032
+ return;
2033
+ }
2034
+ this.begin();
2035
+ this.setText(lines.join("\n"));
2036
+ this.off = firstNonBlank(this.value, lineAt(this.value, lastL));
2037
+ this.end();
2038
+ if (subs > 2)
2039
+ this.say(`${subs} substitutions on ${changed} line${changed > 1 ? "s" : ""}`);
2040
+ }
2041
+ /* ==== REPEATING, MACROS, AND UNDO ==== */
2042
+ /* repeat the last change, optionally with a new count (".") */
2043
+ dot(c) {
2044
+ let tokens = this.lastChange;
2045
+ if (tokens.length === 0)
2046
+ return;
2047
+ if (c.count > 0) {
2048
+ /* the new count replaces the counts before and after the register and the operator */
2049
+ const old = tokens;
2050
+ const skip = (i) => {
2051
+ if (/^[1-9]$/.test(old[i] ?? ""))
2052
+ while (/^[0-9]$/.test(old[i] ?? ""))
2053
+ i++;
2054
+ return i;
2055
+ };
2056
+ let i = skip(0);
2057
+ const head = [];
2058
+ if (old[i] === "\"") {
2059
+ head.push(...old.slice(i, i + 2));
2060
+ i = skip(i + 2);
2061
+ }
2062
+ const len = PREFIXES.has(old[i] ?? "") ? 2 : 1;
2063
+ const cmd = old.slice(i, i + len);
2064
+ const rest = OPERATORS.has(cmd.join("")) ? old.slice(skip(i + len)) : old.slice(i + len);
2065
+ tokens = [...head, ...String(c.count).split(""), ...cmd, ...rest];
2066
+ }
2067
+ this.replay(tokens);
2068
+ }
2069
+ /* replay key tokens, guarded against endless recursion and optionally aborted
2070
+ by a failing command (returning whether no command failed) */
2071
+ replay(tokens, abort = false) {
2072
+ if (this.depth > 100)
2073
+ return false;
2074
+ this.depth++;
2075
+ this.failed = false;
2076
+ for (const t of tokens) {
2077
+ this.feed(t, false);
2078
+ if (abort && this.failed)
2079
+ break;
2080
+ }
2081
+ this.depth--;
2082
+ return !this.failed;
2083
+ }
2084
+ /* start or stop recording a macro into a register ("q") */
2085
+ macroRecord(reg) {
2086
+ if (this.recording) {
2087
+ if (this.macro[this.macro.length - 1] === "q")
2088
+ this.macro.pop();
2089
+ this.macros.set(this.recording, this.macro);
2090
+ const text = this.macro.filter((t) => isText(t)).map((t) => t.startsWith("\u0000") ? t.slice(1) : t).join("");
2091
+ this.regs.set(this.recording, { text, linewise: false });
2092
+ this.recording = "";
2093
+ return;
2094
+ }
2095
+ if (!/^[a-zA-Z0-9]$/.test(reg))
2096
+ return;
2097
+ const lower = reg.toLowerCase();
2098
+ this.macro = reg !== lower ? [...(this.macros.get(lower) ?? [])] : [];
2099
+ this.recording = lower;
2100
+ this.message = "";
2101
+ }
2102
+ /* play a macro or the last Ex command ("@") */
2103
+ macroPlay(reg, n) {
2104
+ if (reg === ":") {
2105
+ for (let i = 0; i < n && this.lastEx; i++)
2106
+ this.ex(this.lastEx);
2107
+ return;
2108
+ }
2109
+ const r = (reg === "@" ? this.lastMacro : reg).toLowerCase();
2110
+ if (!r)
2111
+ return;
2112
+ this.lastMacro = r;
2113
+ const tokens = this.macros.get(r) ?? [...(this.regs.get(r)?.text ?? "")].map((c) => c === "\n" ? "<CR>" : c);
2114
+ for (let i = 0; i < n; i++)
2115
+ if (!this.replay(tokens, true))
2116
+ break;
2117
+ }
2118
+ /* open an undo step */
2119
+ begin() {
2120
+ this.undos.push({ value: this.value, off: this.off });
2121
+ if (this.undos.length > 1000)
2122
+ this.undos.shift();
2123
+ this.redoSave = this.redos;
2124
+ this.redos = [];
2125
+ }
2126
+ /* close an undo step, dropping it where nothing changed */
2127
+ end() {
2128
+ const top = this.undos[this.undos.length - 1];
2129
+ if (top && top.value === this.value) {
2130
+ this.undos.pop();
2131
+ this.redos = this.redoSave;
2132
+ }
2133
+ }
2134
+ /* undo up to "n" changes */
2135
+ undo(n) {
2136
+ let done = 0;
2137
+ for (let i = 0; i < n && this.undos.length > 0; i++, done++) {
2138
+ const s = this.undos.pop();
2139
+ this.redos.push({ value: this.value, off: s.off });
2140
+ this.value = s.value;
2141
+ this.off = s.off;
2142
+ }
2143
+ if (done === 0) {
2144
+ this.say("Already at oldest change");
2145
+ return;
2146
+ }
2147
+ this.emit(this.value);
2148
+ this.off = this.clampLine(this.value, Math.min(this.off, this.value.length));
2149
+ this.say(`${done} change${done > 1 ? "s" : ""}; before #${this.undos.length + 1}`);
2150
+ }
2151
+ /* redo up to "n" undone changes */
2152
+ redo(n) {
2153
+ let done = 0;
2154
+ for (let i = 0; i < n && this.redos.length > 0; i++, done++) {
2155
+ const s = this.redos.pop();
2156
+ this.undos.push({ value: this.value, off: s.off });
2157
+ this.value = s.value;
2158
+ this.off = s.off;
2159
+ }
2160
+ if (done === 0) {
2161
+ this.say("Already at newest change");
2162
+ return;
2163
+ }
2164
+ this.emit(this.value);
2165
+ this.off = this.clampLine(this.value, Math.min(this.off, this.value.length));
2166
+ this.say(`${done} change${done > 1 ? "s" : ""}; after #${this.undos.length}`);
2167
+ }
2168
+ /* ==== REGISTERS AND HELPERS ==== */
2169
+ /* store a yanked or deleted text into a register and the unnamed and numbered ones */
2170
+ setReg(reg, text, linewise, kind) {
2171
+ if (reg === "_")
2172
+ return;
2173
+ let r = { text, linewise };
2174
+ if (/^[A-Z]$/.test(reg)) {
2175
+ const old = this.regs.get(reg.toLowerCase());
2176
+ /* mixing a linewise and a charwise text makes the latter whole lines */
2177
+ if (old) {
2178
+ const mix = old.linewise !== linewise;
2179
+ r = { text: old.text + (mix && linewise ? "\n" : "") + text + (mix && old.linewise ? "\n" : ""),
2180
+ linewise: old.linewise || linewise };
2181
+ }
2182
+ this.regs.set(reg.toLowerCase(), r);
2183
+ }
2184
+ else if (reg !== "" && reg !== "\"")
2185
+ this.regs.set(reg, r);
2186
+ else if (kind === "yank")
2187
+ this.regs.set("0", r);
2188
+ else
2189
+ this.regs.set(linewise || text.includes("\n") ? "1" : "-", r);
2190
+ this.macros.delete(reg.toLowerCase());
2191
+ if (reg === "+" || reg === "*")
2192
+ this.clip(text);
2193
+ this.regs.set("\"", r);
2194
+ }
2195
+ /* the register of a name (the unnamed one for an empty name) */
2196
+ getReg(reg) {
2197
+ return this.regs.get(reg === "" ? "\"" : reg.toLowerCase());
2198
+ }
2199
+ /* replace a range of the text */
2200
+ replace(s, e, text) {
2201
+ this.setText(this.value.slice(0, s) + text + this.value.slice(e));
2202
+ }
2203
+ /* set the entire text and emit it to the front end */
2204
+ setText(value) {
2205
+ this.value = value;
2206
+ this.emit(value);
2207
+ }
2208
+ /* show an informational message */
2209
+ say(text) {
2210
+ this.message = text;
2211
+ this.error = false;
2212
+ }
2213
+ /* show an error message (aborting a replay, unless just a warning) */
2214
+ fail(text, abort = true) {
2215
+ this.message = text;
2216
+ this.error = true;
2217
+ if (abort)
2218
+ this.failed = true;
2219
+ }
2220
+ }