@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,850 @@
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
+ /* VS Code-style 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, isIdent, isSpace, wordEnd, wordBegin, escapeRegExp, literalRegExp, findNext, findPrevious, goalColumn, rowMove } from "./ink-editor-text";
28
+ /* the key bindings, from keys to command names (the "shift+" variants of the cursor commands select) */
29
+ const BINDINGS = new Map(Object.entries({
30
+ "ctrl+s": "save",
31
+ "ctrl+q": "quit",
32
+ "ctrl+w": "quit",
33
+ "ctrl+z": "undo",
34
+ "ctrl+y": "redo",
35
+ "ctrl+shift+z": "redo",
36
+ "ctrl+x": "cut",
37
+ "ctrl+c": "copy",
38
+ "ctrl+v": "paste",
39
+ "ctrl+a": "selectAll",
40
+ "ctrl+f": "find",
41
+ "ctrl+h": "replace",
42
+ "ctrl+r": "replace",
43
+ "ctrl+g": "gotoLine",
44
+ "ctrl+d": "selectNextMatch",
45
+ "ctrl+l": "selectLine",
46
+ "ctrl+shift+k": "deleteLines",
47
+ "ctrl+enter": "insertLineAfter",
48
+ "ctrl+shift+enter": "insertLineBefore",
49
+ "alt+up": "moveLinesUp",
50
+ "alt+down": "moveLinesDown",
51
+ "shift+alt+up": "copyLinesUp",
52
+ "shift+alt+down": "copyLinesDown",
53
+ "ctrl+/": "commentLine",
54
+ "ctrl+_": "commentLine",
55
+ "ctrl+]": "indentLines",
56
+ "tab": "tab",
57
+ "shift+tab": "outdentLines",
58
+ "escape": "cancelSelection",
59
+ "enter": "newline",
60
+ "backspace": "deleteLeft",
61
+ "delete": "deleteRight",
62
+ "ctrl+backspace": "deleteWordLeft",
63
+ "alt+backspace": "deleteWordLeft",
64
+ "ctrl+delete": "deleteWordRight",
65
+ "alt+delete": "deleteWordRight",
66
+ "left": "cursorLeft",
67
+ "right": "cursorRight",
68
+ "up": "cursorUp",
69
+ "down": "cursorDown",
70
+ "home": "cursorHome",
71
+ "end": "cursorEnd",
72
+ "pageup": "cursorPageUp",
73
+ "pagedown": "cursorPageDown",
74
+ "ctrl+home": "cursorTop",
75
+ "ctrl+end": "cursorBottom",
76
+ "ctrl+left": "cursorWordLeft",
77
+ "alt+left": "cursorWordLeft",
78
+ "ctrl+right": "cursorWordRight",
79
+ "alt+right": "cursorWordRight"
80
+ }));
81
+ /* the line comment prefixes, by file extension (default: "#") */
82
+ const COMMENTS = Object.fromEntries([
83
+ ...["js", "mjs", "cjs", "jsx", "ts", "mts", "cts", "tsx", "c", "h", "cc", "cpp", "hpp", "cxx", "java",
84
+ "cs", "go", "rs", "swift", "kt", "kts", "scala", "php", "dart", "json5", "jsonc", "groovy", "vue"]
85
+ .map((ext) => [ext, "//"]),
86
+ ...["sql", "lua", "hs", "elm", "ada"].map((ext) => [ext, "--"]),
87
+ ...["tex", "sty", "erl", "m"].map((ext) => [ext, "%"]),
88
+ ...["ini", "lisp", "el", "clj", "scm", "asm"].map((ext) => [ext, ";"]),
89
+ ...["vim"].map((ext) => [ext, "\""])
90
+ ]);
91
+ /* whether a key token is a printable character, and the plural of a count */
92
+ const isChar = (t) => [...t].length === 1 && t >= " ";
93
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
94
+ /* the VS Code-style editing engine, operating on a plain string value, a cursor offset,
95
+ and the anchor of the selection */
96
+ export class Code {
97
+ constructor(value, ops) {
98
+ /* bindings to the outside */
99
+ this.emit = () => { };
100
+ this.clip = () => { };
101
+ this.files = null;
102
+ this.height = 24;
103
+ this.off = 0;
104
+ this.anchor = null;
105
+ this.message = "";
106
+ this.error = false;
107
+ this.cmd = "";
108
+ this.lastCmd = "";
109
+ this.recorded = false;
110
+ this.undos = [];
111
+ this.redos = [];
112
+ this.clipboard = "";
113
+ this.clipLine = false;
114
+ this.goal = null;
115
+ this.input = null;
116
+ this.question = null;
117
+ this.rep = null;
118
+ this.searching = "";
119
+ this.lastSearch = "";
120
+ this.value = value;
121
+ this.seen = value;
122
+ this.ops = ops;
123
+ }
124
+ /* ==== EXTERNAL INTERFACE ==== */
125
+ /* take over an externally changed value */
126
+ sync(value) {
127
+ if (value === this.seen)
128
+ return;
129
+ this.seen = value;
130
+ if (value === this.value)
131
+ return;
132
+ this.value = value;
133
+ this.off = Math.min(this.off, value.length);
134
+ this.anchor = null;
135
+ }
136
+ /* handle the key tokens of a key press (like [ "x" ], [ "ctrl+s" ], or [ "shift+left" ]) */
137
+ keys(tokens) {
138
+ for (const t of tokens)
139
+ this.dispatch(t);
140
+ return true;
141
+ }
142
+ /* handle a bracketed paste */
143
+ paste(text) {
144
+ if (this.input !== null) {
145
+ this.input.text += text.replace(/\r?\n/g, " ");
146
+ this.input.change?.(this.input.text);
147
+ }
148
+ else if (this.question === null && this.rep === null) {
149
+ this.recorded = false;
150
+ this.type(text);
151
+ this.lastCmd = "paste";
152
+ }
153
+ }
154
+ /* take over a text change of the front end */
155
+ onText(value) {
156
+ this.recorded = false;
157
+ this.record();
158
+ this.value = value;
159
+ this.off = Math.min(this.off, value.length);
160
+ this.anchor = null;
161
+ this.emit(value);
162
+ }
163
+ /* take over a cursor change of the front end (a mouse click) */
164
+ onCursor(cursor) {
165
+ if (this.prompt() === null) {
166
+ this.off = toOffset(this.value, cursor);
167
+ this.lastCmd = "";
168
+ }
169
+ }
170
+ /* take over a mouse selection */
171
+ onSelect(sel) {
172
+ if (this.prompt() !== null)
173
+ return false;
174
+ this.lastCmd = "";
175
+ if (!sel || sel[0] === sel[1]) {
176
+ if (this.anchor === null)
177
+ return false;
178
+ this.anchor = null;
179
+ return true;
180
+ }
181
+ this.anchor = sel[0];
182
+ this.off = sel[1];
183
+ return true;
184
+ }
185
+ /* the selection to be drawn */
186
+ selection() {
187
+ if (this.rep !== null)
188
+ return this.rep.match;
189
+ return this.range();
190
+ }
191
+ /* the prompt of the status line (with its input), or null without one */
192
+ prompt() {
193
+ if (this.question !== null)
194
+ return this.question.prompt;
195
+ if (this.input !== null)
196
+ return this.input.prompt() + this.input.text;
197
+ if (this.rep !== null)
198
+ return "Replace? (y)es (n)o (a)ll (esc) ";
199
+ return null;
200
+ }
201
+ /* the text being searched resp. replaced, to be highlighted */
202
+ searched() {
203
+ if (this.rep !== null)
204
+ return this.rep.from;
205
+ return this.searching !== "" ? this.searching : null;
206
+ }
207
+ /* ==== KEY DISPATCHING ==== */
208
+ /* dispatch a key token by the current input state */
209
+ dispatch(t) {
210
+ this.recorded = false;
211
+ if (this.question !== null) {
212
+ const q = this.question;
213
+ this.question = null;
214
+ q.take(t);
215
+ }
216
+ else if (this.input !== null)
217
+ this.inputKey(t);
218
+ else if (this.rep !== null)
219
+ this.replaceKey(t);
220
+ else
221
+ this.bufferKey(t);
222
+ }
223
+ /* handle a key of the buffer */
224
+ bufferKey(t) {
225
+ this.message = "";
226
+ this.error = false;
227
+ let cmd = BINDINGS.get(t);
228
+ let select = false;
229
+ if (cmd === undefined && t.includes("shift+")) {
230
+ const base = BINDINGS.get(t.replace("shift+", ""));
231
+ if (base !== undefined && base.startsWith("cursor")) {
232
+ cmd = base;
233
+ select = true;
234
+ }
235
+ }
236
+ if (cmd === undefined && isChar(t))
237
+ cmd = "type";
238
+ if (cmd === undefined) {
239
+ this.lastCmd = "";
240
+ return;
241
+ }
242
+ this.cmd = cmd;
243
+ this.exec(cmd, t, select);
244
+ this.cmd = "";
245
+ this.lastCmd = cmd;
246
+ }
247
+ /* ==== COMMANDS ==== */
248
+ /* execute a command with its key and whether it extends the selection */
249
+ exec(cmd, t, select) {
250
+ const v = this.value;
251
+ const o = this.off;
252
+ const r = this.range();
253
+ switch (cmd) {
254
+ /* ---- typing and deleting ---- */
255
+ case "type":
256
+ this.type(t);
257
+ break;
258
+ case "newline": {
259
+ const s = r ? r[0] : o;
260
+ const indent = /^[ \t]*/.exec(v.slice(lineStart(v, s), s))?.[0] ?? "";
261
+ this.type("\n" + indent);
262
+ break;
263
+ }
264
+ case "tab":
265
+ if (r !== null && lineNo(v, r[0]) !== lineNo(v, r[1]))
266
+ this.indent(true);
267
+ else {
268
+ const unit = this.indentUnit();
269
+ const col = (r ? r[0] : o) - lineStart(v, r ? r[0] : o);
270
+ this.type(unit === "\t" ? "\t" : " ".repeat(unit.length - col % unit.length));
271
+ }
272
+ break;
273
+ case "indentLines":
274
+ case "outdentLines":
275
+ this.indent(cmd === "indentLines");
276
+ break;
277
+ case "deleteLeft":
278
+ case "deleteRight":
279
+ case "deleteWordLeft":
280
+ case "deleteWordRight": {
281
+ if (r !== null) {
282
+ this.cut(r[0], r[1]);
283
+ break;
284
+ }
285
+ const p = cmd === "deleteLeft" ? this.ops.previous(v, o)
286
+ : cmd === "deleteRight" ? this.ops.next(v, o)
287
+ : cmd === "deleteWordLeft" ? wordBegin(v, o, isIdent)
288
+ : wordEnd(v, o, isIdent);
289
+ this.cut(Math.min(o, p), Math.max(o, p));
290
+ break;
291
+ }
292
+ /* ---- the clipboard ---- */
293
+ case "cut":
294
+ case "copy": {
295
+ const [s, e] = r ?? this.lineRange(o);
296
+ const text = r ? v.slice(s, e) : this.lineText(o);
297
+ this.clipboard = text;
298
+ this.clipLine = r === null;
299
+ this.clip(text);
300
+ /* a line cut of the last line removes its preceding newline (like deleteLines) */
301
+ if (cmd === "cut")
302
+ this.cut(r === null && e === v.length && s > 0 ? s - 1 : s, e);
303
+ break;
304
+ }
305
+ case "paste":
306
+ if (this.clipboard === "")
307
+ break;
308
+ if (this.clipLine && r === null) {
309
+ const s = lineStart(v, o);
310
+ this.replace(s, s, this.clipboard);
311
+ this.off = o + this.clipboard.length;
312
+ }
313
+ else
314
+ this.type(this.clipboard);
315
+ break;
316
+ /* ---- undoing ---- */
317
+ case "undo":
318
+ case "redo":
319
+ this.undo(cmd === "undo");
320
+ break;
321
+ /* ---- selecting ---- */
322
+ case "selectAll":
323
+ this.anchor = 0;
324
+ this.off = v.length;
325
+ break;
326
+ case "cancelSelection":
327
+ this.anchor = null;
328
+ break;
329
+ case "selectLine": {
330
+ if (r === null)
331
+ this.anchor = lineStart(v, o);
332
+ const e = lineEnd(v, o);
333
+ this.off = e < v.length ? e + 1 : e;
334
+ break;
335
+ }
336
+ case "selectNextMatch": {
337
+ if (r === null) {
338
+ let s = o;
339
+ let e = o;
340
+ while (s > 0 && isIdent(v[s - 1]))
341
+ s--;
342
+ while (e < v.length && isIdent(v[e]))
343
+ e++;
344
+ if (e > s) {
345
+ this.anchor = s;
346
+ this.off = e;
347
+ }
348
+ break;
349
+ }
350
+ const m = findNext(v, v.slice(r[0], r[1]), r[1], false);
351
+ if (m !== null) {
352
+ this.anchor = m.match[0];
353
+ this.off = m.match[1];
354
+ }
355
+ break;
356
+ }
357
+ /* ---- lines ---- */
358
+ case "deleteLines": {
359
+ const [first, last] = this.lines();
360
+ const s = lineAt(v, first);
361
+ const e = lineEnd(v, lineAt(v, last));
362
+ if (e < v.length)
363
+ this.cut(s, e + 1);
364
+ else
365
+ this.cut(s > 0 ? s - 1 : s, e);
366
+ this.off = lineStart(this.value, Math.min(s, this.value.length));
367
+ break;
368
+ }
369
+ case "insertLineAfter":
370
+ case "insertLineBefore": {
371
+ const s = lineStart(v, o);
372
+ const indent = /^[ \t]*/.exec(v.slice(s, lineEnd(v, o)))?.[0] ?? "";
373
+ this.anchor = null;
374
+ if (cmd === "insertLineAfter") {
375
+ const e = lineEnd(v, o);
376
+ this.replace(e, e, "\n" + indent);
377
+ this.off = e + 1 + indent.length;
378
+ }
379
+ else {
380
+ this.replace(s, s, indent + "\n");
381
+ this.off = s + indent.length;
382
+ }
383
+ break;
384
+ }
385
+ case "moveLinesUp":
386
+ case "moveLinesDown":
387
+ case "copyLinesUp":
388
+ case "copyLinesDown":
389
+ this.moveLines(cmd);
390
+ break;
391
+ case "commentLine":
392
+ this.comment();
393
+ break;
394
+ /* ---- moving ---- */
395
+ case "cursorLeft":
396
+ case "cursorRight":
397
+ if (r !== null && !select)
398
+ this.moveTo(cmd === "cursorLeft" ? r[0] : r[1], false);
399
+ else
400
+ this.moveTo(cmd === "cursorLeft" ? this.ops.previous(v, o) : this.ops.next(v, o), select);
401
+ break;
402
+ case "cursorUp":
403
+ case "cursorDown":
404
+ case "cursorPageUp":
405
+ case "cursorPageDown": {
406
+ if (!["cursorUp", "cursorDown", "cursorPageUp", "cursorPageDown"].includes(this.lastCmd))
407
+ this.goal = goalColumn(this.ops, v, o);
408
+ const dir = cmd === "cursorUp" || cmd === "cursorPageUp" ? -1 : 1;
409
+ const rows = cmd.includes("Page") ? Math.max(1, this.height - 2) : 1;
410
+ let p = o;
411
+ for (let i = 0; i < rows; i++)
412
+ p = rowMove(this.ops, v, p, dir, this.goal);
413
+ this.moveTo(p, select);
414
+ break;
415
+ }
416
+ case "cursorHome": {
417
+ const s = lineStart(v, o);
418
+ let p = s;
419
+ while (p < lineEnd(v, o) && isSpace(v[p]))
420
+ p++;
421
+ this.moveTo(o === p ? s : p, select);
422
+ break;
423
+ }
424
+ case "cursorEnd":
425
+ this.moveTo(lineEnd(v, o), select);
426
+ break;
427
+ case "cursorTop":
428
+ this.moveTo(0, select);
429
+ break;
430
+ case "cursorBottom":
431
+ this.moveTo(v.length, select);
432
+ break;
433
+ case "cursorWordLeft":
434
+ this.moveTo(wordBegin(v, o, isIdent), select);
435
+ break;
436
+ case "cursorWordRight":
437
+ this.moveTo(wordEnd(v, o, isIdent), select);
438
+ break;
439
+ /* ---- finding and replacing ---- */
440
+ case "find":
441
+ this.find();
442
+ break;
443
+ case "replace":
444
+ this.replaceStart();
445
+ break;
446
+ case "gotoLine":
447
+ this.read(() => "Go to line: ", "", (text) => {
448
+ const m = /^\s*(\d+)\s*(?::\s*(\d+))?\s*$/.exec(text);
449
+ if (!m)
450
+ return;
451
+ const s = lineAt(this.value, Math.max(0, parseInt(m[1], 10) - 1));
452
+ const c = m[2] !== undefined ? parseInt(m[2], 10) - 1 : 0;
453
+ this.moveTo(s + Math.max(0, Math.min(c, lineEnd(this.value, s) - s)), false);
454
+ });
455
+ break;
456
+ /* ---- files and quitting ---- */
457
+ case "save":
458
+ this.save(() => { });
459
+ break;
460
+ case "quit": {
461
+ const f = this.need();
462
+ if (f === null)
463
+ break;
464
+ if (!f.modified()) {
465
+ f.quit();
466
+ break;
467
+ }
468
+ this.ask("Save changes before closing? (y)es (n)o (esc) ", () => this.save(() => f.quit()), () => f.quit());
469
+ break;
470
+ }
471
+ }
472
+ }
473
+ /* ==== HELPERS ==== */
474
+ /* the ordered selection, or null without one */
475
+ range() {
476
+ if (this.anchor === null || this.anchor === this.off)
477
+ return null;
478
+ return this.anchor < this.off ? [this.anchor, this.off] : [this.off, this.anchor];
479
+ }
480
+ /* move the cursor, extending resp. dropping the selection */
481
+ moveTo(p, select) {
482
+ if (select && this.anchor === null)
483
+ this.anchor = this.off;
484
+ else if (!select)
485
+ this.anchor = null;
486
+ this.off = p;
487
+ }
488
+ /* the range of the line of an offset with its newline, and its text with a newline */
489
+ lineRange(o) {
490
+ const e = lineEnd(this.value, o);
491
+ return [lineStart(this.value, o), e < this.value.length ? e + 1 : e];
492
+ }
493
+ lineText(o) {
494
+ return this.value.slice(lineStart(this.value, o), lineEnd(this.value, o)) + "\n";
495
+ }
496
+ /* the first and last line of the selection resp. of the cursor
497
+ (a selection ending at a line start excludes that line) */
498
+ lines() {
499
+ const v = this.value;
500
+ const [s, e] = this.range() ?? [this.off, this.off];
501
+ const last = e > s && e === lineStart(v, e) ? lineNo(v, e) - 1 : lineNo(v, e);
502
+ return [lineNo(v, s), last];
503
+ }
504
+ /* the unit of indentation: a tab if more lines are indented by tabs than by spaces, else 4 spaces */
505
+ indentUnit() {
506
+ const tabs = (this.value.match(/^\t/gm) ?? []).length;
507
+ const spaces = (this.value.match(/^ {2}/gm) ?? []).length;
508
+ return tabs > spaces ? "\t" : " ";
509
+ }
510
+ /* type a text, replacing the selection */
511
+ type(text) {
512
+ const r = this.range();
513
+ const [s, e] = r ?? [this.off, this.off];
514
+ this.replace(s, e, text);
515
+ this.off = s + text.length;
516
+ this.anchor = null;
517
+ }
518
+ /* delete a range of the text */
519
+ cut(s, e) {
520
+ this.replace(s, e, "");
521
+ this.off = s;
522
+ this.anchor = null;
523
+ }
524
+ /* replace a range of the text, keeping the selection on the surrounding text */
525
+ replace(s, e, text) {
526
+ if (s === e && text === "")
527
+ return;
528
+ this.record();
529
+ const d = text.length - (e - s);
530
+ const adjust = (p) => p > e || (p === e && e > s) ? p + d : p > s ? s : p;
531
+ this.value = this.value.slice(0, s) + text + this.value.slice(e);
532
+ if (this.anchor !== null)
533
+ this.anchor = adjust(this.anchor);
534
+ this.emit(this.value);
535
+ }
536
+ /* replace lines from bottom to top, keeping the cursor and the selection on their characters */
537
+ eachLine(first, last, change) {
538
+ for (let l = last; l >= first; l--) {
539
+ const s = lineAt(this.value, l);
540
+ const e = lineEnd(this.value, s);
541
+ const line = this.value.slice(s, e);
542
+ const text = change(line);
543
+ if (text === line)
544
+ continue;
545
+ const d = text.length - line.length;
546
+ const adjust = (p) => p <= s ? p : p >= e ? p + d : Math.max(s, p + d);
547
+ const off = adjust(this.off);
548
+ const anchor = this.anchor !== null ? adjust(this.anchor) : null;
549
+ this.replace(s, e, text);
550
+ this.off = off;
551
+ this.anchor = anchor;
552
+ }
553
+ }
554
+ /* indent resp. outdent the lines of the selection resp. of the cursor */
555
+ indent(indent) {
556
+ const [first, last] = this.lines();
557
+ const unit = this.indentUnit();
558
+ const lead = new RegExp(`^(\\t| {1,${unit.length === 1 ? 4 : unit.length}})`);
559
+ this.eachLine(first, last, (line) => indent ? (line === "" ? line : unit + line) : line.replace(lead, ""));
560
+ }
561
+ /* toggle the line comments of the lines of the selection resp. of the cursor */
562
+ comment() {
563
+ const name = this.files?.name() ?? "";
564
+ const prefix = COMMENTS[/\.([^./]+)$/.exec(name)?.[1]?.toLowerCase() ?? ""] ?? "#";
565
+ const [first, last] = this.lines();
566
+ const lines = [];
567
+ for (let l = first; l <= last; l++)
568
+ lines.push(this.value.slice(lineAt(this.value, l), lineEnd(this.value, lineAt(this.value, l))));
569
+ const used = lines.filter((line) => !/^\s*$/.test(line));
570
+ if (used.length === 0)
571
+ return;
572
+ const commented = used.every((line) => line.trimStart().startsWith(prefix));
573
+ const column = Math.min(...used.map((line) => /^[ \t]*/.exec(line)?.[0].length ?? 0));
574
+ const re = new RegExp(`^([ \\t]*)${escapeRegExp(prefix)} ?`);
575
+ this.eachLine(first, last, (line) => /^\s*$/.test(line) ? line
576
+ : commented ? line.replace(re, "$1")
577
+ : line.slice(0, column) + prefix + " " + line.slice(column));
578
+ }
579
+ /* move resp. copy the lines of the selection resp. of the cursor up or down */
580
+ moveLines(cmd) {
581
+ const v = this.value;
582
+ const [first, last] = this.lines();
583
+ const bs = lineAt(v, first);
584
+ const be = lineEnd(v, lineAt(v, last));
585
+ const block = v.slice(bs, be);
586
+ const shift = (d) => {
587
+ this.off += d;
588
+ if (this.anchor !== null)
589
+ this.anchor += d;
590
+ };
591
+ const anchor = this.anchor;
592
+ if (cmd === "moveLinesUp" && first > 0) {
593
+ const as = lineAt(v, first - 1);
594
+ const above = v.slice(as, bs - 1);
595
+ this.replace(as, be, block + "\n" + above);
596
+ this.anchor = anchor;
597
+ shift(-(above.length + 1));
598
+ }
599
+ else if (cmd === "moveLinesDown" && be < v.length) {
600
+ const ne = lineEnd(v, be + 1);
601
+ const below = v.slice(be + 1, ne);
602
+ this.replace(bs, ne, below + "\n" + block);
603
+ this.anchor = anchor;
604
+ shift(below.length + 1);
605
+ }
606
+ else if (cmd === "copyLinesUp") {
607
+ this.replace(bs, bs, block + "\n");
608
+ this.anchor = anchor;
609
+ }
610
+ else if (cmd === "copyLinesDown") {
611
+ this.replace(be, be, "\n" + block);
612
+ this.anchor = anchor;
613
+ shift(block.length + 1);
614
+ }
615
+ }
616
+ /* record the text for undoing, once per key and amalgamating typed characters */
617
+ record() {
618
+ if (this.recorded)
619
+ return;
620
+ this.recorded = true;
621
+ this.redos = [];
622
+ if (this.cmd === "type" && this.lastCmd === "type")
623
+ return;
624
+ this.undos.push({ value: this.value, off: this.off, anchor: this.anchor });
625
+ if (this.undos.length > 2000)
626
+ this.undos.shift();
627
+ }
628
+ /* undo resp. redo a change */
629
+ undo(undo) {
630
+ const from = undo ? this.undos : this.redos;
631
+ const to = undo ? this.redos : this.undos;
632
+ const snap = from.pop();
633
+ if (snap === undefined)
634
+ return;
635
+ to.push({ value: this.value, off: this.off, anchor: this.anchor });
636
+ this.value = snap.value;
637
+ this.off = Math.min(snap.off, snap.value.length);
638
+ this.anchor = snap.anchor !== null ? Math.min(snap.anchor, snap.value.length) : null;
639
+ this.emit(this.value);
640
+ }
641
+ /* ==== FINDING AND REPLACING ==== */
642
+ /* the initial text of finding: the single-line selection, else the last searched text */
643
+ findInit() {
644
+ const r = this.range();
645
+ const sel = r ? this.value.slice(r[0], r[1]) : "";
646
+ return sel !== "" && !sel.includes("\n") ? sel : this.lastSearch;
647
+ }
648
+ /* the number of the current match and the number of all matches */
649
+ findCount(text) {
650
+ const all = [...this.value.matchAll(literalRegExp(text, true))];
651
+ if (all.length === 0)
652
+ return "No results";
653
+ const r = this.range();
654
+ const i = r ? all.findIndex((m) => m.index === r[0]) : -1;
655
+ return `${i >= 0 ? i + 1 : "?"} of ${all.length}`;
656
+ }
657
+ /* find a text incrementally, with Enter resp. Down for the next match, Up for the previous one,
658
+ and Escape closing the find */
659
+ find() {
660
+ const origin = this.range()?.[0] ?? this.off;
661
+ const select = (m) => {
662
+ if (m !== null) {
663
+ this.anchor = m.match[0];
664
+ this.off = m.match[1];
665
+ }
666
+ };
667
+ const init = this.findInit();
668
+ this.searching = init;
669
+ this.read(() => this.searching !== "" ? `Find (${this.findCount(this.searching)}): ` : "Find: ", init, () => { }, {
670
+ change: (text) => {
671
+ this.searching = text;
672
+ if (text !== "")
673
+ select(findNext(this.value, text, origin, true));
674
+ },
675
+ key: (t) => {
676
+ if (this.searching === "" || !["enter", "down", "up", "shift+enter"].includes(t))
677
+ return false;
678
+ const r = this.range() ?? [this.off, this.off];
679
+ select(t === "up" || t === "shift+enter"
680
+ ? findPrevious(this.value, this.searching, r[0], true)
681
+ : findNext(this.value, this.searching, r[1], true));
682
+ return true;
683
+ },
684
+ close: () => {
685
+ if (this.searching !== "")
686
+ this.lastSearch = this.searching;
687
+ this.searching = "";
688
+ }
689
+ });
690
+ if (init !== "")
691
+ select(findNext(this.value, init, origin, true));
692
+ }
693
+ /* replace a text, read with its replacement, match by match from the cursor, wrapping around up to it */
694
+ replaceStart() {
695
+ this.read(() => "Find: ", this.findInit(), (from) => {
696
+ if (from === "")
697
+ return;
698
+ this.lastSearch = from;
699
+ this.read(() => `Replace ${from} with: `, "", (to) => {
700
+ const start = this.range()?.[0] ?? this.off;
701
+ this.anchor = null;
702
+ this.rep = { from, to, pos: start, stop: start, wrapped: false, match: [start, start], count: 0 };
703
+ this.replaceNext();
704
+ });
705
+ });
706
+ }
707
+ /* find the next match to replace, or end the replacing */
708
+ replaceNext() {
709
+ const q = this.rep;
710
+ if (q === null)
711
+ return;
712
+ const find = (from) => {
713
+ const re = literalRegExp(q.from, true);
714
+ re.lastIndex = from;
715
+ const m = re.exec(this.value);
716
+ return m === null || (q.wrapped && m.index + m[0].length > q.stop) ? null : m;
717
+ };
718
+ let m = find(q.pos);
719
+ if (m === null && !q.wrapped) {
720
+ q.wrapped = true;
721
+ m = find(0);
722
+ }
723
+ if (m === null) {
724
+ this.rep = null;
725
+ this.say(`Replaced ${plural(q.count, "occurrence")}`);
726
+ return;
727
+ }
728
+ q.match = [m.index, m.index + m[0].length];
729
+ this.off = q.match[1];
730
+ }
731
+ /* handle a key of the replace question */
732
+ replaceKey(t) {
733
+ const q = this.rep;
734
+ if (q === null)
735
+ return;
736
+ const one = () => {
737
+ const [s, e] = q.match;
738
+ this.replace(s, e, q.to);
739
+ q.pos = s + q.to.length;
740
+ if (q.wrapped)
741
+ q.stop += q.to.length - (e - s);
742
+ q.count++;
743
+ this.off = q.pos;
744
+ };
745
+ if (t === "y" || t === "enter") {
746
+ one();
747
+ this.replaceNext();
748
+ }
749
+ else if (t === "n") {
750
+ q.pos = q.match[1];
751
+ this.replaceNext();
752
+ }
753
+ else if (t === "a") {
754
+ while (this.rep !== null) {
755
+ one();
756
+ this.replaceNext();
757
+ }
758
+ }
759
+ else if (t === "escape") {
760
+ this.rep = null;
761
+ this.say(`Replaced ${plural(q.count, "occurrence")}`);
762
+ }
763
+ }
764
+ /* ==== PROMPTS ==== */
765
+ /* read a text on the status line */
766
+ read(prompt, init, done, hooks = {}) {
767
+ this.input = { prompt, text: init, done, ...hooks };
768
+ }
769
+ /* ask a yes/no question (Escape cancels) */
770
+ ask(question, yes, no) {
771
+ this.question = { prompt: question, take: (t) => {
772
+ if (t === "y" || t === "Y")
773
+ yes();
774
+ else if (t === "n" || t === "N")
775
+ no();
776
+ else if (t !== "escape" && t !== "ctrl+c")
777
+ this.ask(question, yes, no);
778
+ } };
779
+ }
780
+ /* handle a key of the text input */
781
+ inputKey(t) {
782
+ const p = this.input;
783
+ if (p === null)
784
+ return;
785
+ if (p.key?.(t))
786
+ return;
787
+ if (isChar(t)) {
788
+ p.text += t;
789
+ p.change?.(p.text);
790
+ }
791
+ else if (t === "backspace") {
792
+ p.text = p.text.slice(0, this.ops.previous(p.text, p.text.length));
793
+ p.change?.(p.text);
794
+ }
795
+ else if (t === "escape" || t === "ctrl+c") {
796
+ this.input = null;
797
+ p.close?.();
798
+ }
799
+ else if (t === "enter") {
800
+ this.input = null;
801
+ p.close?.();
802
+ p.done(p.text);
803
+ }
804
+ }
805
+ /* ==== FILES ==== */
806
+ /* the file operations, or an error without them */
807
+ need() {
808
+ if (this.files === null)
809
+ this.fail("No file operations available");
810
+ return this.files;
811
+ }
812
+ /* save the text (asking for a file name without one), and continue after a successful save */
813
+ save(then) {
814
+ const f = this.need();
815
+ if (f === null)
816
+ return;
817
+ const done = (res) => {
818
+ if (res.error)
819
+ this.fail(res.message);
820
+ else {
821
+ this.say(res.message);
822
+ then();
823
+ }
824
+ };
825
+ if (f.name() !== "") {
826
+ done(f.write("", false, false));
827
+ return;
828
+ }
829
+ this.read(() => "Save as: ", "", (file) => {
830
+ if (file === "")
831
+ return;
832
+ const res = f.write(file, false, true);
833
+ if (res.exists)
834
+ this.ask(`File ${file} exists. Overwrite? (y)es (n)o `, () => done(f.write(file, true, true)), () => { });
835
+ else
836
+ done(res);
837
+ });
838
+ }
839
+ /* ==== MESSAGES ==== */
840
+ /* show an informational message */
841
+ say(text) {
842
+ this.message = text;
843
+ this.error = false;
844
+ }
845
+ /* show an error message */
846
+ fail(text) {
847
+ this.message = text;
848
+ this.error = true;
849
+ }
850
+ }