@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,1648 @@
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
+ /* Emacs 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, toCursor, toOffset,
30
+ isSpace, isBlank, wordEnd, wordBegin, paragraphEnd, paragraphBegin,
31
+ literalRegExp, goalColumn, rowMove, fillParagraph } from "./ink-editor-text"
32
+ import type { TextOps } from "./ink-editor-text"
33
+
34
+ /* the outcome of a file operation: a message, whether it is an error,
35
+ and whether forcing it would overwrite an existing other file */
36
+ export type EmacsOutcome = { message: string, error: boolean, exists?: boolean }
37
+
38
+ /* the file operations of the outside, used by the file commands */
39
+ export interface EmacsFiles {
40
+ /* the name of the visited file ("" for none), and whether the text is modified */
41
+ name (): string
42
+ modified (): boolean
43
+
44
+ /* write the text to a file ("" for the visited one), overwriting another existing file
45
+ only with "force", and with "rename" making the written file the visited one */
46
+ write (file: string, force: boolean, rename: boolean): EmacsOutcome
47
+
48
+ /* reload the text of the visited file, and quit the editor */
49
+ reload (): EmacsOutcome
50
+ quit (failed?: boolean): void
51
+ }
52
+
53
+ /* an undo snapshot, a pending prefix argument, a minibuffer input, and a single key input */
54
+ type Snap = { value: string, off: number }
55
+ type Prefix = { n: number, digits: string, neg: boolean, closed: boolean }
56
+ type Mini = { kind: string, prompt: string, text: string, done: (text: string) => void, names?: string[], hist: number }
57
+ type Reader = { prompt: string, take: (token: string) => void }
58
+
59
+ /* an incremental search, with the steps taken back by DEL */
60
+ type Step = { forward: boolean, text: string, failing: boolean, wrapped: boolean, match: [ number, number ] | null, off: number }
61
+ type Isearch = Step & { origin: number, stack: Step[] }
62
+
63
+ /* a query replace */
64
+ type Query = { from: string, to: string, pos: number, limit: number, match: [ number, number ], count: number }
65
+
66
+ /* the key bindings, from key sequences to command names */
67
+ const BINDINGS = new Map<string, string>(Object.entries({
68
+ /* motion */
69
+ "C-f": "forward-char",
70
+ "<right>": "forward-char",
71
+ "C-b": "backward-char",
72
+ "<left>": "backward-char",
73
+ "C-n": "next-line",
74
+ "<down>": "next-line",
75
+ "C-p": "previous-line",
76
+ "<up>": "previous-line",
77
+ "C-a": "move-beginning-of-line",
78
+ "<home>": "move-beginning-of-line",
79
+ "C-e": "move-end-of-line",
80
+ "<end>": "move-end-of-line",
81
+ "M-f": "forward-word",
82
+ "C-<right>": "forward-word",
83
+ "M-<right>": "forward-word",
84
+ "M-b": "backward-word",
85
+ "C-<left>": "backward-word",
86
+ "M-<left>": "backward-word",
87
+ "M-}": "forward-paragraph",
88
+ "C-<down>": "forward-paragraph",
89
+ "M-{": "backward-paragraph",
90
+ "C-<up>": "backward-paragraph",
91
+ "M-m": "back-to-indentation",
92
+ "M-<": "beginning-of-buffer",
93
+ "C-<home>": "beginning-of-buffer",
94
+ "M->": "end-of-buffer",
95
+ "C-<end>": "end-of-buffer",
96
+ "C-v": "scroll-up-command",
97
+ "<next>": "scroll-up-command",
98
+ "M-v": "scroll-down-command",
99
+ "<prior>": "scroll-down-command",
100
+ "C-l": "recenter-top-bottom",
101
+ "M-g g": "goto-line",
102
+ "M-g M-g": "goto-line",
103
+ "M-g c": "goto-char",
104
+
105
+ /* inserting, deleting, and changing */
106
+ "RET": "newline",
107
+ "C-j": "newline",
108
+ "C-o": "open-line",
109
+ "TAB": "indent-for-tab-command",
110
+ "M-i": "tab-to-tab-stop",
111
+ "C-q": "quoted-insert",
112
+ "C-d": "delete-char",
113
+ "<deletechar>": "delete-forward-char",
114
+ "DEL": "delete-backward-char",
115
+ "M-\\": "delete-horizontal-space",
116
+ "M-SPC": "just-one-space",
117
+ "M-^": "delete-indentation",
118
+ "C-x C-o": "delete-blank-lines",
119
+ "C-t": "transpose-chars",
120
+ "M-t": "transpose-words",
121
+ "C-x C-t": "transpose-lines",
122
+ "M-u": "upcase-word",
123
+ "M-l": "downcase-word",
124
+ "M-c": "capitalize-word",
125
+ "C-x C-u": "upcase-region",
126
+ "C-x C-l": "downcase-region",
127
+ "M-q": "fill-paragraph",
128
+
129
+ /* killing and yanking */
130
+ "C-k": "kill-line",
131
+ "M-d": "kill-word",
132
+ "M-DEL": "backward-kill-word",
133
+ "C-DEL": "backward-kill-word",
134
+ "C-w": "kill-region",
135
+ "M-w": "kill-ring-save",
136
+ "C-y": "yank",
137
+ "M-y": "yank-pop",
138
+ "M-z": "zap-to-char",
139
+
140
+ /* the mark and the region */
141
+ "C-SPC": "set-mark-command",
142
+ "C-@": "set-mark-command",
143
+ "C-x C-x": "exchange-point-and-mark",
144
+ "C-x h": "mark-whole-buffer",
145
+ "M-h": "mark-paragraph",
146
+ "M-@": "mark-word",
147
+
148
+ /* undoing, quitting, searching, replacing, and commands */
149
+ "C-/": "undo",
150
+ "C-_": "undo",
151
+ "C-x u": "undo",
152
+ "C-g": "keyboard-quit",
153
+ "C-s": "isearch-forward",
154
+ "C-r": "isearch-backward",
155
+ "M-%": "query-replace",
156
+ "M-x": "execute-extended-command",
157
+
158
+ /* files and quitting */
159
+ "C-x C-s": "save-buffer",
160
+ "C-x C-w": "write-file",
161
+ "C-x s": "save-some-buffers",
162
+ "C-x C-f": "find-file",
163
+ "C-x C-c": "save-buffers-kill-terminal",
164
+ "C-z": "suspend-frame",
165
+ "C-x C-z": "suspend-frame",
166
+
167
+ /* information */
168
+ "C-x =": "what-cursor-position",
169
+ "M-=": "count-words-region",
170
+
171
+ /* keyboard macros */
172
+ "C-x (": "kmacro-start-macro",
173
+ "C-x )": "kmacro-end-macro",
174
+ "C-x e": "kmacro-end-and-call-macro"
175
+ }))
176
+
177
+ /* the prefix keys of the key bindings */
178
+ const PREFIXES = new Set([ ...BINDINGS.keys() ].flatMap((seq) => {
179
+ const keys = seq.split(" ")
180
+ return keys.slice(0, -1).map((_, i) => keys.slice(0, i + 1).join(" "))
181
+ }))
182
+
183
+ /* the commands of "M-x" */
184
+ const COMMANDS = [ ...new Set([ ...BINDINGS.values(),
185
+ "replace-string", "replace-regexp", "revert-buffer", "kill-emacs", "count-words",
186
+ "what-line", "delete-trailing-whitespace", "keyboard-escape-quit"
187
+ ]) ].sort()
188
+
189
+ /* the commands whose kills are appended to by a directly following kill */
190
+ const KILLS = new Set([ "kill-line", "kill-word", "backward-kill-word", "kill-region", "zap-to-char" ])
191
+
192
+ /* the column of filling paragraphs */
193
+ const FILL_COLUMN = 70
194
+
195
+ /* the limit of numeric arguments, against runaway repetitions */
196
+ const MAX_ARG = 1000000
197
+
198
+ /* whether a key token is a printable character */
199
+ const isChar = (t: string) => [ ...t ].length === 1 && t >= " "
200
+
201
+ /* the longest common prefix of strings */
202
+ const commonPrefix = (list: string[]) =>
203
+ list.reduce((a, b) => { let i = 0; while (i < a.length && a[i] === b[i]) i++; return a.slice(0, i) })
204
+
205
+ /* a count with its word, in plural form unless the count is one */
206
+ const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? "" : "s"}`
207
+
208
+ /* the Emacs editing engine, operating on a plain string value and a point offset */
209
+ export class Emacs {
210
+ /* bindings to the outside */
211
+ emit: (value: string) => void = () => {}
212
+ clip: (text: string) => void = () => {}
213
+ files: EmacsFiles | null = null
214
+ ops: TextOps
215
+ height = 24
216
+
217
+ /* editing state */
218
+ value: string
219
+ off = 0
220
+ mark: number | null = null
221
+ active = false
222
+ message = ""
223
+ error = false
224
+
225
+ /* internal state */
226
+ private seen: string
227
+ private pend: string[] = []
228
+ private prefix: Prefix | null = null
229
+ private bare = false
230
+ private esc = false
231
+ private cmd = ""
232
+ private lastCmd = ""
233
+ private recorded = false
234
+ private amalgam = 0
235
+ private undos: Snap[] = []
236
+ private undoPtr = 0
237
+ private kills: string[] = []
238
+ private yankRange: [ number, number ] = [ 0, 0 ]
239
+ private yankIdx = 0
240
+ private markRing: number[] = []
241
+ private goal: number | null = null
242
+ private mini: Mini | null = null
243
+ private reader: Reader | null = null
244
+ private is: Isearch | null = null
245
+ private qr: Query | null = null
246
+ private lastSearch = ""
247
+ private lastReplace: [ string, string ] | null = null
248
+ private history = new Map<string, string[]>()
249
+ private macroRec: string[] | null = null
250
+ private macroStart = 0
251
+ private macro: string[] = []
252
+ private depth = 0
253
+
254
+ constructor (value: string, ops: TextOps) {
255
+ this.value = value
256
+ this.seen = value
257
+ this.ops = ops
258
+ }
259
+
260
+ /* ==== EXTERNAL INTERFACE ==== */
261
+
262
+ /* take over an externally changed value */
263
+ sync (value: string) {
264
+ if (value === this.seen)
265
+ return
266
+ this.seen = value
267
+ if (value === this.value)
268
+ return
269
+ this.value = value
270
+ this.off = Math.min(this.off, value.length)
271
+ if (this.mark !== null)
272
+ this.mark = Math.min(this.mark, value.length)
273
+ }
274
+
275
+ /* handle the key tokens of a key press (like [ "x" ], [ "C-x" ], [ "M-f" ], or [ "<up>" ]) */
276
+ keys (tokens: string[]): boolean {
277
+ for (const t of tokens) {
278
+ if (this.macroRec !== null)
279
+ this.macroRec.push(t)
280
+ this.dispatch(t)
281
+ }
282
+ return true
283
+ }
284
+
285
+ /* handle a bracketed paste */
286
+ paste (text: string) {
287
+ if (this.mini !== null)
288
+ this.mini.text += text.replace(/\r?\n/g, " ")
289
+ else if (this.is !== null)
290
+ for (const c of text.replace(/\r?\n/g, " "))
291
+ this.isearchKey(c)
292
+ else if (this.reader === null && this.qr === null) {
293
+ this.recorded = false
294
+ this.insert(text)
295
+ this.active = false
296
+ this.lastCmd = ""
297
+ }
298
+ }
299
+
300
+ /* take over a text change of the front end */
301
+ onText (value: string) {
302
+ this.recorded = false
303
+ this.record()
304
+ this.value = value
305
+ this.off = Math.min(this.off, value.length)
306
+ if (this.mark !== null)
307
+ this.mark = Math.min(this.mark, value.length)
308
+ this.emit(value)
309
+ }
310
+
311
+ /* take over a cursor change of the front end (a mouse click) */
312
+ onCursor (cursor: [ number, number ]) {
313
+ if (this.prompt() === null) {
314
+ this.off = toOffset(this.value, cursor)
315
+ this.lastCmd = ""
316
+ }
317
+ }
318
+
319
+ /* take over a mouse selection as the active region */
320
+ onSelect (sel: [ number, number ] | null): boolean {
321
+ if (this.prompt() !== null)
322
+ return false
323
+ if (!sel || sel[0] === sel[1]) {
324
+ if (!this.active)
325
+ return false
326
+ this.active = false
327
+ return true
328
+ }
329
+ this.mark = sel[0]
330
+ this.off = sel[1]
331
+ this.active = true
332
+ this.lastCmd = ""
333
+ return true
334
+ }
335
+
336
+ /* the region to be drawn: the current search or replace match, or the active region */
337
+ selection (): [ number, number ] | null {
338
+ if (this.is !== null)
339
+ return this.is.match
340
+ if (this.qr !== null)
341
+ return this.qr.match
342
+ if (this.active && this.mark !== null && this.mark !== this.off)
343
+ return this.mark < this.off ? [ this.mark, this.off ] : [ this.off, this.mark ]
344
+ return null
345
+ }
346
+
347
+ /* the prompt of the minibuffer (with its input), or null without one */
348
+ prompt (): string | null {
349
+ if (this.reader !== null)
350
+ return this.reader.prompt
351
+ if (this.mini !== null)
352
+ return this.mini.prompt + this.mini.text
353
+ if (this.is !== null) {
354
+ const s = this.is
355
+ const what = [ s.failing ? "failing" : "", s.wrapped ? "wrapped" : "", "I-search" ]
356
+ .filter((w) => w !== "").join(" ")
357
+ return `${what[0].toUpperCase()}${what.slice(1)}${s.forward ? "" : " backward"}: ${s.text}`
358
+ }
359
+ if (this.qr !== null)
360
+ return `Query replacing ${this.qr.from} with ${this.qr.to}: (y, n, !, ., q) `
361
+ return null
362
+ }
363
+
364
+ /* the echo of the pending keys (like "C-x-"), or "" */
365
+ echo (): string {
366
+ const keys: string[] = []
367
+ if (this.prefix !== null)
368
+ keys.push([ "C-u", this.prefix.neg ? "-" : "", this.prefix.digits ].filter((k) => k !== "").join(" "))
369
+ if (this.esc)
370
+ keys.push("ESC")
371
+ keys.push(...this.pend)
372
+ return keys.length > 0 ? keys.join(" ") + "-" : ""
373
+ }
374
+
375
+ /* the text being searched resp. replaced, to be highlighted */
376
+ searched (): string | null {
377
+ if (this.is !== null && this.is.text !== "")
378
+ return this.is.text
379
+ if (this.qr !== null)
380
+ return this.qr.from
381
+ return null
382
+ }
383
+
384
+ /* whether a keyboard macro is being defined */
385
+ defining () {
386
+ return this.macroRec !== null
387
+ }
388
+
389
+ /* ==== KEY DISPATCHING ==== */
390
+
391
+ /* dispatch a key token by the current input state */
392
+ private dispatch (token: string) {
393
+ /* an ESC turns the next key into a Meta key, and a second one quits */
394
+ let t = token
395
+ if (this.esc) {
396
+ this.esc = false
397
+ if (t === "ESC")
398
+ t = "C-g"
399
+ else if (t.startsWith("C-"))
400
+ t = "C-M-" + t.slice(2)
401
+ else
402
+ t = "M-" + (t === " " ? "SPC" : t)
403
+ }
404
+ else if (t === "ESC") {
405
+ this.esc = true
406
+ return
407
+ }
408
+ this.recorded = false
409
+ if (this.reader !== null) {
410
+ const r = this.reader
411
+ this.reader = null
412
+ r.take(t)
413
+ }
414
+ else if (this.mini !== null)
415
+ this.miniKey(t)
416
+ else if (this.is !== null)
417
+ this.isearchKey(t)
418
+ else if (this.qr !== null)
419
+ this.queryKey(t)
420
+ else
421
+ this.bufferKey(t)
422
+ }
423
+
424
+ /* handle a key of the buffer: prefix arguments, prefix keys, and commands */
425
+ private bufferKey (t: string) {
426
+ this.message = ""
427
+ this.error = false
428
+ if (this.pend.length === 0 && this.prefix === null && this.macroRec !== null)
429
+ this.macroStart = this.macroRec.length - 1
430
+ if (this.pend.length === 0 && this.argument(t))
431
+ return
432
+ const seq = [ ...this.pend, t ].join(" ")
433
+ if (PREFIXES.has(seq)) {
434
+ this.pend.push(t)
435
+ return
436
+ }
437
+ this.pend = []
438
+ let cmd = BINDINGS.get(seq)
439
+ if (seq === "e" && this.lastCmd === "kmacro-end-and-call-macro" && this.macro.length > 0)
440
+ cmd = "kmacro-end-and-call-macro"
441
+ else if (cmd === undefined && isChar(seq))
442
+ cmd = "self-insert-command"
443
+ const p = this.prefix
444
+ this.prefix = null
445
+ if (cmd === undefined) {
446
+ this.fail(`${seq} is undefined`)
447
+ this.lastCmd = ""
448
+ return
449
+ }
450
+ const arg = p === null ? 1 : p.digits !== "" ? parseInt(p.digits, 10) * (p.neg ? -1 : 1) : p.neg ? -1 : p.n
451
+ const n = Math.max(-MAX_ARG, Math.min(MAX_ARG, arg))
452
+ this.bare = p !== null && p.digits === "" && !p.neg
453
+ this.run(cmd, n, p !== null, t)
454
+ }
455
+
456
+ /* handle the keys of the prefix argument ("C-u", "C-u 5", "M-5", "M--") */
457
+ private argument (t: string): boolean {
458
+ const p = this.prefix
459
+ if (t === "C-u") {
460
+ if (p === null)
461
+ this.prefix = { n: 4, digits: "", neg: false, closed: false }
462
+ else if (p.digits === "" && !p.neg && !p.closed)
463
+ p.n *= 4
464
+ else
465
+ p.closed = true
466
+ return true
467
+ }
468
+ const m = /^M-([0-9-])$/.exec(t)
469
+ if (m) {
470
+ const q = this.prefix ?? (this.prefix = { n: 1, digits: "", neg: false, closed: false })
471
+ if (m[1] === "-")
472
+ q.neg = !q.neg
473
+ else
474
+ q.digits += m[1]
475
+ return true
476
+ }
477
+ if (p !== null && !p.closed && /^[0-9]$/.test(t)) {
478
+ p.digits += t
479
+ return true
480
+ }
481
+ if (p !== null && !p.closed && t === "-" && p.digits === "" && !p.neg) {
482
+ p.neg = true
483
+ return true
484
+ }
485
+ return false
486
+ }
487
+
488
+ /* run a command (deactivating the mark on a text change, like in transient mark mode) */
489
+ private run (cmd: string, n: number, raw: boolean, t: string) {
490
+ const value = this.value
491
+ this.cmd = cmd
492
+ this.exec(cmd, n, raw, t)
493
+ this.cmd = ""
494
+ if (this.value !== value)
495
+ this.active = false
496
+ this.lastCmd = cmd
497
+ }
498
+
499
+ /* ==== COMMANDS ==== */
500
+
501
+ /* execute a command with its numeric argument, whether the argument was given, and its key */
502
+ private exec (cmd: string, n: number, raw: boolean, t: string) {
503
+ const v = this.value
504
+ const o = this.off
505
+ switch (cmd) {
506
+ /* ---- motion ---- */
507
+ case "forward-char": case "backward-char": {
508
+ const k = cmd === "forward-char" ? n : -n
509
+ const p = this.chars(o, k)
510
+ if (p === o && k !== 0)
511
+ this.fail(k > 0 ? "End of buffer" : "Beginning of buffer")
512
+ this.off = p
513
+ break
514
+ }
515
+ case "next-line":
516
+ this.vertical(n)
517
+ break
518
+ case "previous-line":
519
+ this.vertical(-n)
520
+ break
521
+ case "move-beginning-of-line": case "move-end-of-line": {
522
+ const p = n === 1 ? o : lineAt(v, Math.max(0, lineNo(v, o) + n - 1))
523
+ this.off = cmd === "move-beginning-of-line" ? lineStart(v, p) : lineEnd(v, p)
524
+ break
525
+ }
526
+ case "forward-word": case "backward-word":
527
+ this.off = this.words(o, cmd === "forward-word" ? n : -n)
528
+ break
529
+ case "forward-paragraph": case "backward-paragraph": {
530
+ let p = o
531
+ for (let i = 0; i < Math.abs(n); i++)
532
+ p = (cmd === "forward-paragraph") === (n > 0) ? paragraphEnd(v, p) : paragraphBegin(v, p)
533
+ this.off = p
534
+ break
535
+ }
536
+ case "back-to-indentation": {
537
+ let p = lineStart(v, o)
538
+ while (p < lineEnd(v, o) && isSpace(v[p]))
539
+ p++
540
+ this.off = p
541
+ break
542
+ }
543
+ case "beginning-of-buffer": case "end-of-buffer":
544
+ if (!this.active) {
545
+ this.pushMark(o, false)
546
+ this.say("Mark set")
547
+ }
548
+ this.off = cmd === "beginning-of-buffer" ? 0 : v.length
549
+ break
550
+ case "scroll-up-command": case "scroll-down-command": {
551
+ const rows = raw ? n : Math.max(1, this.height - 2)
552
+ this.vertical(cmd === "scroll-up-command" ? rows : -rows)
553
+ break
554
+ }
555
+ case "recenter-top-bottom":
556
+ break
557
+ case "goto-line":
558
+ if (raw)
559
+ this.gotoLine(n)
560
+ else
561
+ this.ask("goto-line", "Goto line: ", "", (text) => {
562
+ const l = parseInt(text, 10)
563
+ if (!Number.isNaN(l))
564
+ this.gotoLine(l)
565
+ })
566
+ break
567
+ case "goto-char":
568
+ this.ask("goto-char", "Goto char: ", "", (text) => {
569
+ const c = parseInt(text, 10)
570
+ if (!Number.isNaN(c)) {
571
+ this.pushMark(this.off, false)
572
+ this.off = Math.max(0, Math.min(c - 1, this.value.length))
573
+ }
574
+ })
575
+ break
576
+
577
+ /* ---- inserting ---- */
578
+ case "self-insert-command":
579
+ this.insert(t.repeat(Math.max(0, n)))
580
+ break
581
+ case "newline":
582
+ this.insert("\n".repeat(Math.max(0, n)))
583
+ break
584
+ case "open-line":
585
+ this.insert("\n".repeat(Math.max(0, n)))
586
+ this.off = o
587
+ break
588
+ case "indent-for-tab-command": case "tab-to-tab-stop":
589
+ this.insert("\t".repeat(Math.max(0, n)))
590
+ break
591
+ case "quoted-insert":
592
+ this.reader = { prompt: "C-q-", take: (k) => {
593
+ const text = isChar(k) ? k : k === "TAB" ? "\t" : k === "C-j" || k === "RET" ? "\n" : ""
594
+ this.insert(text.repeat(Math.max(0, n)))
595
+ } }
596
+ break
597
+
598
+ /* ---- deleting ---- */
599
+ case "delete-char": case "delete-forward-char": {
600
+ if (cmd === "delete-forward-char" && this.deleteRegion())
601
+ break
602
+ const p = this.chars(o, n)
603
+ if (p === o) {
604
+ this.fail(n >= 0 ? "End of buffer" : "Beginning of buffer")
605
+ break
606
+ }
607
+ if (raw)
608
+ this.kill(Math.min(o, p), Math.max(o, p), p < o)
609
+ else {
610
+ this.replace(Math.min(o, p), Math.max(o, p), "")
611
+ this.off = Math.min(o, p)
612
+ }
613
+ break
614
+ }
615
+ case "delete-backward-char": {
616
+ if (this.deleteRegion())
617
+ break
618
+ const p = this.chars(o, -n)
619
+ if (p === o) {
620
+ this.fail(n < 0 ? "End of buffer" : "Beginning of buffer")
621
+ break
622
+ }
623
+ if (raw)
624
+ this.kill(Math.min(o, p), Math.max(o, p), p < o)
625
+ else {
626
+ this.replace(Math.min(o, p), Math.max(o, p), "")
627
+ this.off = Math.min(o, p)
628
+ }
629
+ break
630
+ }
631
+ case "delete-horizontal-space": case "just-one-space": {
632
+ let s = o
633
+ let e = o
634
+ while (s > lineStart(v, o) && isSpace(v[s - 1]))
635
+ s--
636
+ while (!(raw && cmd === "delete-horizontal-space") && e < lineEnd(v, o) && isSpace(v[e]))
637
+ e++
638
+ const text = cmd === "just-one-space" ? " ".repeat(Math.max(0, n)) : ""
639
+ this.replace(s, e, text)
640
+ this.off = s + text.length
641
+ break
642
+ }
643
+ case "delete-indentation": {
644
+ const cs = raw ? (lineEnd(v, o) < v.length ? lineEnd(v, o) + 1 : -1) : lineStart(v, o)
645
+ if (cs <= 0)
646
+ break
647
+ let s = cs - 1
648
+ while (s > lineStart(v, cs - 1) && isSpace(v[s - 1]))
649
+ s--
650
+ let e = cs
651
+ while (e < lineEnd(v, cs) && isSpace(v[e]))
652
+ e++
653
+ const join = s === lineStart(v, cs - 1) || e === lineEnd(v, cs) || v[e] === ")" || v[s - 1] === "(" ? "" : " "
654
+ this.replace(s, e, join)
655
+ this.off = s
656
+ break
657
+ }
658
+ case "delete-blank-lines": {
659
+ const l = lineNo(v, o)
660
+ const last = lineNo(v, v.length)
661
+ const blank = (i: number) => isBlank(v, lineAt(v, i))
662
+ if (blank(l)) {
663
+ let a = l
664
+ let b = l
665
+ while (a > 0 && blank(a - 1))
666
+ a--
667
+ while (b < last && blank(b + 1))
668
+ b++
669
+ if (a === b) {
670
+ let s = lineAt(v, a)
671
+ const e = b < last ? lineAt(v, b + 1) : v.length
672
+ if (e === v.length && s > 0)
673
+ s--
674
+ this.replace(s, e, "")
675
+ this.off = Math.min(s, this.value.length)
676
+ }
677
+ else {
678
+ this.replace(lineAt(v, a), lineEnd(v, lineAt(v, b)), "")
679
+ this.off = lineAt(this.value, a)
680
+ }
681
+ }
682
+ else {
683
+ let b = l + 1
684
+ while (b <= last && blank(b))
685
+ b++
686
+ if (b > l + 1)
687
+ this.replace(lineEnd(v, o), lineEnd(v, lineAt(v, b - 1)), "")
688
+ }
689
+ break
690
+ }
691
+
692
+ /* ---- changing ---- */
693
+ case "transpose-chars": {
694
+ let p = o
695
+ for (let i = 0; i < Math.max(1, n); i++) {
696
+ const w = this.value
697
+ if (p === lineEnd(w, p) && p > lineStart(w, p))
698
+ p = this.ops.previous(w, p)
699
+ const a = this.ops.previous(w, p)
700
+ const b = this.ops.next(w, p)
701
+ if (a === p || b === p) {
702
+ this.fail(a === p ? "Beginning of buffer" : "End of buffer")
703
+ break
704
+ }
705
+ this.replace(a, b, w.slice(p, b) + w.slice(a, p))
706
+ p = b
707
+ }
708
+ this.off = p
709
+ break
710
+ }
711
+ case "transpose-words": {
712
+ const s1 = wordBegin(v, o)
713
+ const e1 = wordEnd(v, s1)
714
+ const e2 = wordEnd(v, e1)
715
+ const s2 = wordBegin(v, e2)
716
+ if (s1 >= s2 || e1 > s2 || s2 >= e2) {
717
+ this.fail("Don't have two things to transpose")
718
+ break
719
+ }
720
+ this.replace(s1, e2, v.slice(s2, e2) + v.slice(e1, s2) + v.slice(s1, e1))
721
+ this.off = e2
722
+ break
723
+ }
724
+ case "transpose-lines": {
725
+ const cs = lineStart(v, o)
726
+ if (cs === 0) {
727
+ this.fail("Don't have two things to transpose")
728
+ break
729
+ }
730
+ const ps = lineStart(v, cs - 1)
731
+ const ce = lineEnd(v, cs)
732
+ this.replace(ps, ce, v.slice(cs, ce) + "\n" + v.slice(ps, cs - 1))
733
+ this.off = ce < v.length ? ce + 1 : ce
734
+ break
735
+ }
736
+ case "upcase-word": case "downcase-word": case "capitalize-word": {
737
+ const s = n >= 0 ? o : this.words(o, n)
738
+ const e = n >= 0 ? this.words(o, n) : o
739
+ const text = this.convert(cmd, v.slice(s, e))
740
+ this.replace(s, e, text)
741
+ if (n >= 0)
742
+ this.off = s + text.length
743
+ break
744
+ }
745
+ case "upcase-region": case "downcase-region": {
746
+ const r = this.region()
747
+ if (r === null)
748
+ break
749
+ this.replace(r[0], r[1], this.convert(cmd, v.slice(r[0], r[1])))
750
+ break
751
+ }
752
+ case "fill-paragraph":
753
+ this.fill()
754
+ break
755
+
756
+ /* ---- killing and yanking ---- */
757
+ case "kill-line": {
758
+ if (raw && n <= 0) {
759
+ let p = lineStart(v, o)
760
+ for (let i = 0; i < -n; i++)
761
+ p = p > 0 ? lineStart(v, p - 1) : 0
762
+ this.kill(p, o, true)
763
+ break
764
+ }
765
+ let e = lineEnd(v, o)
766
+ if (raw) {
767
+ e = o
768
+ for (let i = 0; i < n; i++)
769
+ e = lineEnd(v, e) < v.length ? lineEnd(v, e) + 1 : v.length
770
+ }
771
+ else if (/^[ \t]*$/.test(v.slice(o, e)) && e < v.length)
772
+ e++
773
+ if (e === o) {
774
+ this.fail("End of buffer")
775
+ break
776
+ }
777
+ this.kill(o, e, false)
778
+ break
779
+ }
780
+ case "kill-word":
781
+ if (n >= 0)
782
+ this.kill(o, this.words(o, n), false)
783
+ else
784
+ this.kill(this.words(o, n), o, true)
785
+ break
786
+ case "backward-kill-word":
787
+ if (n >= 0)
788
+ this.kill(this.words(o, -n), o, true)
789
+ else
790
+ this.kill(o, this.words(o, -n), false)
791
+ break
792
+ case "kill-region": {
793
+ const r = this.region()
794
+ if (r !== null)
795
+ this.kill(r[0], r[1], this.off < (this.mark ?? 0))
796
+ break
797
+ }
798
+ case "kill-ring-save": {
799
+ const r = this.region()
800
+ if (r !== null)
801
+ this.pushKill(v.slice(r[0], r[1]), this.off < (this.mark ?? 0), KILLS.has(this.lastCmd))
802
+ this.active = false
803
+ break
804
+ }
805
+ case "yank": {
806
+ if (this.kills.length === 0) {
807
+ this.fail("Kill ring is empty")
808
+ break
809
+ }
810
+ const len = this.kills.length
811
+ this.yankIdx = raw && !this.bare ? ((n - 1) % len + len) % len : 0
812
+ this.insert(this.kills[this.yankIdx])
813
+ this.yankRange = [ o, this.off ]
814
+
815
+ /* a bare "C-u" puts the point at the beginning and the mark at the end */
816
+ if (raw && this.bare) {
817
+ this.pushMark(this.off, false)
818
+ this.off = o
819
+ }
820
+ else
821
+ this.pushMark(o, false)
822
+ break
823
+ }
824
+ case "yank-pop": {
825
+ if (this.kills.length === 0) {
826
+ this.fail("Kill ring is empty")
827
+ break
828
+ }
829
+ if (this.lastCmd !== "yank" && this.lastCmd !== "yank-pop") {
830
+ this.fail("Previous command was not a yank")
831
+ break
832
+ }
833
+ const len = this.kills.length
834
+ this.yankIdx = ((this.yankIdx + n) % len + len) % len
835
+ const text = this.kills[this.yankIdx]
836
+ const [ s, e ] = this.yankRange
837
+ this.replace(s, e, text)
838
+ this.off = s + text.length
839
+ this.yankRange = [ s, this.off ]
840
+ break
841
+ }
842
+ case "zap-to-char": {
843
+ const append = KILLS.has(this.lastCmd)
844
+ this.reader = { prompt: "Zap to char: ", take: (k) => {
845
+ if (!isChar(k)) {
846
+ if (k === "C-g")
847
+ this.say("Quit")
848
+ return
849
+ }
850
+ let e = this.off
851
+ for (let i = 0; i < Math.max(1, n); i++) {
852
+ const p = this.value.indexOf(k, e)
853
+ if (p < 0) {
854
+ this.fail(`Search failed: "${k}"`)
855
+ return
856
+ }
857
+ e = p + k.length
858
+ }
859
+ this.kill(this.off, e, false, append)
860
+ this.lastCmd = "zap-to-char"
861
+ } }
862
+ break
863
+ }
864
+
865
+ /* ---- the mark and the region ---- */
866
+ case "set-mark-command":
867
+ if (raw) {
868
+ if (this.mark === null) {
869
+ this.fail("No mark set in this buffer")
870
+ break
871
+ }
872
+ this.off = this.mark
873
+ this.active = false
874
+
875
+ /* rotate the mark ring, so repeated pops cycle through it */
876
+ const m = this.markRing.pop()
877
+ if (m !== undefined) {
878
+ this.markRing.unshift(this.mark)
879
+ this.mark = m
880
+ }
881
+ }
882
+ else if (this.lastCmd === "set-mark-command" && this.active) {
883
+ this.active = false
884
+ this.say("Mark deactivated")
885
+ }
886
+ else {
887
+ this.pushMark(o, true)
888
+ this.say("Mark set")
889
+ }
890
+ break
891
+ case "exchange-point-and-mark":
892
+ if (this.mark === null) {
893
+ this.fail("No mark set in this buffer")
894
+ break
895
+ }
896
+ this.off = this.mark
897
+ this.mark = o
898
+ this.active = !raw
899
+ break
900
+ case "mark-whole-buffer":
901
+ this.pushMark(v.length, true)
902
+ this.off = 0
903
+ this.say("Mark set")
904
+ break
905
+ case "mark-paragraph": {
906
+ const e = paragraphEnd(v, o)
907
+ this.pushMark(e, true)
908
+ this.off = paragraphBegin(v, e)
909
+ break
910
+ }
911
+ case "mark-word": {
912
+ const from = this.active && this.mark !== null ? this.mark : o
913
+ if (!this.active)
914
+ this.pushMark(o, true)
915
+ this.mark = this.words(from, n)
916
+ this.active = true
917
+ break
918
+ }
919
+
920
+ /* ---- undoing and quitting ---- */
921
+ case "undo":
922
+ this.undo(Math.max(1, n))
923
+ break
924
+ case "keyboard-quit": case "keyboard-escape-quit":
925
+ this.active = false
926
+ if (this.macroRec !== null && cmd === "keyboard-quit") {
927
+ this.macroRec = null
928
+ this.say("Keyboard macro definition cancelled")
929
+ }
930
+ else if (cmd === "keyboard-quit")
931
+ this.say("Quit")
932
+ break
933
+
934
+ /* ---- searching and replacing ---- */
935
+ case "isearch-forward": case "isearch-backward":
936
+ this.is = { forward: cmd === "isearch-forward", text: "", origin: o, failing: false,
937
+ wrapped: false, match: null, off: o, stack: [] }
938
+ break
939
+ case "query-replace": {
940
+ const last = this.lastReplace
941
+ const prompt = last ? `Query replace (default ${last[0]} → ${last[1]}): ` : "Query replace: "
942
+ this.ask("replace", prompt, "", (from) => {
943
+ if (from === "") {
944
+ if (last)
945
+ this.queryStart(last[0], last[1])
946
+ return
947
+ }
948
+ this.ask("replace", `Query replace ${from} with: `, "", (to) => this.queryStart(from, to))
949
+ })
950
+ break
951
+ }
952
+ case "replace-string": case "replace-regexp": {
953
+ const what = cmd === "replace-string" ? "Replace string" : "Replace regexp"
954
+ this.ask("replace", `${what}: `, "", (from) => {
955
+ if (from !== "")
956
+ this.ask("replace", `${what} ${from} with: `, "", (to) =>
957
+ this.replaceAll(from, to, cmd === "replace-regexp"))
958
+ })
959
+ break
960
+ }
961
+
962
+ /* ---- commands ---- */
963
+ case "execute-extended-command":
964
+ this.ask("command", raw ? "C-u M-x " : "M-x ", "", (name) => {
965
+ if (!COMMANDS.includes(name))
966
+ this.fail("[No match]")
967
+ else
968
+ this.run(name, n, raw, "")
969
+ }, COMMANDS)
970
+ break
971
+
972
+ /* ---- files and quitting ---- */
973
+ case "save-buffer": {
974
+ const f = this.need()
975
+ if (f === null)
976
+ break
977
+ if (f.name() === "")
978
+ this.ask("file", "File to save in: ", "", (file) => this.writeFile(file))
979
+ else if (!f.modified())
980
+ this.say("(No changes need to be saved)")
981
+ else
982
+ this.outcome(f.write("", false, false))
983
+ break
984
+ }
985
+ case "write-file":
986
+ if (this.need() !== null)
987
+ this.ask("file", "Write file: ", "", (file) => this.writeFile(file))
988
+ break
989
+ case "save-some-buffers": {
990
+ const f = this.need()
991
+ if (f === null)
992
+ break
993
+ if (!f.modified())
994
+ this.say("(No files need saving)")
995
+ else
996
+ this.askYN(`Save file ${f.name() || "*scratch*"}? `, () => this.exec("save-buffer", 1, false, ""))
997
+ break
998
+ }
999
+ case "save-buffers-kill-terminal": {
1000
+ const f = this.need()
1001
+ if (f === null)
1002
+ break
1003
+ if (!f.modified()) {
1004
+ f.quit()
1005
+ break
1006
+ }
1007
+ this.askYN(`Save file ${f.name() || "*scratch*"}? `, () => {
1008
+ if (f.name() === "")
1009
+ this.ask("file", "File to save in: ", "", (file) => this.writeFile(file, () => f.quit()))
1010
+ else {
1011
+ const res = f.write("", false, false)
1012
+ if (res.error)
1013
+ this.outcome(res)
1014
+ else
1015
+ f.quit()
1016
+ }
1017
+ }, () => this.askYesNo("Modified buffers exist; exit anyway? ", () => f.quit()))
1018
+ break
1019
+ }
1020
+ case "kill-emacs":
1021
+ this.need()?.quit()
1022
+ break
1023
+ case "find-file": {
1024
+ const f = this.need()
1025
+ if (f !== null)
1026
+ this.ask("file", "Find file: ", f.name(), (file) => {
1027
+ if (file !== "" && file !== f.name())
1028
+ this.fail("Visiting another file is not supported")
1029
+ })
1030
+ break
1031
+ }
1032
+ case "revert-buffer": {
1033
+ const f = this.need()
1034
+ if (f === null)
1035
+ break
1036
+ if (f.name() === "") {
1037
+ this.fail("Buffer does not seem to be associated with any file")
1038
+ break
1039
+ }
1040
+ this.askYesNo(`Revert buffer from file ${f.name()}? `, () => this.outcome(f.reload()))
1041
+ break
1042
+ }
1043
+ case "suspend-frame":
1044
+ this.fail("Suspending is not supported")
1045
+ break
1046
+
1047
+ /* ---- information ---- */
1048
+ case "what-cursor-position": {
1049
+ const col = o - lineStart(v, o)
1050
+ const pct = Math.round(100 * o / Math.max(1, v.length))
1051
+ if (o >= v.length)
1052
+ this.say(`point=${o + 1} of ${v.length + 1} (${pct}%) column=${col}`)
1053
+ else {
1054
+ const cp = v.codePointAt(o) ?? 0
1055
+ const ch = cp === 10 ? "C-j" : String.fromCodePoint(cp)
1056
+ this.say(`Char: ${ch} (${cp}, #o${cp.toString(8)}, #x${cp.toString(16)}) ` +
1057
+ `point=${o + 1} of ${v.length + 1} (${pct}%) column=${col}`)
1058
+ }
1059
+ break
1060
+ }
1061
+ case "count-words-region": case "count-words": {
1062
+ const mark = cmd === "count-words-region" ? this.mark : null
1063
+ const text = mark === null ? v : v.slice(Math.min(mark, o), Math.max(mark, o))
1064
+ const lines = text === "" ? 0 : text.split("\n").length - (text.endsWith("\n") ? 1 : 0)
1065
+ const words = (text.match(/[\p{L}\p{N}]+/gu) ?? []).length
1066
+ const what = mark === null ? "Buffer" : "Region"
1067
+ this.say(`${what} has ${plural(lines, "line")}, ${plural(words, "word")}, ` +
1068
+ `and ${plural([ ...text ].length, "character")}.`)
1069
+ break
1070
+ }
1071
+ case "what-line":
1072
+ this.say(`Line ${lineNo(v, o) + 1}`)
1073
+ break
1074
+ case "delete-trailing-whitespace": {
1075
+ const text = v.replace(/[ \t]+$/gm, "")
1076
+ if (text !== v) {
1077
+ const cur = toCursor(v, o)
1078
+ this.replace(0, v.length, text)
1079
+ this.off = toOffset(text, cur)
1080
+ }
1081
+ break
1082
+ }
1083
+
1084
+ /* ---- keyboard macros ---- */
1085
+ case "kmacro-start-macro":
1086
+ if (this.macroRec !== null) {
1087
+ this.fail("Already defining keyboard macro")
1088
+ break
1089
+ }
1090
+ this.macroRec = []
1091
+ this.say("Defining kbd macro...")
1092
+ break
1093
+ case "kmacro-end-macro":
1094
+ if (this.macroRec === null) {
1095
+ this.fail("Not defining kbd macro")
1096
+ break
1097
+ }
1098
+ this.macro = this.macroRec.slice(0, this.macroStart)
1099
+ this.macroRec = null
1100
+ this.say("Keyboard macro defined")
1101
+ break
1102
+ case "kmacro-end-and-call-macro": {
1103
+ if (this.macroRec !== null) {
1104
+ this.macro = this.macroRec.slice(0, this.macroStart)
1105
+ this.macroRec = null
1106
+ }
1107
+ if (this.macro.length === 0) {
1108
+ this.fail("No kbd macro has been defined")
1109
+ break
1110
+ }
1111
+ if (this.depth > 0)
1112
+ break
1113
+ this.depth++
1114
+ for (let i = 0; i < Math.max(1, n) && !this.error; i++)
1115
+ for (const k of this.macro)
1116
+ if (!this.error)
1117
+ this.dispatch(k)
1118
+ this.depth--
1119
+ this.lastCmd = cmd
1120
+ if (!this.error)
1121
+ this.say("(Type e to repeat macro)")
1122
+ break
1123
+ }
1124
+ }
1125
+ }
1126
+
1127
+ /* ==== MOTION HELPERS ==== */
1128
+
1129
+ /* step over graphemes */
1130
+ private chars (o: number, n: number): number {
1131
+ let p = o
1132
+ for (let i = 0; i < Math.abs(n); i++) {
1133
+ const q = n > 0 ? this.ops.next(this.value, p) : this.ops.previous(this.value, p)
1134
+ if (q === p)
1135
+ break
1136
+ p = q
1137
+ }
1138
+ return p
1139
+ }
1140
+
1141
+ /* step over words */
1142
+ private words (o: number, n: number): number {
1143
+ let p = o
1144
+ for (let i = 0; i < Math.abs(n); i++)
1145
+ p = n > 0 ? wordEnd(this.value, p) : wordBegin(this.value, p)
1146
+ return p
1147
+ }
1148
+
1149
+ /* move by rows, keeping the goal column of the first move of a sequence */
1150
+ private vertical (n: number) {
1151
+ if (this.lastCmd !== "next-line" && this.lastCmd !== "previous-line")
1152
+ this.goal = goalColumn(this.ops, this.value, this.off)
1153
+ const dir = n < 0 ? -1 : 1
1154
+ for (let i = 0; i < Math.abs(n); i++) {
1155
+ const t = rowMove(this.ops, this.value, this.off, dir, this.goal)
1156
+ if (t === this.off) {
1157
+ this.fail(dir < 0 ? "Beginning of buffer" : "End of buffer")
1158
+ break
1159
+ }
1160
+ this.off = t
1161
+ }
1162
+ }
1163
+
1164
+ /* go to a line, saving the mark */
1165
+ private gotoLine (l: number) {
1166
+ this.pushMark(this.off, false)
1167
+ this.off = lineAt(this.value, Math.max(0, l - 1))
1168
+ }
1169
+
1170
+ /* ==== EDITING HELPERS ==== */
1171
+
1172
+ /* record the text for undoing, once per key and amalgamating up to 20 inserted characters */
1173
+ private record () {
1174
+ if (this.recorded)
1175
+ return
1176
+ this.recorded = true
1177
+ if (this.cmd === "self-insert-command" && this.lastCmd === "self-insert-command" && this.amalgam < 20) {
1178
+ this.amalgam++
1179
+ return
1180
+ }
1181
+ this.amalgam = this.cmd === "self-insert-command" ? 1 : 0
1182
+ this.undos.push({ value: this.value, off: this.off })
1183
+ if (this.undos.length > 2000)
1184
+ this.undos.splice(0, this.undos.length - 2000)
1185
+ }
1186
+
1187
+ /* replace a range of the text, keeping the mark and the mark ring on the surrounding text */
1188
+ private replace (s: number, e: number, text: string) {
1189
+ this.record()
1190
+ const d = text.length - (e - s)
1191
+ const adjust = (p: number) => p > e || (p === e && e > s) ? p + d : p > s ? s : p
1192
+ this.value = this.value.slice(0, s) + text + this.value.slice(e)
1193
+ if (this.mark !== null)
1194
+ this.mark = adjust(this.mark)
1195
+ this.markRing = this.markRing.map(adjust)
1196
+ this.emit(this.value)
1197
+ }
1198
+
1199
+ /* insert a text at the point */
1200
+ private insert (text: string) {
1201
+ if (text === "")
1202
+ return
1203
+ this.replace(this.off, this.off, text)
1204
+ this.off += text.length
1205
+ }
1206
+
1207
+ /* convert the case of a text */
1208
+ private convert (cmd: string, text: string) {
1209
+ if (cmd.startsWith("upcase"))
1210
+ return text.toUpperCase()
1211
+ if (cmd.startsWith("downcase"))
1212
+ return text.toLowerCase()
1213
+ return text.replace(/[\p{L}\p{N}]+/gu, (w) => {
1214
+ const [ c, ...rest ] = [ ...w ]
1215
+ return c.toUpperCase() + rest.join("").toLowerCase()
1216
+ })
1217
+ }
1218
+
1219
+ /* fill the paragraph of the point */
1220
+ private fill () {
1221
+ const f = fillParagraph(this.value, this.off, FILL_COLUMN)
1222
+ if (f === null)
1223
+ return
1224
+ if (f.text !== this.value.slice(f.start, f.end))
1225
+ this.replace(f.start, f.end, f.text)
1226
+ this.off = f.off
1227
+ }
1228
+
1229
+ /* ==== MARK AND KILL HELPERS ==== */
1230
+
1231
+ /* set the mark, saving the previous one on the mark ring */
1232
+ private pushMark (o: number, activate: boolean) {
1233
+ if (this.mark !== null) {
1234
+ this.markRing.push(this.mark)
1235
+ if (this.markRing.length > 16)
1236
+ this.markRing.shift()
1237
+ }
1238
+ this.mark = o
1239
+ this.active = activate
1240
+ }
1241
+
1242
+ /* the region between the point and the mark */
1243
+ private region (): [ number, number ] | null {
1244
+ if (this.mark === null) {
1245
+ this.fail("The mark is not set now, so there is no region")
1246
+ return null
1247
+ }
1248
+ return this.mark < this.off ? [ this.mark, this.off ] : [ this.off, this.mark ]
1249
+ }
1250
+
1251
+ /* delete the active region (of DEL and <deletechar>) */
1252
+ private deleteRegion (): boolean {
1253
+ if (!this.active || this.mark === null || this.mark === this.off)
1254
+ return false
1255
+ const s = Math.min(this.mark, this.off)
1256
+ this.replace(s, Math.max(this.mark, this.off), "")
1257
+ this.off = s
1258
+ return true
1259
+ }
1260
+
1261
+ /* kill a range of the text into the kill ring */
1262
+ private kill (s: number, e: number, prepend: boolean, append = KILLS.has(this.lastCmd)) {
1263
+ this.pushKill(this.value.slice(s, e), prepend, append)
1264
+ this.replace(s, e, "")
1265
+ this.off = s
1266
+ }
1267
+
1268
+ /* put a text onto the kill ring (and the clipboard), appending it to the last kill
1269
+ resp. prepending it for a backward kill */
1270
+ private pushKill (text: string, prepend: boolean, append: boolean) {
1271
+ if (append && this.kills.length > 0)
1272
+ this.kills[0] = prepend ? text + this.kills[0] : this.kills[0] + text
1273
+ else {
1274
+ this.kills.unshift(text)
1275
+ if (this.kills.length > 120)
1276
+ this.kills.pop()
1277
+ }
1278
+ this.clip(this.kills[0])
1279
+ }
1280
+
1281
+ /* undo changes, where an interrupted sequence of undos starts over and hence redoes */
1282
+ private undo (n: number) {
1283
+ if (this.lastCmd !== "undo")
1284
+ this.undoPtr = this.undos.length
1285
+ for (let i = 0; i < n; i++) {
1286
+ if (this.undoPtr === 0) {
1287
+ this.fail("No further undo information")
1288
+ return
1289
+ }
1290
+ const snap = this.undos[--this.undoPtr]
1291
+ this.undos.push({ value: this.value, off: this.off })
1292
+ this.value = snap.value
1293
+ this.off = Math.min(snap.off, snap.value.length)
1294
+ if (this.mark !== null)
1295
+ this.mark = Math.min(this.mark, this.value.length)
1296
+ this.emit(this.value)
1297
+ }
1298
+ this.say("Undo")
1299
+ }
1300
+
1301
+ /* ==== MINIBUFFER ==== */
1302
+
1303
+ /* read a text in the minibuffer */
1304
+ private ask (kind: string, prompt: string, init: string, done: (text: string) => void, names?: string[]) {
1305
+ this.mini = { kind, prompt, text: init, done, names, hist: -1 }
1306
+ }
1307
+
1308
+ /* read a "y" or "n" answer */
1309
+ private askYN (question: string, yes: () => void, no: () => void = () => {}) {
1310
+ this.reader = { prompt: `${question}(y or n) `, take: (t) => {
1311
+ if (t === "y" || t === "Y" || t === " ")
1312
+ yes()
1313
+ else if (t === "n" || t === "N" || t === "DEL")
1314
+ no()
1315
+ else if (t === "C-g")
1316
+ this.say("Quit")
1317
+ else
1318
+ this.askYN(question.startsWith("Please answer") ? question : `Please answer y or n. ${question}`, yes, no)
1319
+ } }
1320
+ }
1321
+
1322
+ /* read a "yes" or "no" answer */
1323
+ private askYesNo (question: string, yes: () => void) {
1324
+ this.ask("yes-or-no", `${question}(yes or no) `, "", (answer) => {
1325
+ if (answer === "yes")
1326
+ yes()
1327
+ else if (answer !== "no")
1328
+ this.askYesNo(question.startsWith("Please answer") ? question : `Please answer yes or no. ${question}`, yes)
1329
+ })
1330
+ }
1331
+
1332
+ /* handle a key of the minibuffer */
1333
+ private miniKey (t: string) {
1334
+ const m = this.mini
1335
+ if (m === null)
1336
+ return
1337
+ const hist = this.history.get(m.kind) ?? []
1338
+ if (isChar(t))
1339
+ m.text += t
1340
+ else if (t === "DEL")
1341
+ m.text = m.text.slice(0, this.ops.previous(m.text, m.text.length))
1342
+ else if (t === "M-DEL" || t === "C-DEL")
1343
+ m.text = m.text.slice(0, wordBegin(m.text, m.text.length))
1344
+ else if (t === "C-y")
1345
+ m.text += this.kills[0] ?? ""
1346
+ else if (t === "TAB" && m.names) {
1347
+ const hits = m.names.filter((name) => name.startsWith(m.text))
1348
+ if (hits.length > 0)
1349
+ m.text = commonPrefix(hits)
1350
+ }
1351
+ else if ((t === "M-p" || t === "<up>") && m.hist + 1 < hist.length)
1352
+ m.text = hist[++m.hist]
1353
+ else if ((t === "M-n" || t === "<down>") && m.hist >= 0) {
1354
+ m.hist--
1355
+ m.text = m.hist >= 0 ? hist[m.hist] : ""
1356
+ }
1357
+ else if (t === "C-g") {
1358
+ this.mini = null
1359
+ this.say("Quit")
1360
+ }
1361
+ else if (t === "RET") {
1362
+ this.mini = null
1363
+ if (m.text !== "")
1364
+ this.history.set(m.kind, [ m.text, ...hist.filter((h) => h !== m.text) ].slice(0, 50))
1365
+ m.done(m.text)
1366
+ }
1367
+ }
1368
+
1369
+ /* ==== FILE HELPERS ==== */
1370
+
1371
+ /* the file operations, or an error without them */
1372
+ private need (): EmacsFiles | null {
1373
+ if (this.files === null)
1374
+ this.fail("No file operations available")
1375
+ return this.files
1376
+ }
1377
+
1378
+ /* show the outcome of a file operation */
1379
+ private outcome (res: EmacsOutcome) {
1380
+ if (res.error)
1381
+ this.fail(res.message)
1382
+ else
1383
+ this.say(res.message)
1384
+ }
1385
+
1386
+ /* write the text to a file, which becomes the visited one, asking before overwriting,
1387
+ and continue after a successful write */
1388
+ private writeFile (file: string, then: () => void = () => {}) {
1389
+ const f = this.files
1390
+ if (f === null)
1391
+ return
1392
+ if (file === "") {
1393
+ this.fail("No file name")
1394
+ return
1395
+ }
1396
+ const done = (r: EmacsOutcome) => {
1397
+ this.outcome(r)
1398
+ if (!r.error)
1399
+ then()
1400
+ }
1401
+ const res = f.write(file, false, true)
1402
+ if (res.exists)
1403
+ this.askYN(`File ${file} exists; overwrite? `, () => done(f.write(file, true, true)))
1404
+ else
1405
+ done(res)
1406
+ }
1407
+
1408
+ /* ==== INCREMENTAL SEARCH ==== */
1409
+
1410
+ /* find a text forward from an offset, resp. backward with the match starting at most there */
1411
+ private find (text: string, from: number, forward: boolean): [ number, number ] | null {
1412
+ if (text === "")
1413
+ return null
1414
+ const re = literalRegExp(text)
1415
+ if (forward) {
1416
+ re.lastIndex = Math.max(0, from)
1417
+ const m = re.exec(this.value)
1418
+ return m ? [ m.index, m.index + m[0].length ] : null
1419
+ }
1420
+ let found: [ number, number ] | null = null
1421
+ for (const m of this.value.matchAll(re)) {
1422
+ if (m.index > from)
1423
+ break
1424
+ found = [ m.index, m.index + m[0].length ]
1425
+ }
1426
+ return found
1427
+ }
1428
+
1429
+ /* handle a key of the incremental search */
1430
+ private isearchKey (t: string) {
1431
+ const s = this.is
1432
+ if (s === null)
1433
+ return
1434
+ const save = () => s.stack.push({ forward: s.forward, text: s.text, failing: s.failing,
1435
+ wrapped: s.wrapped, match: s.match, off: this.off })
1436
+ const restore = (p: Step) => {
1437
+ Object.assign(s, { forward: p.forward, text: p.text, failing: p.failing, wrapped: p.wrapped, match: p.match })
1438
+ this.off = p.off
1439
+ }
1440
+ const apply = (m: [ number, number ] | null) => {
1441
+ if (m === null)
1442
+ s.failing = true
1443
+ else {
1444
+ s.failing = false
1445
+ s.match = m
1446
+ this.off = s.forward ? m[1] : m[0]
1447
+ }
1448
+ }
1449
+ if (t === "C-s" || t === "C-r") {
1450
+ const forward = t === "C-s"
1451
+ save()
1452
+ if (s.text === "") {
1453
+ s.forward = forward
1454
+ if (this.lastSearch !== "") {
1455
+ s.text = this.lastSearch
1456
+ apply(this.find(s.text, forward ? this.off : this.off - s.text.length, forward))
1457
+ }
1458
+ }
1459
+ else if (forward !== s.forward) {
1460
+ s.forward = forward
1461
+ if (s.match !== null)
1462
+ this.off = forward ? s.match[1] : s.match[0]
1463
+ }
1464
+ else if (s.failing) {
1465
+ s.wrapped = true
1466
+ apply(this.find(s.text, forward ? 0 : this.value.length, forward))
1467
+ }
1468
+ else
1469
+ apply(this.find(s.text, forward ? (s.match?.[1] ?? this.off) : (s.match?.[0] ?? this.off) - 1, forward))
1470
+ }
1471
+ else if (isChar(t) || t === "C-w" || t === "C-y") {
1472
+ save()
1473
+ if (t === "C-w")
1474
+ s.text += this.value.slice(this.off, wordEnd(this.value, this.off))
1475
+ else if (t === "C-y")
1476
+ s.text += this.kills[0] ?? ""
1477
+ else
1478
+ s.text += t
1479
+ const base = s.match !== null ? s.match[0] : s.forward ? s.origin : s.origin - s.text.length
1480
+ apply(this.find(s.text, base, s.forward))
1481
+ }
1482
+ else if (t === "DEL") {
1483
+ const p = s.stack.pop()
1484
+ if (p !== undefined)
1485
+ restore(p)
1486
+ }
1487
+ else if (t === "C-g") {
1488
+ if (s.failing) {
1489
+ while (s.failing && s.stack.length > 0)
1490
+ restore(s.stack.pop() as Step)
1491
+ s.failing = false
1492
+ }
1493
+ else {
1494
+ this.off = s.origin
1495
+ this.is = null
1496
+ this.say("Quit")
1497
+ }
1498
+ }
1499
+ else if (t === "RET")
1500
+ this.isearchEnd()
1501
+ else {
1502
+ this.isearchEnd()
1503
+ this.dispatch(t)
1504
+ }
1505
+ }
1506
+
1507
+ /* end the incremental search, saving the mark where it started */
1508
+ private isearchEnd () {
1509
+ const s = this.is
1510
+ if (s === null)
1511
+ return
1512
+ this.is = null
1513
+ if (s.text !== "")
1514
+ this.lastSearch = s.text
1515
+ if (this.off !== s.origin) {
1516
+ this.pushMark(s.origin, false)
1517
+ this.say("Mark saved where search started")
1518
+ }
1519
+ }
1520
+
1521
+ /* ==== REPLACING ==== */
1522
+
1523
+ /* start a query replace from the point resp. in the active region */
1524
+ private queryStart (from: string, to: string) {
1525
+ this.lastReplace = [ from, to ]
1526
+ const mark = this.mark
1527
+ const region = this.active && mark !== null
1528
+ const s = region ? Math.min(mark, this.off) : this.off
1529
+ const e = region ? Math.max(mark, this.off) : this.value.length
1530
+ this.active = false
1531
+ this.qr = { from, to, pos: s, limit: e, match: [ s, s ], count: 0 }
1532
+ this.queryNext()
1533
+ }
1534
+
1535
+ /* find the next match of the query replace, or end it */
1536
+ private queryNext () {
1537
+ const q = this.qr
1538
+ if (q === null)
1539
+ return
1540
+ const m = this.find(q.from, q.pos, true)
1541
+ if (m === null || m[1] > q.limit) {
1542
+ this.queryEnd()
1543
+ return
1544
+ }
1545
+ q.match = m
1546
+ this.off = m[1]
1547
+ }
1548
+
1549
+ /* replace the current match of the query replace */
1550
+ private queryReplace () {
1551
+ const q = this.qr
1552
+ if (q === null)
1553
+ return
1554
+ const [ s, e ] = q.match
1555
+ this.replace(s, e, q.to)
1556
+ q.pos = s + q.to.length
1557
+ q.limit += q.to.length - (e - s)
1558
+ q.count++
1559
+ this.off = q.pos
1560
+ }
1561
+
1562
+ /* end the query replace */
1563
+ private queryEnd () {
1564
+ const q = this.qr
1565
+ if (q === null)
1566
+ return
1567
+ this.qr = null
1568
+ this.say(`Replaced ${plural(q.count, "occurrence")}`)
1569
+ }
1570
+
1571
+ /* handle a key of the query replace */
1572
+ private queryKey (t: string) {
1573
+ const q = this.qr
1574
+ if (q === null)
1575
+ return
1576
+ switch (t) {
1577
+ case "y": case " ":
1578
+ this.queryReplace()
1579
+ this.queryNext()
1580
+ break
1581
+ case "n": case "DEL":
1582
+ q.pos = q.match[1]
1583
+ this.queryNext()
1584
+ break
1585
+ case "!":
1586
+ while (this.qr !== null) {
1587
+ this.queryReplace()
1588
+ this.queryNext()
1589
+ }
1590
+ break
1591
+ case ".":
1592
+ this.queryReplace()
1593
+ this.queryEnd()
1594
+ break
1595
+ case "q": case "RET":
1596
+ this.queryEnd()
1597
+ break
1598
+ case "C-g":
1599
+ this.qr = null
1600
+ this.say("Quit")
1601
+ break
1602
+ default:
1603
+ this.queryEnd()
1604
+ this.dispatch(t)
1605
+ }
1606
+ }
1607
+
1608
+ /* replace all matches from the point resp. in the active region */
1609
+ private replaceAll (from: string, to: string, regexp: boolean) {
1610
+ let re: RegExp
1611
+ try {
1612
+ re = regexp ? new RegExp(from, from === from.toLowerCase() ? "gim" : "gm") : literalRegExp(from)
1613
+ }
1614
+ catch (err) {
1615
+ this.fail(`Invalid regexp: ${err instanceof Error ? err.message : String(err)}`)
1616
+ return
1617
+ }
1618
+ const mark = this.mark
1619
+ const region = this.active && mark !== null
1620
+ const s = region ? Math.min(mark, this.off) : this.off
1621
+ const e = region ? Math.max(mark, this.off) : this.value.length
1622
+ const segment = this.value.slice(s, e)
1623
+ const count = [ ...segment.matchAll(re) ].length
1624
+ const result = regexp
1625
+ ? segment.replace(re, to.replace(/\$/g, "$$$$").replace(/\\(\d|&)/g, (_, d: string) => d === "&" ? "$&" : "$" + d))
1626
+ : segment.replace(re, () => to)
1627
+ if (result !== segment)
1628
+ this.replace(s, e, result)
1629
+ this.off = s + result.length
1630
+ this.active = false
1631
+ this.say(`Replaced ${plural(count, "occurrence")}`)
1632
+ }
1633
+
1634
+ /* ==== MESSAGES ==== */
1635
+
1636
+ /* show an informational message */
1637
+ protected say (text: string) {
1638
+ this.message = text
1639
+ this.error = false
1640
+ }
1641
+
1642
+ /* show an error message */
1643
+ protected fail (text: string) {
1644
+ this.message = text
1645
+ this.error = true
1646
+ }
1647
+ }
1648
+