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