@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,137 @@
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
+ /* the contract between the editor, its widget, and its editing modes
26
+ (dependency-free: it knows nothing about React, Ink, or any terminal) */
27
+
28
+ /* internal dependencies */
29
+ import type { TextOps } from "./ink-editor-text"
30
+
31
+ /* a key press (structurally a subset of the "Key" of Ink) */
32
+ export interface EditorKey {
33
+ escape: boolean
34
+ return: boolean
35
+ tab: boolean
36
+ backspace: boolean
37
+ delete: boolean
38
+ upArrow: boolean
39
+ downArrow: boolean
40
+ leftArrow: boolean
41
+ rightArrow: boolean
42
+ pageUp: boolean
43
+ pageDown: boolean
44
+ home: boolean
45
+ end: boolean
46
+ ctrl: boolean
47
+ meta: boolean
48
+ shift: boolean
49
+ }
50
+
51
+ /* the outcome of a file operation of the host: the file, or the failure */
52
+ export type EditorFile = { name: string, isNew: boolean, crlf: boolean, lines: number, bytes: number }
53
+ export type EditorError = { error: "noname" | "exists" | "read" | "write", detail: string }
54
+ export type EditorResult = EditorFile | EditorError
55
+
56
+ /* the file operations and the quitting of the host, used by the modes for their commands */
57
+ export interface EditorHost {
58
+ /* the name of the edited file ("" for none), and whether its text is modified */
59
+ name (): string
60
+ modified (): boolean
61
+
62
+ /* write the text to a file ("" for the edited one), overwriting another existing file
63
+ only with "force", and with "rename" making the written file the edited one */
64
+ write (file: string, force: boolean, rename?: boolean): EditorResult
65
+
66
+ /* reload the text of the edited file */
67
+ reload (): EditorResult
68
+
69
+ /* quit the editor, optionally with a failure exit status */
70
+ quit (failed?: boolean): void
71
+ }
72
+
73
+ /* the bindings of a mode to the widget and the host, re-bound on each rendering */
74
+ export interface EditorBinding {
75
+ ops: TextOps
76
+ height: number
77
+ emit: (value: string) => void
78
+ clip: (text: string) => void
79
+ host: EditorHost | null
80
+ }
81
+
82
+ /* the status line, as drawn by the widget */
83
+ export interface EditorStatus {
84
+ /* the input typed on the status line (with the cursor at its end), or null */
85
+ prompt: string | null
86
+
87
+ /* a message, shown in place of the label and the note, and whether it is an error */
88
+ message: string
89
+ error: boolean
90
+
91
+ /* the label (like the mode) shown bold, and the note following it */
92
+ label: string
93
+ note: string
94
+
95
+ /* the right-aligned information and the keystroke hints following it (shown grey),
96
+ both dropped when they do not fit */
97
+ info: string
98
+ hints: string
99
+ }
100
+
101
+ /* an editing mode, driving the Textarea of the widget */
102
+ export interface EditorMode {
103
+ /* re-bind the mode, take over an externally changed text, and report an opened file */
104
+ bind (binding: EditorBinding): void
105
+ sync (value: string): void
106
+ opened (result: EditorResult): void
107
+
108
+ /* the text and the cursor offset to be drawn */
109
+ readonly value: string
110
+ readonly off: number
111
+
112
+ /* the selection to be drawn (undefined to leave it to the Textarea) */
113
+ selection (): [ number, number ] | null | undefined
114
+
115
+ /* whether the cursor blinks, the pattern to highlight, and the text of the rows below the end */
116
+ blink (): boolean
117
+ highlight (): RegExp | null
118
+ filler (): string
119
+
120
+ /* the status line, given the [ line, column ] cursor of the Textarea */
121
+ status (cursor: [ number, number ]): EditorStatus
122
+
123
+ /* handle a key press (false for one left to the Textarea) and a bracketed paste
124
+ (without the latter, the Textarea inserts a paste itself) */
125
+ key (input: string, key: EditorKey): boolean
126
+ paste? (text: string): void
127
+
128
+ /* take over the text, cursor, and selection changes of the Textarea
129
+ (the latter returning whether the mode took it over) */
130
+ onText (value: string): void
131
+ onCursor (cursor: [ number, number ]): void
132
+ onSelect (selection: [ number, number ] | null): boolean
133
+ }
134
+
135
+ /* the creation of a mode for an initial text and the text operations of the Textarea */
136
+ export type EditorModeFactory = (value: string, ops: TextOps) => EditorMode
137
+
@@ -0,0 +1,176 @@
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
+ /* syntax highlighting of a text via Shiki, as styled ranges for the Textarea */
26
+
27
+ /* external dependencies */
28
+ import path from "node:path"
29
+ import { createHighlighterCore } from "shiki/core"
30
+ import { createJavaScriptRegexEngine } from "shiki/engine/javascript"
31
+ import { bundledLanguages, bundledLanguagesInfo } from "shiki/langs"
32
+ import type { GrammarState } from "shiki/core"
33
+
34
+ /* the style of a highlighted range (a subset of the Textarea styles) */
35
+ export type SyntaxStyle = { color?: string, bold?: boolean, italic?: boolean }
36
+
37
+ /* a highlighted range of a text */
38
+ export type SyntaxRange = { start: number, end: number, label: string, style: SyntaxStyle }
39
+
40
+ /* the highlighting of a text */
41
+ export type Syntax = (value: string) => SyntaxRange[]
42
+
43
+ /* the highlight groups (a restrained theme of just the named terminal colors
44
+ gray, blue, and red, so they follow the terminal theme, plus bold and italic),
45
+ each with the TextMate scopes it covers and a unique pseudo color, by which the
46
+ group of a token is recognized again after Shiki resolved the theme */
47
+ const groups: { scopes: string[], marker: string, style: SyntaxStyle }[] = [
48
+ { marker: "#000001", style: { color: "gray", italic: true },
49
+ scopes: [ "comment", "punctuation.definition.comment" ] },
50
+ { marker: "#000002", style: { color: "red" },
51
+ scopes: [ "string", "constant", "markup.inline.raw", "markup.fenced_code", "punctuation.definition.string" ] },
52
+ { marker: "#000003", style: { color: "blue", bold: true },
53
+ scopes: [ "keyword", "storage", "variable.language" ] },
54
+ { marker: "#000004", style: { color: "blue", bold: true },
55
+ scopes: [ "entity.name.type", "entity.name.class", "support.type", "support.class" ] },
56
+ { marker: "#000005", style: { color: "blue" },
57
+ scopes: [ "entity.name.function", "support.function", "entity.name.tag",
58
+ "entity.other.attribute-name", "support.type.property-name", "meta.object-literal.key",
59
+ "markup.underline.link" ] },
60
+ { marker: "#000006", style: { color: "red", bold: true },
61
+ scopes: [ "constant.character.escape", "punctuation.definition.template-expression",
62
+ "punctuation.section.embedded", "meta.preprocessor", "keyword.control.directive" ] },
63
+ { marker: "#000007", style: { color: "blue", bold: true },
64
+ scopes: [ "markup.heading", "entity.name.section", "punctuation.definition.heading" ] },
65
+ { marker: "#000008", style: { bold: true },
66
+ scopes: [ "markup.bold" ] },
67
+ { marker: "#000009", style: { italic: true },
68
+ scopes: [ "markup.italic" ] }
69
+ ]
70
+
71
+ /* the style of each highlight group, by its pseudo color */
72
+ const styleOf = new Map(groups.map((g) => [ g.marker, g.style ]))
73
+
74
+ /* the scopes left uncolored (more specific scopes above still win) */
75
+ const plain = [ "keyword.operator", "punctuation" ]
76
+
77
+ /* the language of a file, by its name, its extension, or a Shiki language id or alias */
78
+ export const syntaxLanguage = (file: string): string | null => {
79
+ const known = new Map<string, string>()
80
+ for (const info of bundledLanguagesInfo)
81
+ for (const name of [ info.id, ...(info.aliases ?? []) ])
82
+ known.set(name.toLowerCase(), info.id)
83
+ const base = path.basename(file).toLowerCase()
84
+ const ext = path.extname(base).slice(1)
85
+ return known.get(base) ?? known.get(ext) ?? null
86
+ }
87
+
88
+ /* the tokens of a line (with offsets relative to the line start) */
89
+ type LineTokens = { start: number, end: number, style: SyntaxStyle }[]
90
+
91
+ /* load the highlighting of a language, or null where there is none */
92
+ export const syntaxLoad = async (language: string | null): Promise<Syntax | null> => {
93
+ if (language === null || !Object.hasOwn(bundledLanguages, language))
94
+ return null
95
+ const highlighter = await createHighlighterCore({
96
+ themes: [ {
97
+ name: "editor", type: "dark", fg: "#000000", bg: "#ffffff",
98
+ settings: [
99
+ ...groups.map((g) => ({ scope: g.scopes, settings: { foreground: g.marker } })),
100
+ { scope: plain, settings: { foreground: "#000000" } },
101
+
102
+ /* uncolored scopes nested in a group (like a quantifier in a regex) keep its color */
103
+ ...groups.map((g) => ({ scope: g.scopes.flatMap((s) => plain.map((p) => `${s} ${p}`)),
104
+ settings: { foreground: g.marker } }))
105
+ ]
106
+ } ],
107
+ langs: [ bundledLanguages[language as keyof typeof bundledLanguages] ],
108
+ engine: createJavaScriptRegexEngine({ forgiving: true })
109
+ })
110
+
111
+ /* tokenize a single line, continuing from the grammar state at its start */
112
+ const tokenize = (line: string, state: GrammarState | undefined): { tokens: LineTokens, end: GrammarState } => {
113
+ const result = highlighter.codeToTokensBase(line, { lang: language, theme: "editor", grammarState: state })
114
+ const tokens: LineTokens = []
115
+ for (const token of result[0] ?? []) {
116
+ const style = styleOf.get((token.color ?? "").toLowerCase())
117
+ if (style !== undefined && token.content !== "")
118
+ tokens.push({ start: token.offset, end: token.offset + token.content.length, style })
119
+ }
120
+ return { tokens, end: highlighter.getLastGrammarState(result) as GrammarState }
121
+ }
122
+
123
+ /* whether two grammar states are equal (by their internal grammar stacks) */
124
+ const same = (a: GrammarState, b: GrammarState) => {
125
+ const sa = a.getInternalStack()
126
+ const sb = b.getInternalStack()
127
+ return sa !== undefined && sb !== undefined && sa.equals(sb)
128
+ }
129
+
130
+ /* the lines, their tokens, and their grammar states at their ends, of the last highlighting:
131
+ an edit re-tokenizes only from its first changed line on, until a line of the unchanged
132
+ rest ends in the same grammar state as before, so a keystroke costs only a few lines */
133
+ let cache: { lines: string[], tokens: LineTokens[], ends: GrammarState[] } = { lines: [], tokens: [], ends: [] }
134
+ return (value) => {
135
+ /* determine the unchanged leading and trailing lines */
136
+ const lines = value.split("\n")
137
+ const old = cache
138
+ let d = 0
139
+ while (d < lines.length && d < old.lines.length && lines[d] === old.lines[d])
140
+ d++
141
+ let s = 0
142
+ while (s < lines.length - d && s < old.lines.length - d
143
+ && lines[lines.length - 1 - s] === old.lines[old.lines.length - 1 - s])
144
+ s++
145
+ const delta = lines.length - old.lines.length
146
+ const tokens = old.tokens.slice(0, d)
147
+ const ends = old.ends.slice(0, d)
148
+
149
+ /* re-tokenize from the first changed line on, until the grammar state converges */
150
+ for (let i = d; i < lines.length; i++) {
151
+ const r = tokenize(lines[i], i > 0 ? ends[i - 1] : undefined)
152
+ tokens.push(r.tokens)
153
+ ends.push(r.end)
154
+ const j = i - delta
155
+ if (i >= lines.length - s && j >= 0 && j < old.ends.length && same(r.end, old.ends[j])) {
156
+ for (let k = j + 1; k < old.ends.length; k++) {
157
+ tokens.push(old.tokens[k])
158
+ ends.push(old.ends[k])
159
+ }
160
+ break
161
+ }
162
+ }
163
+ cache = { lines, tokens, ends }
164
+
165
+ /* the ranges with offsets relative to the text start */
166
+ const ranges: SyntaxRange[] = []
167
+ let off = 0
168
+ for (let l = 0; l < lines.length; l++) {
169
+ for (const t of tokens[l])
170
+ ranges.push({ start: off + t.start, end: off + t.end, label: "syntax", style: t.style })
171
+ off += lines[l].length + 1
172
+ }
173
+ return ranges
174
+ }
175
+ }
176
+
@@ -0,0 +1,205 @@
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
+ /* the line geometry of a text and the text operations of the front end
26
+ (dependency-free: it knows nothing about React, Ink, or any terminal) */
27
+
28
+ /* line geometry of a text */
29
+ export const lineStart = (v: string, o: number) => o <= 0 ? 0 : v.lastIndexOf("\n", o - 1) + 1
30
+ export const lineEnd = (v: string, o: number) => { const e = v.indexOf("\n", o); return e < 0 ? v.length : e }
31
+ export const lineNo = (v: string, o: number) => {
32
+ let n = 0
33
+ const to = Math.min(o, v.length)
34
+ for (let i = v.indexOf("\n"); i >= 0 && i < to; i = v.indexOf("\n", i + 1))
35
+ n++
36
+ return n
37
+ }
38
+ export const lineAt = (v: string, l: number) => {
39
+ let s = 0
40
+ for (let i = 0; i < l; i++) {
41
+ const e = v.indexOf("\n", s)
42
+ if (e < 0)
43
+ break
44
+ s = e + 1
45
+ }
46
+ return s
47
+ }
48
+
49
+ /* conversion between an offset and a [ line, column ] cursor (column clamped to the line) */
50
+ export const toCursor = (v: string, o: number): [ number, number ] => {
51
+ const p = Math.min(o, v.length)
52
+ return [ lineNo(v, p), p - lineStart(v, p) ]
53
+ }
54
+ export const toOffset = (v: string, [ l, c ]: [ number, number ]) => {
55
+ const s = lineAt(v, l)
56
+ return s + Math.max(0, Math.min(c, lineEnd(v, s) - s))
57
+ }
58
+
59
+ /* the text operations which have to agree with the front end drawing and editing the text */
60
+ export interface TextOps {
61
+ /* where the grapheme before resp. after an offset starts resp. ends */
62
+ previous (v: string, o: number): number
63
+ next (v: string, o: number): number
64
+
65
+ /* the start of the word before an offset */
66
+ wordStart (v: string, o: number): number
67
+
68
+ /* the offset one row above or below */
69
+ vertical (v: string, o: number, direction: 1 | -1): number
70
+ }
71
+
72
+ /* character classes (words of letters and digits, identifiers also of underscores),
73
+ and whether the line of an offset is blank */
74
+ export const isWord = (c: string | undefined) => c !== undefined && /[\p{L}\p{N}]/u.test(c)
75
+ export const isIdent = (c: string | undefined) => c !== undefined && /[\p{L}\p{N}_]/u.test(c)
76
+ export const isSpace = (c: string | undefined) => c === " " || c === "\t"
77
+ export const isBlank = (v: string, o: number) => /^[ \t]*$/.test(v.slice(lineStart(v, o), lineEnd(v, o)))
78
+
79
+ /* the end of the word at or after an offset, and the start of the word at or before it */
80
+ export const wordEnd = (v: string, o: number, word = isWord) => {
81
+ let i = o
82
+ while (i < v.length && !word(v[i]))
83
+ i++
84
+ while (i < v.length && word(v[i]))
85
+ i++
86
+ return i
87
+ }
88
+ export const wordBegin = (v: string, o: number, word = isWord) => {
89
+ let i = o
90
+ while (i > 0 && !word(v[i - 1]))
91
+ i--
92
+ while (i > 0 && word(v[i - 1]))
93
+ i--
94
+ return i
95
+ }
96
+
97
+ /* the blank line after resp. before the paragraph of an offset (paragraphs are separated by blank lines) */
98
+ export const paragraphEnd = (v: string, o: number) => {
99
+ let p = lineStart(v, o)
100
+ while (p < v.length && isBlank(v, p))
101
+ p = Math.min(lineEnd(v, p) + 1, v.length)
102
+ while (p < v.length && !isBlank(v, p))
103
+ p = Math.min(lineEnd(v, p) + 1, v.length)
104
+ return p
105
+ }
106
+ export const paragraphBegin = (v: string, o: number) => {
107
+ let p = lineStart(v, o)
108
+ while (p > 0 && isBlank(v, p))
109
+ p = lineStart(v, p - 1)
110
+ while (p > 0 && !isBlank(v, p))
111
+ p = lineStart(v, p - 1)
112
+ return p
113
+ }
114
+
115
+ /* a literal text as a regular expression, matched ignoring case without upper case letters */
116
+ export const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
117
+ export const literalRegExp = (text: string, icase = text === text.toLowerCase()) =>
118
+ new RegExp(escapeRegExp(text), icase ? "gi" : "g")
119
+
120
+ /* the matches of a literal text, the next one from an offset (wrapping around), and the previous
121
+ one starting before an offset (wrapping around), with whether wrapping was necessary */
122
+ export const findNext = (v: string, text: string, from: number, icase?: boolean) => {
123
+ const re = literalRegExp(text, icase)
124
+ re.lastIndex = Math.max(0, from)
125
+ let m = re.exec(v)
126
+ let wrapped = false
127
+ if (m === null) {
128
+ re.lastIndex = 0
129
+ m = re.exec(v)
130
+ wrapped = true
131
+ }
132
+ return m === null ? null : { match: [ m.index, m.index + m[0].length ] as [ number, number ], wrapped }
133
+ }
134
+ export const findPrevious = (v: string, text: string, before: number, icase?: boolean) => {
135
+ const all = [ ...v.matchAll(literalRegExp(text, icase)) ].map((m) => [ m.index, m.index + m[0].length ] as [ number, number ])
136
+ const hit = all.findLast((m) => m[0] < before)
137
+ if (hit !== undefined)
138
+ return { match: hit, wrapped: false }
139
+ const last = all.at(-1)
140
+ return last === undefined ? null : { match: last, wrapped: true }
141
+ }
142
+
143
+ /* whether the line of an offset wraps into multiple rows */
144
+ const isWrapped = (ops: TextOps, v: string, o: number) => {
145
+ const s = lineStart(v, o)
146
+ const e = lineEnd(v, o)
147
+ const t = ops.vertical(v, s, 1)
148
+ return t > s && t < e
149
+ }
150
+
151
+ /* the goal column of a sequence of row moves (null for a wrapped line) */
152
+ export const goalColumn = (ops: TextOps, v: string, o: number) =>
153
+ isWrapped(ops, v, o) ? null : o - lineStart(v, o)
154
+
155
+ /* the offset one row above or below, keeping the goal column between lines which are not wrapped */
156
+ export const rowMove = (ops: TextOps, v: string, o: number, direction: 1 | -1, goal: number | null) => {
157
+ let t = ops.vertical(v, o, direction)
158
+ if (t !== o && goal !== null && lineNo(v, t) !== lineNo(v, o) && !isWrapped(ops, v, t)) {
159
+ const s = lineStart(v, t)
160
+ t = s + Math.min(goal, lineEnd(v, t) - s)
161
+ if (ops.next(v, ops.previous(v, t)) !== t)
162
+ t = ops.previous(v, t)
163
+ }
164
+ return t
165
+ }
166
+
167
+ /* fill the paragraph of an offset to a column, keeping the offset at the same non-blank character
168
+ (the replaced range and its new text, or null on a blank line) */
169
+ export const fillParagraph = (v: string, o: number, column: number) => {
170
+ if (isBlank(v, o))
171
+ return null
172
+ let start = lineStart(v, o)
173
+ while (start > 0 && !isBlank(v, start - 1))
174
+ start = lineStart(v, start - 1)
175
+ let end = lineEnd(v, o)
176
+ while (end < v.length && !isBlank(v, end + 1))
177
+ end = lineEnd(v, end + 1)
178
+ const old = v.slice(start, end)
179
+ const indent = /^[ \t]*/.exec(old)?.[0] ?? ""
180
+ const lines: string[] = []
181
+ let line = ""
182
+ for (const w of old.split(/[ \t\n]+/).filter((x) => x !== "")) {
183
+ if (line !== "" && indent.length + line.length + 1 + w.length > column) {
184
+ lines.push(indent + line)
185
+ line = w
186
+ }
187
+ else
188
+ line = line === "" ? w : line + " " + w
189
+ }
190
+ if (line !== "")
191
+ lines.push(indent + line)
192
+ const text = lines.join("\n")
193
+ let k = v.slice(start, o).replace(/[ \t\n]/g, "").length
194
+ let p = 0
195
+ while (p < text.length && k > 0) {
196
+ if (!/[ \t\n]/.test(text[p]))
197
+ k--
198
+ p++
199
+ }
200
+ if (o < end && !/[ \t\n]/.test(v[o]))
201
+ while (p < text.length && /[ \t\n]/.test(text[p]))
202
+ p++
203
+ return { start, end, text, off: start + p }
204
+ }
205
+