@rse/ink-editor 0.0.0-stage → 0.9.0

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,884 @@
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
+ /* Nano 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, toOffset, isWord, wordBegin, paragraphEnd, paragraphBegin, isBlank, literalRegExp, findNext, findPrevious, goalColumn, rowMove, fillParagraph } from "./ink-editor-text";
28
+ /* the key bindings, from keys to the function names of Nano */
29
+ const BINDINGS = new Map(Object.entries({
30
+ "^G": "help",
31
+ "^X": "exit",
32
+ "^O": "writeout",
33
+ "^S": "savefile",
34
+ "^R": "insert",
35
+ "^W": "whereis",
36
+ "^Q": "wherewas",
37
+ "M-W": "findnext",
38
+ "M-Q": "findprevious",
39
+ "^\\": "replace",
40
+ "M-R": "replace",
41
+ "^K": "cut",
42
+ "^U": "paste",
43
+ "M-6": "copy",
44
+ "M-^": "copy",
45
+ "M-T": "cutrestoffile",
46
+ "^J": "justify",
47
+ "^C": "location",
48
+ "^_": "gotoline",
49
+ "M-G": "gotoline",
50
+ "M-U": "undo",
51
+ "M-E": "redo",
52
+ "M-A": "mark",
53
+ "^^": "mark",
54
+ "M-}": "indent",
55
+ "M-{": "unindent",
56
+ "M-3": "comment",
57
+ "Tab": "tab",
58
+ "Enter": "enter",
59
+ "^A": "home",
60
+ "Home": "home",
61
+ "^E": "end",
62
+ "End": "end",
63
+ "^F": "forward",
64
+ "Right": "forward",
65
+ "^B": "back",
66
+ "Left": "back",
67
+ "^P": "prevline",
68
+ "Up": "prevline",
69
+ "^N": "nextline",
70
+ "Down": "nextline",
71
+ "^Y": "prevpage",
72
+ "PgUp": "prevpage",
73
+ "^V": "nextpage",
74
+ "PgDn": "nextpage",
75
+ "M-\\": "firstline",
76
+ "^Home": "firstline",
77
+ "M-/": "lastline",
78
+ "^End": "lastline",
79
+ "^Space": "nextword",
80
+ "^Right": "nextword",
81
+ "M-Space": "prevword",
82
+ "^Left": "prevword",
83
+ "M-(": "beginpara",
84
+ "^Up": "beginpara",
85
+ "M-)": "endpara",
86
+ "^Down": "endpara",
87
+ "M-]": "findbracket",
88
+ "^D": "delete",
89
+ "Del": "delete",
90
+ "Bsp": "backspace",
91
+ "M-Bsp": "chopwordleft",
92
+ "^Del": "chopwordright",
93
+ "M-D": "wordcount",
94
+ "^L": "refresh",
95
+ "^Z": "suspend",
96
+ "M-V": "verbatim",
97
+ "^T": "execute"
98
+ }));
99
+ /* the kinds of changes, as named by undoing and redoing */
100
+ const CHANGES = {
101
+ insertchar: "addition", tab: "addition", enter: "line break", paste: "paste",
102
+ cut: "cut", cutrestoffile: "cut", backspace: "deletion", delete: "deletion",
103
+ chopwordleft: "deletion", chopwordright: "deletion", justify: "justification",
104
+ indent: "indent", unindent: "unindent", comment: "comment", replace: "replacement"
105
+ };
106
+ /* the short help of the key bindings */
107
+ const HELP = "^G Help ^X Exit ^O Write Out ^S Save ^W Where Is ^Q Where Was ^\\ Replace " +
108
+ "^K Cut ^U Paste M-6 Copy M-A Mark M-U Undo M-E Redo ^_ Go To Line ^C Location ^J Justify";
109
+ /* the brackets matched by "findbracket" */
110
+ const BRACKETS = {
111
+ "(": ["(", ")", 1], ")": ["(", ")", -1], "[": ["[", "]", 1], "]": ["[", "]", -1],
112
+ "{": ["{", "}", 1], "}": ["{", "}", -1], "<": ["<", ">", 1], ">": ["<", ">", -1]
113
+ };
114
+ /* the column of justifying paragraphs */
115
+ const FILL_COLUMN = 72;
116
+ /* whether a key token is a printable character, and the plural of a count */
117
+ const isChar = (t) => [...t].length === 1 && t >= " ";
118
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
119
+ /* the Nano editing engine, operating on a plain string value and a cursor offset */
120
+ export class Nano {
121
+ constructor(value, ops) {
122
+ /* bindings to the outside */
123
+ this.emit = () => { };
124
+ this.clip = () => { };
125
+ this.files = null;
126
+ this.height = 24;
127
+ this.off = 0;
128
+ this.mark = null;
129
+ this.message = "";
130
+ this.error = false;
131
+ this.esc = false;
132
+ this.cmd = "";
133
+ this.lastCmd = "";
134
+ this.recorded = false;
135
+ this.typing = false;
136
+ this.undos = [];
137
+ this.redos = [];
138
+ this.cutbuf = "";
139
+ this.goal = null;
140
+ this.found = null;
141
+ this.input = null;
142
+ this.question = null;
143
+ this.rep = null;
144
+ this.verbatim = false;
145
+ this.lastSearch = "";
146
+ this.value = value;
147
+ this.seen = value;
148
+ this.ops = ops;
149
+ }
150
+ /* ==== EXTERNAL INTERFACE ==== */
151
+ /* take over an externally changed value */
152
+ sync(value) {
153
+ if (value === this.seen)
154
+ return;
155
+ this.seen = value;
156
+ if (value === this.value)
157
+ return;
158
+ this.value = value;
159
+ this.off = Math.min(this.off, value.length);
160
+ if (this.mark !== null)
161
+ this.mark = Math.min(this.mark, value.length);
162
+ }
163
+ /* handle the key tokens of a key press (like [ "x" ], [ "^X" ], [ "M-U" ], or [ "Up" ]) */
164
+ keys(tokens) {
165
+ for (const t of tokens)
166
+ this.dispatch(t);
167
+ return true;
168
+ }
169
+ /* handle a bracketed paste */
170
+ paste(text) {
171
+ if (this.input !== null)
172
+ this.input.text += text.replace(/\r?\n/g, " ");
173
+ else if (this.question === null && this.rep === null) {
174
+ this.recorded = false;
175
+ this.found = null;
176
+ this.cmd = "paste";
177
+ this.insert(text);
178
+ this.cmd = "";
179
+ this.lastCmd = "paste";
180
+ }
181
+ }
182
+ /* take over a text change of the front end */
183
+ onText(value) {
184
+ this.recorded = false;
185
+ this.record();
186
+ this.value = value;
187
+ this.off = Math.min(this.off, value.length);
188
+ this.lastCmd = "";
189
+ if (this.mark !== null)
190
+ this.mark = Math.min(this.mark, value.length);
191
+ this.emit(value);
192
+ }
193
+ /* take over a cursor change of the front end (a mouse click) */
194
+ onCursor(cursor) {
195
+ if (this.prompt() === null) {
196
+ this.off = toOffset(this.value, cursor);
197
+ this.lastCmd = "";
198
+ }
199
+ }
200
+ /* take over a mouse selection as the marked region */
201
+ onSelect(sel) {
202
+ if (this.prompt() !== null || !sel || sel[0] === sel[1])
203
+ return false;
204
+ this.mark = sel[0];
205
+ this.off = sel[1];
206
+ this.lastCmd = "";
207
+ return true;
208
+ }
209
+ /* the region to be drawn: the current replace match, the found match, or the marked region */
210
+ selection() {
211
+ if (this.rep !== null)
212
+ return this.rep.match;
213
+ if (this.found !== null)
214
+ return this.found;
215
+ if (this.mark !== null && this.mark !== this.off)
216
+ return this.mark < this.off ? [this.mark, this.off] : [this.off, this.mark];
217
+ return null;
218
+ }
219
+ /* the prompt of the status bar (with its input), or null without one */
220
+ prompt() {
221
+ if (this.question !== null)
222
+ return this.question.prompt;
223
+ if (this.input !== null)
224
+ return this.input.prompt + this.input.text;
225
+ if (this.rep !== null)
226
+ return "Replace this instance? (Y/N/A/^C) ";
227
+ if (this.verbatim)
228
+ return "Verbatim Input: ";
229
+ return null;
230
+ }
231
+ /* the text being replaced, to be highlighted */
232
+ searched() {
233
+ return this.rep !== null ? this.rep.from : null;
234
+ }
235
+ /* ==== KEY DISPATCHING ==== */
236
+ /* dispatch a key token by the current input state */
237
+ dispatch(token) {
238
+ /* an Esc turns the next key into a Meta key, and a second one cancels */
239
+ let t = token;
240
+ if (this.esc) {
241
+ this.esc = false;
242
+ t = t === "Esc" ? "Cancel" : t === " " ? "M-Space" : isChar(t) ? `M-${t.toUpperCase()}` : `M-${t}`;
243
+ }
244
+ else if (t === "Esc") {
245
+ this.esc = true;
246
+ return;
247
+ }
248
+ this.recorded = false;
249
+ this.found = null;
250
+ if (this.verbatim) {
251
+ this.verbatim = false;
252
+ this.cmd = "insertchar";
253
+ this.insert(isChar(t) ? t : t === "Tab" ? "\t" : t === "Enter" ? "\n" : "");
254
+ this.cmd = "";
255
+ this.lastCmd = "insertchar";
256
+ }
257
+ else if (this.question !== null) {
258
+ const q = this.question;
259
+ this.question = null;
260
+ q.take(t);
261
+ }
262
+ else if (this.input !== null)
263
+ this.inputKey(t);
264
+ else if (this.rep !== null)
265
+ this.replaceKey(t);
266
+ else
267
+ this.bufferKey(t);
268
+ }
269
+ /* handle a key of the buffer */
270
+ bufferKey(t) {
271
+ this.message = "";
272
+ this.error = false;
273
+ const cmd = BINDINGS.get(t) ?? (isChar(t) ? "insertchar" : undefined);
274
+ if (cmd === undefined) {
275
+ if (t !== "Cancel")
276
+ this.fail(`Unbound key: ${t}`);
277
+ this.lastCmd = "";
278
+ return;
279
+ }
280
+ this.cmd = cmd;
281
+ this.exec(cmd, t);
282
+ this.cmd = "";
283
+ this.lastCmd = cmd;
284
+ }
285
+ /* ==== FUNCTIONS ==== */
286
+ /* execute a function with its key */
287
+ exec(cmd, t) {
288
+ const v = this.value;
289
+ const o = this.off;
290
+ switch (cmd) {
291
+ /* ---- files and quitting ---- */
292
+ case "help":
293
+ this.say(HELP);
294
+ break;
295
+ case "exit": {
296
+ const f = this.need();
297
+ if (f === null)
298
+ break;
299
+ if (!f.modified()) {
300
+ f.quit();
301
+ break;
302
+ }
303
+ this.ask("Save modified buffer? (Answering \"No\" will DISCARD changes.)", () => this.writeOut(true), () => f.quit());
304
+ break;
305
+ }
306
+ case "writeout":
307
+ this.writeOut(false);
308
+ break;
309
+ case "savefile": {
310
+ const f = this.need();
311
+ if (f === null)
312
+ break;
313
+ if (f.name() === "")
314
+ this.writeOut(false);
315
+ else
316
+ this.outcome(f.write("", false, false));
317
+ break;
318
+ }
319
+ case "insert":
320
+ this.fail("Inserting files is not supported");
321
+ break;
322
+ case "suspend":
323
+ this.fail("Suspension is not enabled");
324
+ break;
325
+ case "execute":
326
+ this.fail("Executing commands is not supported");
327
+ break;
328
+ case "refresh":
329
+ break;
330
+ /* ---- searching and replacing ---- */
331
+ case "whereis":
332
+ case "wherewas": {
333
+ const forward = cmd === "whereis";
334
+ const last = this.lastSearch !== "" ? ` [${this.lastSearch}]` : "";
335
+ this.read(`Search${forward ? "" : " Backward"}${last}: `, "", (text) => {
336
+ const s = text !== "" ? text : this.lastSearch;
337
+ if (s === "") {
338
+ this.fail("Cancelled");
339
+ return;
340
+ }
341
+ this.lastSearch = s;
342
+ this.search(forward);
343
+ });
344
+ break;
345
+ }
346
+ case "findnext":
347
+ case "findprevious":
348
+ if (this.lastSearch === "")
349
+ this.fail("No current search pattern");
350
+ else
351
+ this.search(cmd === "findnext");
352
+ break;
353
+ case "replace": {
354
+ const last = this.lastSearch !== "" ? ` [${this.lastSearch}]` : "";
355
+ this.read(`Search (to replace)${last}: `, "", (text) => {
356
+ const from = text !== "" ? text : this.lastSearch;
357
+ if (from === "") {
358
+ this.fail("Cancelled");
359
+ return;
360
+ }
361
+ this.lastSearch = from;
362
+ this.read("Replace with: ", "", (to) => this.replaceStart(from, to));
363
+ });
364
+ break;
365
+ }
366
+ /* ---- cutting and pasting ---- */
367
+ case "cut": {
368
+ if (this.mark !== null) {
369
+ this.cutbuf = this.cutRegion();
370
+ this.clip(this.cutbuf);
371
+ break;
372
+ }
373
+ const ls = lineStart(v, o);
374
+ const le = lineEnd(v, o);
375
+ /* like the "magic line" of nano, the empty last line has nothing to cut */
376
+ if (ls === le && le === v.length)
377
+ break;
378
+ const e = le < v.length ? le + 1 : le;
379
+ const text = le < v.length ? v.slice(ls, e) : v.slice(ls, le) + "\n";
380
+ this.cutbuf = this.lastCmd === "cut" ? this.cutbuf + text : text;
381
+ this.replace(ls, e, "");
382
+ this.off = ls;
383
+ this.clip(this.cutbuf);
384
+ break;
385
+ }
386
+ case "copy": {
387
+ if (this.mark !== null) {
388
+ const [s, e] = this.region();
389
+ this.cutbuf = v.slice(s, e);
390
+ this.mark = null;
391
+ }
392
+ else {
393
+ const le = lineEnd(v, o);
394
+ const text = v.slice(lineStart(v, o), le) + "\n";
395
+ this.cutbuf = this.lastCmd === "copy" ? this.cutbuf + text : text;
396
+ this.off = le < v.length ? le + 1 : le;
397
+ }
398
+ this.clip(this.cutbuf);
399
+ break;
400
+ }
401
+ case "cutrestoffile":
402
+ this.cutbuf = v.slice(o);
403
+ this.replace(o, v.length, "");
404
+ this.mark = null;
405
+ this.clip(this.cutbuf);
406
+ break;
407
+ case "paste":
408
+ this.insert(this.cutbuf);
409
+ break;
410
+ /* ---- the mark ---- */
411
+ case "mark":
412
+ if (this.mark !== null) {
413
+ this.mark = null;
414
+ this.say("Mark Unset");
415
+ }
416
+ else {
417
+ this.mark = o;
418
+ this.say("Mark Set");
419
+ }
420
+ break;
421
+ /* ---- inserting and deleting ---- */
422
+ case "insertchar":
423
+ this.insert(t);
424
+ break;
425
+ case "enter":
426
+ this.insert("\n");
427
+ break;
428
+ case "tab":
429
+ if (this.mark !== null)
430
+ this.indent(true);
431
+ else
432
+ this.insert("\t");
433
+ break;
434
+ case "delete":
435
+ if (o < v.length)
436
+ this.replace(o, this.ops.next(v, o), "");
437
+ break;
438
+ case "backspace":
439
+ if (o > 0) {
440
+ const p = this.ops.previous(v, o);
441
+ this.replace(p, o, "");
442
+ this.off = p;
443
+ }
444
+ break;
445
+ case "chopwordleft": {
446
+ const s = wordBegin(v, o);
447
+ this.replace(s, o, "");
448
+ this.off = s;
449
+ break;
450
+ }
451
+ case "chopwordright":
452
+ this.replace(o, this.nextWord(o), "");
453
+ break;
454
+ /* ---- changing ---- */
455
+ case "indent":
456
+ case "unindent":
457
+ this.indent(cmd === "indent");
458
+ break;
459
+ case "comment":
460
+ this.comment();
461
+ break;
462
+ case "justify": {
463
+ const f = fillParagraph(v, o, FILL_COLUMN);
464
+ if (f === null)
465
+ break;
466
+ if (f.text !== v.slice(f.start, f.end))
467
+ this.replace(f.start, f.end, f.text);
468
+ this.off = f.start + f.text.length;
469
+ this.say("Justified paragraph");
470
+ break;
471
+ }
472
+ case "undo":
473
+ case "redo":
474
+ this.undo(cmd === "undo");
475
+ break;
476
+ /* ---- moving ---- */
477
+ case "home":
478
+ this.off = lineStart(v, o);
479
+ break;
480
+ case "end":
481
+ this.off = lineEnd(v, o);
482
+ break;
483
+ case "forward":
484
+ this.off = this.ops.next(v, o);
485
+ break;
486
+ case "back":
487
+ this.off = this.ops.previous(v, o);
488
+ break;
489
+ case "prevline":
490
+ case "nextline":
491
+ this.rows(cmd === "nextline" ? 1 : -1);
492
+ break;
493
+ case "prevpage":
494
+ case "nextpage":
495
+ this.rows((cmd === "nextpage" ? 1 : -1) * Math.max(1, this.height - 2));
496
+ break;
497
+ case "firstline":
498
+ this.off = 0;
499
+ break;
500
+ case "lastline":
501
+ this.off = v.length;
502
+ break;
503
+ case "nextword":
504
+ this.off = this.nextWord(o);
505
+ break;
506
+ case "prevword":
507
+ this.off = wordBegin(v, o);
508
+ break;
509
+ case "beginpara": {
510
+ let p = paragraphBegin(v, o);
511
+ if (isBlank(v, p) && p < v.length && lineEnd(v, p) < v.length)
512
+ p = lineEnd(v, p) + 1;
513
+ this.off = p;
514
+ break;
515
+ }
516
+ case "endpara":
517
+ this.off = paragraphEnd(v, o);
518
+ break;
519
+ case "findbracket":
520
+ this.findBracket();
521
+ break;
522
+ case "gotoline":
523
+ this.read("Enter line number, column number: ", "", (text) => {
524
+ const m = /^\s*(-?\d+)\s*(?:[,\s]\s*(\d+))?\s*$/.exec(text);
525
+ if (!m) {
526
+ this.fail("Invalid line or column number");
527
+ return;
528
+ }
529
+ const total = lineNo(this.value, this.value.length) + 1;
530
+ let l = parseInt(m[1], 10);
531
+ if (l < 0)
532
+ l = total + l + 1;
533
+ const s = lineAt(this.value, Math.max(0, Math.min(l, total) - 1));
534
+ const c = m[2] !== undefined ? parseInt(m[2], 10) : 1;
535
+ this.off = s + Math.max(0, Math.min(c - 1, lineEnd(this.value, s) - s));
536
+ });
537
+ break;
538
+ /* ---- information ---- */
539
+ case "location": {
540
+ const l = lineNo(v, o);
541
+ const total = lineNo(v, v.length) + 1;
542
+ const s = lineStart(v, o);
543
+ const chars = (a, b) => [...v.slice(a, b)].length;
544
+ const col = chars(s, o);
545
+ const len = chars(s, lineEnd(v, o));
546
+ const ch = chars(0, o);
547
+ const all = chars(0, v.length);
548
+ const pct = (a, b) => Math.round(100 * a / Math.max(1, b));
549
+ this.say(`line ${l + 1}/${total} (${pct(l + 1, total)}%), col ${col + 1}/${len + 1} (${pct(col + 1, len + 1)}%), ` +
550
+ `char ${ch + 1}/${all + 1} (${pct(ch + 1, all + 1)}%)`);
551
+ break;
552
+ }
553
+ case "wordcount": {
554
+ const [s, e] = this.mark !== null ? this.region() : [0, v.length];
555
+ const text = v.slice(s, e);
556
+ const words = (text.match(/\S+/g) ?? []).length;
557
+ const lines = text === "" ? 0 : text.split("\n").length - (text.endsWith("\n") ? 1 : 0);
558
+ this.say(`${this.mark !== null ? "In Selection: " : ""}Words: ${words} Lines: ${lines} Chars: ${[...text].length}`);
559
+ break;
560
+ }
561
+ case "verbatim":
562
+ this.verbatim = true;
563
+ break;
564
+ }
565
+ }
566
+ /* ==== HELPERS ==== */
567
+ /* the start of the next word */
568
+ nextWord(o) {
569
+ const v = this.value;
570
+ let i = o;
571
+ while (i < v.length && isWord(v[i]))
572
+ i++;
573
+ while (i < v.length && !isWord(v[i]))
574
+ i++;
575
+ return i;
576
+ }
577
+ /* move by rows, keeping the goal column of the first move of a sequence */
578
+ rows(n) {
579
+ if (!["prevline", "nextline", "prevpage", "nextpage"].includes(this.lastCmd))
580
+ this.goal = goalColumn(this.ops, this.value, this.off);
581
+ for (let i = 0; i < Math.abs(n); i++) {
582
+ const t = rowMove(this.ops, this.value, this.off, n < 0 ? -1 : 1, this.goal);
583
+ if (t === this.off)
584
+ break;
585
+ this.off = t;
586
+ }
587
+ }
588
+ /* find the bracket matching the one at the cursor */
589
+ findBracket() {
590
+ const v = this.value;
591
+ const b = BRACKETS[v[this.off] ?? ""];
592
+ if (b === undefined) {
593
+ this.fail("Not a bracket");
594
+ return;
595
+ }
596
+ const [open, close, dir] = b;
597
+ let depth = 0;
598
+ for (let i = this.off; i >= 0 && i < v.length; i += dir) {
599
+ if (v[i] === open)
600
+ depth += dir;
601
+ else if (v[i] === close)
602
+ depth -= dir;
603
+ if (depth === 0) {
604
+ this.off = i;
605
+ return;
606
+ }
607
+ }
608
+ this.fail("No matching bracket");
609
+ }
610
+ /* the marked region */
611
+ region() {
612
+ const m = this.mark ?? this.off;
613
+ return m < this.off ? [m, this.off] : [this.off, m];
614
+ }
615
+ /* cut the marked region */
616
+ cutRegion() {
617
+ const [s, e] = this.region();
618
+ const text = this.value.slice(s, e);
619
+ this.replace(s, e, "");
620
+ this.off = s;
621
+ this.mark = null;
622
+ return text;
623
+ }
624
+ /* the lines of the marked region resp. of the cursor */
625
+ lines() {
626
+ const v = this.value;
627
+ const [s, e] = this.mark !== null ? this.region() : [this.off, this.off];
628
+ const last = e > s && e === lineStart(v, e) ? lineNo(v, e) - 1 : lineNo(v, e);
629
+ const ls = [];
630
+ for (let l = lineNo(v, s); l <= last; l++)
631
+ ls.push(l);
632
+ return ls;
633
+ }
634
+ /* indent resp. unindent lines by a tab (unindenting also by up to 8 spaces) */
635
+ indent(indent) {
636
+ for (const l of this.lines().reverse()) {
637
+ const s = lineAt(this.value, l);
638
+ if (indent) {
639
+ if (lineEnd(this.value, s) > s)
640
+ this.replace(s, s, "\t", true);
641
+ }
642
+ else {
643
+ const m = /^(\t| {1,8})/.exec(this.value.slice(s, lineEnd(this.value, s)));
644
+ if (m)
645
+ this.replace(s, s + m[0].length, "", true);
646
+ }
647
+ }
648
+ }
649
+ /* comment resp. uncomment lines with "#" */
650
+ comment() {
651
+ const marked = this.lines();
652
+ /* blank lines are left alone, unless only blank lines are given */
653
+ const filled = marked.filter((l) => !isBlank(this.value, lineAt(this.value, l)));
654
+ const lines = filled.length > 0 ? filled : marked;
655
+ const all = lines.every((l) => this.value[lineAt(this.value, l)] === "#");
656
+ for (const l of lines.reverse()) {
657
+ const s = lineAt(this.value, l);
658
+ if (all)
659
+ this.replace(s, s + 1, "", true);
660
+ else
661
+ this.replace(s, s, "#", true);
662
+ }
663
+ }
664
+ /* record the text for undoing, once per key and amalgamating typed characters */
665
+ record() {
666
+ if (this.recorded)
667
+ return;
668
+ this.recorded = true;
669
+ this.redos = [];
670
+ if (this.cmd === "insertchar" && this.lastCmd === "insertchar" && this.typing)
671
+ return;
672
+ this.typing = this.cmd === "insertchar";
673
+ this.undos.push({ value: this.value, off: this.off, what: CHANGES[this.cmd] ?? "change" });
674
+ if (this.undos.length > 2000)
675
+ this.undos.shift();
676
+ }
677
+ /* undo resp. redo a change */
678
+ undo(undo) {
679
+ const from = undo ? this.undos : this.redos;
680
+ const to = undo ? this.redos : this.undos;
681
+ const snap = from.pop();
682
+ if (snap === undefined) {
683
+ this.fail(undo ? "Nothing to undo" : "Nothing to redo");
684
+ return;
685
+ }
686
+ to.push({ value: this.value, off: this.off, what: snap.what });
687
+ this.value = snap.value;
688
+ this.off = Math.min(snap.off, snap.value.length);
689
+ this.mark = null;
690
+ this.typing = false;
691
+ this.emit(this.value);
692
+ this.say(`${undo ? "Undid" : "Redid"} ${snap.what}`);
693
+ }
694
+ /* replace a range of the text, keeping the mark (and optionally the cursor) on the surrounding text */
695
+ replace(s, e, text, moveCursor = false) {
696
+ if (s === e && text === "")
697
+ return;
698
+ this.record();
699
+ const d = text.length - (e - s);
700
+ const adjust = (p) => p > e || (p === e && e > s) ? p + d : p > s ? s : p;
701
+ this.value = this.value.slice(0, s) + text + this.value.slice(e);
702
+ if (this.mark !== null)
703
+ this.mark = adjust(this.mark);
704
+ if (moveCursor)
705
+ this.off = s === e && this.off === s ? this.off + d : adjust(this.off);
706
+ this.emit(this.value);
707
+ }
708
+ /* insert a text at the cursor */
709
+ insert(text) {
710
+ if (text === "")
711
+ return;
712
+ this.replace(this.off, this.off, text);
713
+ this.off += text.length;
714
+ }
715
+ /* ==== SEARCHING AND REPLACING ==== */
716
+ /* search for the last search text, forward from after the cursor resp. backward from before it */
717
+ search(forward) {
718
+ const v = this.value;
719
+ const text = this.lastSearch;
720
+ const r = forward ? findNext(v, text, this.ops.next(v, this.off), true) : findPrevious(v, text, this.off, true);
721
+ if (r === null) {
722
+ this.fail(`"${text}" not found`);
723
+ return;
724
+ }
725
+ if (r.match[0] === this.off)
726
+ this.say("This is the only occurrence");
727
+ else if (r.wrapped)
728
+ this.say("Search Wrapped");
729
+ this.off = r.match[0];
730
+ this.found = r.match;
731
+ }
732
+ /* start replacing from the cursor, wrapping around up to it */
733
+ replaceStart(from, to) {
734
+ this.rep = { from, to, pos: this.off, stop: this.off, wrapped: false, match: [this.off, this.off], count: 0 };
735
+ this.replaceNext();
736
+ }
737
+ /* find the next match to replace, or end the replacing */
738
+ replaceNext() {
739
+ const q = this.rep;
740
+ if (q === null)
741
+ return;
742
+ const find = (from) => {
743
+ const re = literalRegExp(q.from, true);
744
+ re.lastIndex = from;
745
+ const m = re.exec(this.value);
746
+ return m === null || (q.wrapped && m.index + m[0].length > q.stop) ? null : m;
747
+ };
748
+ let m = find(q.pos);
749
+ if (m === null && !q.wrapped) {
750
+ q.wrapped = true;
751
+ m = find(0);
752
+ }
753
+ if (m === null) {
754
+ this.rep = null;
755
+ this.say(`Replaced ${plural(q.count, "occurrence")}`);
756
+ return;
757
+ }
758
+ q.match = [m.index, m.index + m[0].length];
759
+ this.off = m.index;
760
+ }
761
+ /* replace the current match */
762
+ replaceOne() {
763
+ const q = this.rep;
764
+ if (q === null)
765
+ return;
766
+ const [s, e] = q.match;
767
+ this.cmd = "replace";
768
+ this.replace(s, e, q.to);
769
+ this.cmd = "";
770
+ q.pos = s + q.to.length;
771
+ if (q.wrapped)
772
+ q.stop += q.to.length - (e - s);
773
+ q.count++;
774
+ this.off = q.pos;
775
+ }
776
+ /* handle a key of the replace question */
777
+ replaceKey(t) {
778
+ const q = this.rep;
779
+ if (q === null)
780
+ return;
781
+ if (t === "y" || t === "Y") {
782
+ this.replaceOne();
783
+ this.replaceNext();
784
+ }
785
+ else if (t === "n" || t === "N") {
786
+ q.pos = q.match[1];
787
+ this.replaceNext();
788
+ }
789
+ else if (t === "a" || t === "A") {
790
+ while (this.rep !== null) {
791
+ this.replaceOne();
792
+ this.replaceNext();
793
+ }
794
+ }
795
+ else if (t === "^C" || t === "Cancel") {
796
+ this.rep = null;
797
+ this.say(`Replaced ${plural(q.count, "occurrence")}`);
798
+ }
799
+ }
800
+ /* ==== PROMPTS ==== */
801
+ /* read a text on the status bar */
802
+ read(prompt, init, done) {
803
+ this.input = { prompt, text: init, done };
804
+ }
805
+ /* ask a yes/no question */
806
+ ask(question, yes, no) {
807
+ this.question = { prompt: `${question} (Y/N/^C) `, take: (t) => {
808
+ if (t === "y" || t === "Y")
809
+ yes();
810
+ else if (t === "n" || t === "N")
811
+ no();
812
+ else if (t === "^C" || t === "Cancel")
813
+ this.fail("Cancelled");
814
+ else
815
+ this.ask(question, yes, no);
816
+ } };
817
+ }
818
+ /* handle a key of the text prompt */
819
+ inputKey(t) {
820
+ const p = this.input;
821
+ if (p === null)
822
+ return;
823
+ if (isChar(t))
824
+ p.text += t;
825
+ else if (t === "Bsp")
826
+ p.text = p.text.slice(0, this.ops.previous(p.text, p.text.length));
827
+ else if (t === "^C" || t === "Cancel") {
828
+ this.input = null;
829
+ this.fail("Cancelled");
830
+ }
831
+ else if (t === "Enter") {
832
+ this.input = null;
833
+ p.done(p.text);
834
+ }
835
+ }
836
+ /* ==== FILES ==== */
837
+ /* the file operations, or an error without them */
838
+ need() {
839
+ if (this.files === null)
840
+ this.fail("No file operations available");
841
+ return this.files;
842
+ }
843
+ /* show the outcome of a file operation */
844
+ outcome(res) {
845
+ if (res.error)
846
+ this.fail(res.message);
847
+ else
848
+ this.say(res.message);
849
+ }
850
+ /* write the text to a file read on the status bar, asking before overwriting another one,
851
+ and optionally quit afterwards */
852
+ writeOut(quit) {
853
+ const f = this.need();
854
+ if (f === null)
855
+ return;
856
+ this.read("File Name to Write: ", f.name(), (file) => {
857
+ if (file === "") {
858
+ this.fail("Cancelled");
859
+ return;
860
+ }
861
+ const done = (res) => {
862
+ this.outcome(res);
863
+ if (!res.error && quit)
864
+ f.quit();
865
+ };
866
+ const res = f.write(file, false, file !== f.name());
867
+ if (res.exists)
868
+ this.ask(`File "${file}" exists; OVERWRITE?`, () => done(f.write(file, true, true)), () => this.fail("Cancelled"));
869
+ else
870
+ done(res);
871
+ });
872
+ }
873
+ /* ==== MESSAGES ==== */
874
+ /* show an informational message */
875
+ say(text) {
876
+ this.message = text;
877
+ this.error = false;
878
+ }
879
+ /* show an error message */
880
+ fail(text) {
881
+ this.message = text;
882
+ this.error = true;
883
+ }
884
+ }