@sunub/obsidian-mcp-server 0.3.1 → 0.3.3

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 (154) hide show
  1. package/build/cli/app.d.ts +1 -0
  2. package/build/cli/app.js +7 -0
  3. package/build/cli/app.js.map +1 -0
  4. package/build/cli/colors.d.ts +15 -0
  5. package/build/cli/colors.js +15 -0
  6. package/build/cli/colors.js.map +1 -0
  7. package/build/cli/commands/types.d.ts +19 -0
  8. package/build/cli/commands/types.js +11 -0
  9. package/build/cli/commands/types.js.map +1 -0
  10. package/build/cli/config/mcpServersConfig.d.ts +15 -3
  11. package/build/cli/config/mcpServersConfig.js +2 -2
  12. package/build/cli/config/mcpServersConfig.js.map +1 -1
  13. package/build/cli/constants.d.ts +47 -0
  14. package/build/cli/constants.js +101 -0
  15. package/build/cli/constants.js.map +1 -0
  16. package/build/cli/hooks/useMcpClient.js +1 -1
  17. package/build/cli/index.d.ts +1 -0
  18. package/build/cli/index.js +16 -4
  19. package/build/cli/index.js.map +1 -1
  20. package/build/cli/key/input.d.ts +5 -0
  21. package/build/cli/key/input.js +9 -0
  22. package/build/cli/key/input.js.map +1 -0
  23. package/build/cli/key/mouse.d.ts +23 -0
  24. package/build/cli/key/mouse.js +155 -0
  25. package/build/cli/key/mouse.js.map +1 -0
  26. package/build/cli/key/text-buffer-bestcase.d.ts +867 -0
  27. package/build/cli/key/text-buffer-bestcase.js +2754 -0
  28. package/build/cli/key/text-buffer-bestcase.js.map +1 -0
  29. package/build/cli/key/text-buffer.d.ts +509 -0
  30. package/build/cli/main.d.ts +1 -0
  31. package/build/cli/main.js +20 -0
  32. package/build/cli/main.js.map +1 -0
  33. package/build/cli/reference/text-buffer.d.ts +867 -0
  34. package/build/cli/reference/text-buffer.js +2754 -0
  35. package/build/cli/reference/text-buffer.js.map +1 -0
  36. package/build/cli/theme/builtin/default-dark.d.ts +7 -0
  37. package/build/cli/theme/builtin/default-dark.js +143 -0
  38. package/build/cli/theme/builtin/default-dark.js.map +1 -0
  39. package/build/cli/theme/builtin/no-color.d.ts +7 -0
  40. package/build/cli/theme/builtin/no-color.js +125 -0
  41. package/build/cli/theme/builtin/no-color.js.map +1 -0
  42. package/build/cli/theme/builtin/tokyonight-dark.d.ts +7 -0
  43. package/build/cli/theme/builtin/tokyonight-dark.js +146 -0
  44. package/build/cli/theme/builtin/tokyonight-dark.js.map +1 -0
  45. package/build/cli/theme/semantic-colors.d.ts +2 -0
  46. package/build/cli/theme/semantic-colors.js +19 -0
  47. package/build/cli/theme/semantic-colors.js.map +1 -0
  48. package/build/cli/theme/semantic-tokens.d.ts +42 -0
  49. package/build/cli/theme/semantic-tokens.js +77 -0
  50. package/build/cli/theme/semantic-tokens.js.map +1 -0
  51. package/build/cli/theme/theme-manager.d.ts +32 -0
  52. package/build/cli/theme/theme-manager.js +150 -0
  53. package/build/cli/theme/theme-manager.js.map +1 -0
  54. package/build/cli/theme/theme.d.ts +107 -0
  55. package/build/cli/theme/theme.js +333 -0
  56. package/build/cli/theme/theme.js.map +1 -0
  57. package/build/cli/tmp.d.ts +1 -0
  58. package/build/cli/types.d.ts +72 -0
  59. package/build/cli/types.js +8 -0
  60. package/build/cli/types.js.map +1 -0
  61. package/build/cli/utils/cache.d.ts +21 -0
  62. package/build/cli/utils/cache.js +56 -0
  63. package/build/cli/utils/cache.js.map +1 -0
  64. package/build/cli/utils/debugLogger.js +5 -5
  65. package/build/cli/utils/debugLogger.js.map +1 -1
  66. package/build/config.d.ts +30 -0
  67. package/build/config.js +81 -0
  68. package/build/config.js.map +1 -0
  69. package/build/db.d.ts +1 -0
  70. package/build/index.d.ts +2 -0
  71. package/build/index.js +4 -2
  72. package/build/index.js.map +1 -1
  73. package/build/server.d.ts +2 -0
  74. package/build/server.js +39 -0
  75. package/build/server.js.map +1 -0
  76. package/build/tools/create_document_with_properties/index.js +1 -1
  77. package/build/tools/create_document_with_properties/params.d.ts +3 -3
  78. package/build/tools/create_document_with_properties/params.js +33 -0
  79. package/build/tools/create_document_with_properties/params.js.map +1 -0
  80. package/build/tools/generate_property/index.d.ts +34 -0
  81. package/build/tools/generate_property/params.d.ts +48 -0
  82. package/build/tools/generate_property/params.js +55 -0
  83. package/build/tools/generate_property/params.js.map +1 -0
  84. package/build/tools/index.js +13 -0
  85. package/build/tools/index.js.map +1 -0
  86. package/build/tools/organize_attachments/index.d.ts +32 -0
  87. package/build/tools/organize_attachments/index.js +1 -1
  88. package/build/tools/organize_attachments/params.d.ts +16 -16
  89. package/build/tools/organize_attachments/params.js +61 -0
  90. package/build/tools/organize_attachments/params.js.map +1 -0
  91. package/build/tools/organize_attachments/utils.d.ts +22 -0
  92. package/build/tools/organize_attachments/utils.js +66 -0
  93. package/build/tools/organize_attachments/utils.js.map +1 -0
  94. package/build/tools/vault/index.d.ts +50 -0
  95. package/build/tools/vault/index.js +1 -1
  96. package/build/tools/vault/metrics.d.ts +25 -0
  97. package/build/tools/vault/metrics.js +130 -0
  98. package/build/tools/vault/metrics.js.map +1 -0
  99. package/build/tools/vault/params.d.ts +12 -12
  100. package/build/tools/vault/params.js +148 -0
  101. package/build/tools/vault/params.js.map +1 -0
  102. package/build/tools/vault/types/collect_context.d.ts +249 -249
  103. package/build/tools/vault/types/collect_context.js +103 -0
  104. package/build/tools/vault/types/collect_context.js.map +1 -0
  105. package/build/tools/vault/types/list_all.d.ts +14 -14
  106. package/build/tools/vault/types/list_all.js +53 -0
  107. package/build/tools/vault/types/list_all.js.map +1 -0
  108. package/build/tools/vault/types/read_specific.d.ts +18 -18
  109. package/build/tools/vault/types/read_specific.js +41 -0
  110. package/build/tools/vault/types/read_specific.js.map +1 -0
  111. package/build/tools/vault/types/search.d.ts +22 -22
  112. package/build/tools/vault/types/search.js +59 -0
  113. package/build/tools/vault/types/search.js.map +1 -0
  114. package/build/tools/vault/utils/actions/collect_context.d.ts +4 -0
  115. package/build/tools/vault/utils/actions/index_rag.d.ts +2 -0
  116. package/build/tools/vault/utils/actions/index_rag.js +1 -1
  117. package/build/tools/vault/utils/actions/list_all.d.ts +4 -0
  118. package/build/tools/vault/utils/actions/load_memory.d.ts +4 -0
  119. package/build/tools/vault/utils/actions/read.d.ts +4 -0
  120. package/build/tools/vault/utils/actions/search.d.ts +4 -0
  121. package/build/tools/vault/utils/actions/search_semantic.d.ts +3 -0
  122. package/build/tools/vault/utils/actions/search_semantic.js +23 -6
  123. package/build/tools/vault/utils/actions/search_semantic.js.map +1 -1
  124. package/build/tools/vault/utils/actions/stats.d.ts +3 -0
  125. package/build/tools/vault/utils/constants.d.ts +2 -0
  126. package/build/tools/vault/utils/constants.js +3 -0
  127. package/build/tools/vault/utils/constants.js.map +1 -0
  128. package/build/tools/vault/utils/document.d.ts +35 -0
  129. package/build/tools/vault/utils/shared.d.ts +29 -0
  130. package/build/tools/vault/utils/shared.js +75 -0
  131. package/build/tools/vault/utils/shared.js.map +1 -0
  132. package/build/tools/vault/utils.d.ts +8 -0
  133. package/build/tools/vault/utils.js +9 -0
  134. package/build/tools/vault/utils.js.map +1 -0
  135. package/build/tools/write_property/index.js +1 -1
  136. package/build/tools/write_property/params.d.ts +60 -0
  137. package/build/tools/write_property/params.js +52 -0
  138. package/build/tools/write_property/params.js.map +1 -0
  139. package/build/utils/LLMClient.d.ts +1 -3
  140. package/build/utils/LLMClient.js +18 -4
  141. package/build/utils/LLMClient.js.map +1 -1
  142. package/build/utils/RerankerClient.d.ts +38 -4
  143. package/build/utils/RerankerClient.js +2 -1
  144. package/build/utils/RerankerClient.js.map +1 -1
  145. package/build/utils/VaultWatcher.js +35 -28
  146. package/build/utils/VaultWatcher.js.map +1 -1
  147. package/build/utils/getVaultManager.js +1 -1
  148. package/build/utils/processor/types.d.ts +2 -2
  149. package/build/utils/processor/types.js +21 -0
  150. package/build/utils/processor/types.js.map +1 -0
  151. package/build/utils/semaphore.d.ts +7 -0
  152. package/build/utils/semaphore.js +26 -0
  153. package/build/utils/semaphore.js.map +1 -0
  154. package/package.json +3 -2
@@ -0,0 +1,2754 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * @license
4
+ * Copyright 2025 Google LLC
5
+ * SPDX-License-Identifier: Apache-2.0
6
+ */
7
+ import fs from "node:fs";
8
+ import os from "node:os";
9
+ import pathMod, * as path from "node:path";
10
+ import { coreEvents, debugLogger, unescapePath, } from "@google/gemini-cli-core";
11
+ import { LRUCache } from "mnemonist";
12
+ import { useCallback, useEffect, useMemo, useReducer, useState } from "react";
13
+ import { LRU_BUFFER_PERF_CACHE_LIMIT } from "../../constants.js";
14
+ import { useKeyMatchers } from "../../hooks/useKeyMatchers.js";
15
+ import { Command } from "../../key/keyMatchers.js";
16
+ import { parsePastedPaths } from "../../utils/clipboardUtils.js";
17
+ import { openFileInEditor } from "../../utils/editorUtils.js";
18
+ import { cpLen, cpSlice, getCachedStringWidth, stripUnsafeCharacters, toCodePoints, } from "../../utils/textUtils.js";
19
+ import { handleVimAction } from "./vim-buffer-actions.js";
20
+ export const LARGE_PASTE_LINE_THRESHOLD = 5;
21
+ export const LARGE_PASTE_CHAR_THRESHOLD = 500;
22
+ // Regex to match paste placeholders like [Pasted Text: 6 lines] or [Pasted Text: 501 chars #2]
23
+ export const PASTED_TEXT_PLACEHOLDER_REGEX = /\[Pasted Text: \d+ (?:lines|chars)(?: #\d+)?\]/g;
24
+ // Replace paste placeholder strings with their actual pasted content.
25
+ export function expandPastePlaceholders(text, pastedContent) {
26
+ return text.replace(PASTED_TEXT_PLACEHOLDER_REGEX, (match) => pastedContent[match] || match);
27
+ }
28
+ // Helper functions for line-based word navigation
29
+ export const isWordCharStrict = (char) => /[\w\p{L}\p{N}]/u.test(char); // Matches a single character that is any Unicode letter, any Unicode number, or an underscore
30
+ export const isWhitespace = (char) => /\s/.test(char);
31
+ // Check if a character is a combining mark (only diacritics for now)
32
+ export const isCombiningMark = (char) => /\p{M}/u.test(char);
33
+ // Check if a character should be considered part of a word (including combining marks)
34
+ export const isWordCharWithCombining = (char) => isWordCharStrict(char) || isCombiningMark(char);
35
+ // Get the script of a character (simplified for common scripts)
36
+ export const getCharScript = (char) => {
37
+ if (/[\p{Script=Latin}]/u.test(char))
38
+ return "latin"; // All Latin script chars including diacritics
39
+ if (/[\p{Script=Han}]/u.test(char))
40
+ return "han"; // Chinese
41
+ if (/[\p{Script=Arabic}]/u.test(char))
42
+ return "arabic";
43
+ if (/[\p{Script=Hiragana}]/u.test(char))
44
+ return "hiragana";
45
+ if (/[\p{Script=Katakana}]/u.test(char))
46
+ return "katakana";
47
+ if (/[\p{Script=Cyrillic}]/u.test(char))
48
+ return "cyrillic";
49
+ return "other";
50
+ };
51
+ // Check if two characters are from different scripts (indicating word boundary)
52
+ export const isDifferentScript = (char1, char2) => {
53
+ if (!isWordCharStrict(char1) || !isWordCharStrict(char2))
54
+ return false;
55
+ return getCharScript(char1) !== getCharScript(char2);
56
+ };
57
+ // Find next word start within a line, starting from col
58
+ export const findNextWordStartInLine = (line, col) => {
59
+ const chars = toCodePoints(line);
60
+ let i = col;
61
+ if (i >= chars.length)
62
+ return null;
63
+ const currentChar = chars[i];
64
+ // Skip current word/sequence based on character type
65
+ if (isWordCharStrict(currentChar)) {
66
+ while (i < chars.length && isWordCharWithCombining(chars[i])) {
67
+ // Check for script boundary - if next character is from different script, stop here
68
+ if (i + 1 < chars.length &&
69
+ isWordCharStrict(chars[i + 1]) &&
70
+ isDifferentScript(chars[i], chars[i + 1])) {
71
+ i++; // Include current character
72
+ break; // Stop at script boundary
73
+ }
74
+ i++;
75
+ }
76
+ }
77
+ else if (!isWhitespace(currentChar)) {
78
+ while (i < chars.length &&
79
+ !isWordCharStrict(chars[i]) &&
80
+ !isWhitespace(chars[i])) {
81
+ i++;
82
+ }
83
+ }
84
+ // Skip whitespace
85
+ while (i < chars.length && isWhitespace(chars[i])) {
86
+ i++;
87
+ }
88
+ return i < chars.length ? i : null;
89
+ };
90
+ // Find previous word start within a line
91
+ export const findPrevWordStartInLine = (line, col) => {
92
+ const chars = toCodePoints(line);
93
+ let i = col;
94
+ if (i <= 0)
95
+ return null;
96
+ i--;
97
+ // Skip whitespace moving backwards
98
+ while (i >= 0 && isWhitespace(chars[i])) {
99
+ i--;
100
+ }
101
+ if (i < 0)
102
+ return null;
103
+ if (isWordCharStrict(chars[i])) {
104
+ // We're in a word, move to its beginning
105
+ while (i >= 0 && isWordCharStrict(chars[i])) {
106
+ // Check for script boundary - if previous character is from different script, stop here
107
+ if (i - 1 >= 0 &&
108
+ isWordCharStrict(chars[i - 1]) &&
109
+ isDifferentScript(chars[i], chars[i - 1])) {
110
+ return i; // Return current position at script boundary
111
+ }
112
+ i--;
113
+ }
114
+ return i + 1;
115
+ }
116
+ else {
117
+ // We're in punctuation, move to its beginning
118
+ while (i >= 0 && !isWordCharStrict(chars[i]) && !isWhitespace(chars[i])) {
119
+ i--;
120
+ }
121
+ return i + 1;
122
+ }
123
+ };
124
+ // Find word end within a line
125
+ export const findWordEndInLine = (line, col) => {
126
+ const chars = toCodePoints(line);
127
+ let i = col;
128
+ // If we're already at the end of a word (including punctuation sequences), advance to next word
129
+ // This includes both regular word endings and script boundaries
130
+ let nextBaseCharIdx = i + 1;
131
+ while (nextBaseCharIdx < chars.length &&
132
+ isCombiningMark(chars[nextBaseCharIdx])) {
133
+ nextBaseCharIdx++;
134
+ }
135
+ const atEndOfWordChar = i < chars.length &&
136
+ isWordCharWithCombining(chars[i]) &&
137
+ (nextBaseCharIdx >= chars.length ||
138
+ !isWordCharStrict(chars[nextBaseCharIdx]) ||
139
+ (isWordCharStrict(chars[i]) &&
140
+ isDifferentScript(chars[i], chars[nextBaseCharIdx])));
141
+ const atEndOfPunctuation = i < chars.length &&
142
+ !isWordCharWithCombining(chars[i]) &&
143
+ !isWhitespace(chars[i]) &&
144
+ (i + 1 >= chars.length ||
145
+ isWhitespace(chars[i + 1]) ||
146
+ isWordCharWithCombining(chars[i + 1]));
147
+ if (atEndOfWordChar || atEndOfPunctuation) {
148
+ // We're at the end of a word or punctuation sequence, move forward to find next word
149
+ i++;
150
+ // Skip any combining marks that belong to the word we just finished
151
+ while (i < chars.length && isCombiningMark(chars[i])) {
152
+ i++;
153
+ }
154
+ // Skip whitespace to find next word or punctuation
155
+ while (i < chars.length && isWhitespace(chars[i])) {
156
+ i++;
157
+ }
158
+ }
159
+ // If we're not on a word character, find the next word or punctuation sequence
160
+ if (i < chars.length && !isWordCharWithCombining(chars[i])) {
161
+ // Skip whitespace to find next word or punctuation
162
+ while (i < chars.length && isWhitespace(chars[i])) {
163
+ i++;
164
+ }
165
+ }
166
+ // Move to end of current word (including combining marks, but stop at script boundaries)
167
+ let foundWord = false;
168
+ let lastBaseCharPos = -1;
169
+ if (i < chars.length && isWordCharWithCombining(chars[i])) {
170
+ // Handle word characters
171
+ while (i < chars.length && isWordCharWithCombining(chars[i])) {
172
+ foundWord = true;
173
+ // Track the position of the last base character (not combining mark)
174
+ if (isWordCharStrict(chars[i])) {
175
+ lastBaseCharPos = i;
176
+ }
177
+ // Check if next character is from a different script (word boundary)
178
+ if (i + 1 < chars.length &&
179
+ isWordCharStrict(chars[i + 1]) &&
180
+ isDifferentScript(chars[i], chars[i + 1])) {
181
+ i++; // Include current character
182
+ if (isWordCharStrict(chars[i - 1])) {
183
+ lastBaseCharPos = i - 1;
184
+ }
185
+ break; // Stop at script boundary
186
+ }
187
+ i++;
188
+ }
189
+ }
190
+ else if (i < chars.length && !isWhitespace(chars[i])) {
191
+ // Handle punctuation sequences (like ████)
192
+ while (i < chars.length &&
193
+ !isWordCharStrict(chars[i]) &&
194
+ !isWhitespace(chars[i])) {
195
+ foundWord = true;
196
+ lastBaseCharPos = i;
197
+ i++;
198
+ }
199
+ }
200
+ // Only return a position if we actually found a word
201
+ // Return the position of the last base character, not combining marks
202
+ if (foundWord && lastBaseCharPos >= col) {
203
+ return lastBaseCharPos;
204
+ }
205
+ return null;
206
+ };
207
+ // Find next big word start within a line (W)
208
+ export const findNextBigWordStartInLine = (line, col) => {
209
+ const chars = toCodePoints(line);
210
+ let i = col;
211
+ if (i >= chars.length)
212
+ return null;
213
+ // If currently on non-whitespace, skip it
214
+ if (!isWhitespace(chars[i])) {
215
+ while (i < chars.length && !isWhitespace(chars[i])) {
216
+ i++;
217
+ }
218
+ }
219
+ // Skip whitespace
220
+ while (i < chars.length && isWhitespace(chars[i])) {
221
+ i++;
222
+ }
223
+ return i < chars.length ? i : null;
224
+ };
225
+ // Find previous big word start within a line (B)
226
+ export const findPrevBigWordStartInLine = (line, col) => {
227
+ const chars = toCodePoints(line);
228
+ let i = col;
229
+ if (i <= 0)
230
+ return null;
231
+ i--;
232
+ // Skip whitespace moving backwards
233
+ while (i >= 0 && isWhitespace(chars[i])) {
234
+ i--;
235
+ }
236
+ if (i < 0)
237
+ return null;
238
+ // We're in a big word, move to its beginning
239
+ while (i >= 0 && !isWhitespace(chars[i])) {
240
+ i--;
241
+ }
242
+ return i + 1;
243
+ };
244
+ // Find big word end within a line (E)
245
+ export const findBigWordEndInLine = (line, col) => {
246
+ const chars = toCodePoints(line);
247
+ let i = col;
248
+ // If we're already at the end of a big word, advance to next
249
+ const atEndOfBigWord = i < chars.length &&
250
+ !isWhitespace(chars[i]) &&
251
+ (i + 1 >= chars.length || isWhitespace(chars[i + 1]));
252
+ if (atEndOfBigWord) {
253
+ i++;
254
+ }
255
+ // Skip whitespace
256
+ while (i < chars.length && isWhitespace(chars[i])) {
257
+ i++;
258
+ }
259
+ // Move to end of current big word
260
+ if (i < chars.length && !isWhitespace(chars[i])) {
261
+ while (i < chars.length && !isWhitespace(chars[i])) {
262
+ i++;
263
+ }
264
+ return i - 1;
265
+ }
266
+ return null;
267
+ };
268
+ // Initialize segmenter for word boundary detection
269
+ const segmenter = new Intl.Segmenter(undefined, { granularity: "word" });
270
+ function findPrevWordBoundary(line, cursorCol) {
271
+ const codePoints = toCodePoints(line);
272
+ // Convert cursorCol (CP index) to string index
273
+ const prefix = codePoints.slice(0, cursorCol).join("");
274
+ const cursorIdx = prefix.length;
275
+ let targetIdx = 0;
276
+ for (const seg of segmenter.segment(line)) {
277
+ // We want the last word start strictly before the cursor.
278
+ // If we've reached or passed the cursor, we stop.
279
+ if (seg.index >= cursorIdx)
280
+ break;
281
+ if (seg.isWordLike) {
282
+ targetIdx = seg.index;
283
+ }
284
+ }
285
+ return toCodePoints(line.slice(0, targetIdx)).length;
286
+ }
287
+ function findNextWordBoundary(line, cursorCol) {
288
+ const codePoints = toCodePoints(line);
289
+ const prefix = codePoints.slice(0, cursorCol).join("");
290
+ const cursorIdx = prefix.length;
291
+ let targetIdx = line.length;
292
+ for (const seg of segmenter.segment(line)) {
293
+ const segEnd = seg.index + seg.segment.length;
294
+ if (segEnd > cursorIdx) {
295
+ if (seg.isWordLike) {
296
+ targetIdx = segEnd;
297
+ break;
298
+ }
299
+ }
300
+ }
301
+ return toCodePoints(line.slice(0, targetIdx)).length;
302
+ }
303
+ // Find next word across lines
304
+ export const findNextWordAcrossLines = (lines, cursorRow, cursorCol, searchForWordStart) => {
305
+ // First try current line
306
+ const currentLine = lines[cursorRow] || "";
307
+ const colInCurrentLine = searchForWordStart
308
+ ? findNextWordStartInLine(currentLine, cursorCol)
309
+ : findWordEndInLine(currentLine, cursorCol);
310
+ if (colInCurrentLine !== null) {
311
+ return { row: cursorRow, col: colInCurrentLine };
312
+ }
313
+ let firstEmptyRow = null;
314
+ // Search subsequent lines
315
+ for (let row = cursorRow + 1; row < lines.length; row++) {
316
+ const line = lines[row] || "";
317
+ const chars = toCodePoints(line);
318
+ // For empty lines, if we haven't found any words yet, remember the first empty line
319
+ if (chars.length === 0) {
320
+ if (firstEmptyRow === null) {
321
+ firstEmptyRow = row;
322
+ }
323
+ continue;
324
+ }
325
+ // Find first non-whitespace
326
+ let firstNonWhitespace = 0;
327
+ while (firstNonWhitespace < chars.length &&
328
+ isWhitespace(chars[firstNonWhitespace])) {
329
+ firstNonWhitespace++;
330
+ }
331
+ if (firstNonWhitespace < chars.length) {
332
+ if (searchForWordStart) {
333
+ return { row, col: firstNonWhitespace };
334
+ }
335
+ else {
336
+ // For word end, find the end of the first word
337
+ const endCol = findWordEndInLine(line, firstNonWhitespace);
338
+ if (endCol !== null) {
339
+ return { row, col: endCol };
340
+ }
341
+ }
342
+ }
343
+ }
344
+ // If no words in later lines, return the first empty line we found
345
+ if (firstEmptyRow !== null) {
346
+ return { row: firstEmptyRow, col: 0 };
347
+ }
348
+ return null;
349
+ };
350
+ // Find previous word across lines
351
+ export const findPrevWordAcrossLines = (lines, cursorRow, cursorCol) => {
352
+ // First try current line
353
+ const currentLine = lines[cursorRow] || "";
354
+ const colInCurrentLine = findPrevWordStartInLine(currentLine, cursorCol);
355
+ if (colInCurrentLine !== null) {
356
+ return { row: cursorRow, col: colInCurrentLine };
357
+ }
358
+ // Search previous lines
359
+ for (let row = cursorRow - 1; row >= 0; row--) {
360
+ const line = lines[row] || "";
361
+ const chars = toCodePoints(line);
362
+ if (chars.length === 0)
363
+ continue;
364
+ // Find last word start
365
+ let lastWordStart = chars.length;
366
+ while (lastWordStart > 0 && isWhitespace(chars[lastWordStart - 1])) {
367
+ lastWordStart--;
368
+ }
369
+ if (lastWordStart > 0) {
370
+ // Find start of this word
371
+ const wordStart = findPrevWordStartInLine(line, lastWordStart);
372
+ if (wordStart !== null) {
373
+ return { row, col: wordStart };
374
+ }
375
+ }
376
+ }
377
+ return null;
378
+ };
379
+ // Find next big word across lines
380
+ export const findNextBigWordAcrossLines = (lines, cursorRow, cursorCol, searchForWordStart) => {
381
+ // First try current line
382
+ const currentLine = lines[cursorRow] || "";
383
+ const colInCurrentLine = searchForWordStart
384
+ ? findNextBigWordStartInLine(currentLine, cursorCol)
385
+ : findBigWordEndInLine(currentLine, cursorCol);
386
+ if (colInCurrentLine !== null) {
387
+ return { row: cursorRow, col: colInCurrentLine };
388
+ }
389
+ let firstEmptyRow = null;
390
+ // Search subsequent lines
391
+ for (let row = cursorRow + 1; row < lines.length; row++) {
392
+ const line = lines[row] || "";
393
+ const chars = toCodePoints(line);
394
+ // For empty lines, if we haven't found any words yet, remember the first empty line
395
+ if (chars.length === 0) {
396
+ if (firstEmptyRow === null) {
397
+ firstEmptyRow = row;
398
+ }
399
+ continue;
400
+ }
401
+ // Find first non-whitespace
402
+ let firstNonWhitespace = 0;
403
+ while (firstNonWhitespace < chars.length &&
404
+ isWhitespace(chars[firstNonWhitespace])) {
405
+ firstNonWhitespace++;
406
+ }
407
+ if (firstNonWhitespace < chars.length) {
408
+ // Found a non-whitespace character (start of a big word)
409
+ if (searchForWordStart) {
410
+ return { row, col: firstNonWhitespace };
411
+ }
412
+ else {
413
+ const endCol = findBigWordEndInLine(line, firstNonWhitespace);
414
+ if (endCol !== null) {
415
+ return { row, col: endCol };
416
+ }
417
+ }
418
+ }
419
+ }
420
+ // If no words in later lines, return the first empty line we found
421
+ if (firstEmptyRow !== null) {
422
+ return { row: firstEmptyRow, col: 0 };
423
+ }
424
+ return null;
425
+ };
426
+ // Find previous big word across lines
427
+ export const findPrevBigWordAcrossLines = (lines, cursorRow, cursorCol) => {
428
+ // First try current line
429
+ const currentLine = lines[cursorRow] || "";
430
+ const colInCurrentLine = findPrevBigWordStartInLine(currentLine, cursorCol);
431
+ if (colInCurrentLine !== null) {
432
+ return { row: cursorRow, col: colInCurrentLine };
433
+ }
434
+ // Search previous lines
435
+ for (let row = cursorRow - 1; row >= 0; row--) {
436
+ const line = lines[row] || "";
437
+ const chars = toCodePoints(line);
438
+ if (chars.length === 0)
439
+ continue;
440
+ // Find last big word start
441
+ let lastWordStart = chars.length;
442
+ while (lastWordStart > 0 && isWhitespace(chars[lastWordStart - 1])) {
443
+ lastWordStart--;
444
+ }
445
+ if (lastWordStart > 0) {
446
+ const wordStart = findPrevBigWordStartInLine(line, lastWordStart);
447
+ if (wordStart !== null) {
448
+ return { row, col: wordStart };
449
+ }
450
+ }
451
+ }
452
+ return null;
453
+ };
454
+ // Helper functions for vim line operations
455
+ export const getPositionFromOffsets = (startOffset, endOffset, lines) => {
456
+ let offset = 0;
457
+ let startRow = 0;
458
+ let startCol = 0;
459
+ let endRow = 0;
460
+ let endCol = 0;
461
+ // Find start position
462
+ for (let i = 0; i < lines.length; i++) {
463
+ const lineLength = lines[i].length + 1; // +1 for newline
464
+ if (offset + lineLength > startOffset) {
465
+ startRow = i;
466
+ startCol = startOffset - offset;
467
+ break;
468
+ }
469
+ offset += lineLength;
470
+ }
471
+ // Find end position
472
+ offset = 0;
473
+ for (let i = 0; i < lines.length; i++) {
474
+ const lineLength = lines[i].length + (i < lines.length - 1 ? 1 : 0); // +1 for newline except last line
475
+ if (offset + lineLength >= endOffset) {
476
+ endRow = i;
477
+ endCol = endOffset - offset;
478
+ break;
479
+ }
480
+ offset += lineLength;
481
+ }
482
+ return { startRow, startCol, endRow, endCol };
483
+ };
484
+ export const getLineRangeOffsets = (startRow, lineCount, lines) => {
485
+ let startOffset = 0;
486
+ // Calculate start offset
487
+ for (let i = 0; i < startRow; i++) {
488
+ startOffset += lines[i].length + 1; // +1 for newline
489
+ }
490
+ // Calculate end offset
491
+ let endOffset = startOffset;
492
+ for (let i = 0; i < lineCount; i++) {
493
+ const lineIndex = startRow + i;
494
+ if (lineIndex < lines.length) {
495
+ endOffset += lines[lineIndex].length;
496
+ if (lineIndex < lines.length - 1) {
497
+ endOffset += 1; // +1 for newline
498
+ }
499
+ }
500
+ }
501
+ return { startOffset, endOffset };
502
+ };
503
+ export const replaceRangeInternal = (state, startRow, startCol, endRow, endCol, text) => {
504
+ const currentLine = (row) => state.lines[row] || "";
505
+ const currentLineLen = (row) => cpLen(currentLine(row));
506
+ const clamp = (value, min, max) => Math.min(Math.max(value, min), max);
507
+ if (startRow > endRow ||
508
+ (startRow === endRow && startCol > endCol) ||
509
+ startRow < 0 ||
510
+ startCol < 0 ||
511
+ endRow >= state.lines.length ||
512
+ (endRow < state.lines.length && endCol > currentLineLen(endRow))) {
513
+ return state; // Invalid range
514
+ }
515
+ const newLines = [...state.lines];
516
+ const sCol = clamp(startCol, 0, currentLineLen(startRow));
517
+ const eCol = clamp(endCol, 0, currentLineLen(endRow));
518
+ const prefix = cpSlice(currentLine(startRow), 0, sCol);
519
+ const suffix = cpSlice(currentLine(endRow), eCol);
520
+ const normalisedReplacement = text
521
+ .replace(/\r\n/g, "\n")
522
+ .replace(/\r/g, "\n");
523
+ const replacementParts = normalisedReplacement.split("\n");
524
+ // The combined first line of the new text
525
+ const firstLine = prefix + replacementParts[0];
526
+ if (replacementParts.length === 1) {
527
+ // No newlines in replacement: combine prefix, replacement, and suffix on one line.
528
+ newLines.splice(startRow, endRow - startRow + 1, firstLine + suffix);
529
+ }
530
+ else {
531
+ // Newlines in replacement: create new lines.
532
+ const lastLine = replacementParts[replacementParts.length - 1] + suffix;
533
+ const middleLines = replacementParts.slice(1, -1);
534
+ newLines.splice(startRow, endRow - startRow + 1, firstLine, ...middleLines, lastLine);
535
+ }
536
+ const finalCursorRow = startRow + replacementParts.length - 1;
537
+ const finalCursorCol = (replacementParts.length > 1 ? 0 : sCol) +
538
+ cpLen(replacementParts[replacementParts.length - 1]);
539
+ return {
540
+ ...state,
541
+ lines: newLines,
542
+ cursorRow: Math.min(Math.max(finalCursorRow, 0), newLines.length - 1),
543
+ cursorCol: Math.max(0, Math.min(finalCursorCol, cpLen(newLines[finalCursorRow] || ""))),
544
+ preferredCol: null,
545
+ };
546
+ };
547
+ function clamp(v, min, max) {
548
+ return v < min ? min : v > max ? max : v;
549
+ }
550
+ function calculateInitialCursorPosition(initialLines, offset) {
551
+ let remainingChars = offset;
552
+ let row = 0;
553
+ while (row < initialLines.length) {
554
+ const lineLength = cpLen(initialLines[row]);
555
+ // Add 1 for the newline character (except for the last line)
556
+ const totalCharsInLineAndNewline = lineLength + (row < initialLines.length - 1 ? 1 : 0);
557
+ if (remainingChars <= lineLength) {
558
+ // Cursor is on this line
559
+ return [row, remainingChars];
560
+ }
561
+ remainingChars -= totalCharsInLineAndNewline;
562
+ row++;
563
+ }
564
+ // Offset is beyond the text, place cursor at the end of the last line
565
+ if (initialLines.length > 0) {
566
+ const lastRow = initialLines.length - 1;
567
+ return [lastRow, cpLen(initialLines[lastRow])];
568
+ }
569
+ return [0, 0]; // Default for empty text
570
+ }
571
+ export function offsetToLogicalPos(text, offset) {
572
+ let row = 0;
573
+ let col = 0;
574
+ let currentOffset = 0;
575
+ if (offset === 0)
576
+ return [0, 0];
577
+ const lines = text.split("\n");
578
+ for (let i = 0; i < lines.length; i++) {
579
+ const line = lines[i];
580
+ const lineLength = cpLen(line);
581
+ const lineLengthWithNewline = lineLength + (i < lines.length - 1 ? 1 : 0);
582
+ if (offset <= currentOffset + lineLength) {
583
+ // Check against lineLength first
584
+ row = i;
585
+ col = offset - currentOffset;
586
+ return [row, col];
587
+ }
588
+ else if (offset <= currentOffset + lineLengthWithNewline) {
589
+ // Check if offset is the newline itself
590
+ row = i;
591
+ col = lineLength; // Position cursor at the end of the current line content
592
+ // If the offset IS the newline, and it's not the last line, advance to next line, col 0
593
+ if (offset === currentOffset + lineLengthWithNewline &&
594
+ i < lines.length - 1) {
595
+ return [i + 1, 0];
596
+ }
597
+ return [row, col]; // Otherwise, it's at the end of the current line content
598
+ }
599
+ currentOffset += lineLengthWithNewline;
600
+ }
601
+ // If offset is beyond the text length, place cursor at the end of the last line
602
+ // or [0,0] if text is empty
603
+ if (lines.length > 0) {
604
+ row = lines.length - 1;
605
+ col = cpLen(lines[row]);
606
+ }
607
+ else {
608
+ row = 0;
609
+ col = 0;
610
+ }
611
+ return [row, col];
612
+ }
613
+ /**
614
+ * Converts logical row/col position to absolute text offset
615
+ * Inverse operation of offsetToLogicalPos
616
+ */
617
+ export function logicalPosToOffset(lines, row, col) {
618
+ let offset = 0;
619
+ // Clamp row to valid range
620
+ const actualRow = Math.min(row, lines.length - 1);
621
+ // Add lengths of all lines before the target row
622
+ for (let i = 0; i < actualRow; i++) {
623
+ offset += cpLen(lines[i]) + 1; // +1 for newline
624
+ }
625
+ // Add column offset within the target row
626
+ if (actualRow >= 0 && actualRow < lines.length) {
627
+ offset += Math.min(col, cpLen(lines[actualRow]));
628
+ }
629
+ return offset;
630
+ }
631
+ export const imagePathRegex = /@((?:\\.|[^\s\r\n\\])+?\.(?:png|jpg|jpeg|gif|webp|svg|bmp))\b/gi;
632
+ export function getTransformedImagePath(filePath) {
633
+ const raw = filePath;
634
+ // Ignore leading @ when stripping directories, but keep it for simple '@file.png'
635
+ const withoutAt = raw.startsWith("@") ? raw.slice(1) : raw;
636
+ // Unescape the path to handle escaped spaces and other characters
637
+ const unescaped = unescapePath(withoutAt);
638
+ // Find last directory separator, supporting both POSIX and Windows styles
639
+ const lastSepIndex = Math.max(unescaped.lastIndexOf("/"), unescaped.lastIndexOf("\\"));
640
+ // If we saw a separator, take the segment after it; otherwise fall back to the unescaped string
641
+ const fileName = lastSepIndex >= 0 ? unescaped.slice(lastSepIndex + 1) : unescaped;
642
+ const extension = path.extname(fileName);
643
+ const baseName = path.basename(fileName, extension);
644
+ const maxBaseLength = 10;
645
+ const truncatedBase = baseName.length > maxBaseLength
646
+ ? `...${baseName.slice(-maxBaseLength)}`
647
+ : baseName;
648
+ return `[Image ${truncatedBase}${extension}]`;
649
+ }
650
+ const transformationsCache = new LRUCache(LRU_BUFFER_PERF_CACHE_LIMIT);
651
+ export function calculateTransformationsForLine(line) {
652
+ const cached = transformationsCache.get(line);
653
+ if (cached) {
654
+ return cached;
655
+ }
656
+ const transformations = [];
657
+ // 1. Detect image paths
658
+ imagePathRegex.lastIndex = 0;
659
+ let match;
660
+ while ((match = imagePathRegex.exec(line)) !== null) {
661
+ const logicalText = match[0];
662
+ const logStart = cpLen(line.substring(0, match.index));
663
+ const logEnd = logStart + cpLen(logicalText);
664
+ transformations.push({
665
+ logStart,
666
+ logEnd,
667
+ logicalText,
668
+ collapsedText: getTransformedImagePath(logicalText),
669
+ type: "image",
670
+ });
671
+ }
672
+ // 2. Detect paste placeholders
673
+ const pasteRegex = new RegExp(PASTED_TEXT_PLACEHOLDER_REGEX.source, "g");
674
+ while ((match = pasteRegex.exec(line)) !== null) {
675
+ const logicalText = match[0];
676
+ const logStart = cpLen(line.substring(0, match.index));
677
+ const logEnd = logStart + cpLen(logicalText);
678
+ transformations.push({
679
+ logStart,
680
+ logEnd,
681
+ logicalText,
682
+ collapsedText: logicalText,
683
+ type: "paste",
684
+ id: logicalText,
685
+ });
686
+ }
687
+ // Sort transformations by logStart to maintain consistency
688
+ transformations.sort((a, b) => a.logStart - b.logStart);
689
+ transformationsCache.set(line, transformations);
690
+ return transformations;
691
+ }
692
+ export function calculateTransformations(lines) {
693
+ return lines.map((ln) => calculateTransformationsForLine(ln));
694
+ }
695
+ export function getTransformUnderCursor(row, col, spansByLine, options = {}) {
696
+ const spans = spansByLine[row];
697
+ if (!spans || spans.length === 0)
698
+ return null;
699
+ for (const span of spans) {
700
+ if (col >= span.logStart &&
701
+ (options.includeEdge ? col <= span.logEnd : col < span.logEnd)) {
702
+ return span;
703
+ }
704
+ if (col < span.logStart)
705
+ break;
706
+ }
707
+ return null;
708
+ }
709
+ /**
710
+ * Check if a line index falls within an expanded paste region.
711
+ * Returns the paste placeholder ID if found, null otherwise.
712
+ */
713
+ export function getExpandedPasteAtLine(lineIndex, expandedPaste) {
714
+ if (expandedPaste &&
715
+ lineIndex >= expandedPaste.startLine &&
716
+ lineIndex < expandedPaste.startLine + expandedPaste.lineCount) {
717
+ return expandedPaste.id;
718
+ }
719
+ return null;
720
+ }
721
+ /**
722
+ * Surgery for expanded paste regions when lines are added or removed.
723
+ * Adjusts startLine indices and detaches any region that is partially or fully deleted.
724
+ */
725
+ export function shiftExpandedRegions(expandedPaste, changeStartLine, lineDelta, changeEndLine) {
726
+ if (!expandedPaste)
727
+ return { newInfo: null, isDetached: false };
728
+ const effectiveEndLine = changeEndLine ?? changeStartLine;
729
+ const infoEndLine = expandedPaste.startLine + expandedPaste.lineCount - 1;
730
+ // 1. Check for overlap/intersection with the changed range
731
+ const isOverlapping = changeStartLine <= infoEndLine &&
732
+ effectiveEndLine >= expandedPaste.startLine;
733
+ if (isOverlapping) {
734
+ // If the change is a deletion (lineDelta < 0) that touches this region, we detach.
735
+ // If it's an insertion, we only detach if it's a multi-line insertion (lineDelta > 0)
736
+ // that isn't at the very start of the region (which would shift it).
737
+ // Regular character typing (lineDelta === 0) does NOT detach.
738
+ if (lineDelta < 0 ||
739
+ (lineDelta > 0 &&
740
+ changeStartLine > expandedPaste.startLine &&
741
+ changeStartLine <= infoEndLine)) {
742
+ return { newInfo: null, isDetached: true };
743
+ }
744
+ }
745
+ // 2. Shift regions that start at or after the change point
746
+ if (expandedPaste.startLine >= changeStartLine) {
747
+ return {
748
+ newInfo: {
749
+ ...expandedPaste,
750
+ startLine: expandedPaste.startLine + lineDelta,
751
+ },
752
+ isDetached: false,
753
+ };
754
+ }
755
+ return { newInfo: expandedPaste, isDetached: false };
756
+ }
757
+ /**
758
+ * Detach any expanded paste region if the cursor is within it.
759
+ * This converts the expanded content to regular text that can no longer be collapsed.
760
+ * Returns the state unchanged if cursor is not in an expanded region.
761
+ */
762
+ export function detachExpandedPaste(state) {
763
+ const expandedId = getExpandedPasteAtLine(state.cursorRow, state.expandedPaste);
764
+ if (!expandedId)
765
+ return state;
766
+ const { [expandedId]: _, ...newPastedContent } = state.pastedContent;
767
+ return {
768
+ ...state,
769
+ expandedPaste: null,
770
+ pastedContent: newPastedContent,
771
+ };
772
+ }
773
+ /**
774
+ * Find atomic placeholder at cursor for backspace (cursor at end).
775
+ * Checks all placeholder types in priority order.
776
+ */
777
+ function findAtomicPlaceholderForBackspace(_line, cursorCol, transformations) {
778
+ for (const transform of transformations) {
779
+ if (cursorCol === transform.logEnd) {
780
+ return {
781
+ start: transform.logStart,
782
+ end: transform.logEnd,
783
+ type: transform.type,
784
+ id: transform.id,
785
+ };
786
+ }
787
+ }
788
+ return null;
789
+ }
790
+ /**
791
+ * Find atomic placeholder at cursor for delete (cursor at start).
792
+ */
793
+ function findAtomicPlaceholderForDelete(_line, cursorCol, transformations) {
794
+ for (const transform of transformations) {
795
+ if (cursorCol === transform.logStart) {
796
+ return {
797
+ start: transform.logStart,
798
+ end: transform.logEnd,
799
+ type: transform.type,
800
+ id: transform.id,
801
+ };
802
+ }
803
+ }
804
+ return null;
805
+ }
806
+ export function calculateTransformedLine(logLine, logIndex, logicalCursor, transformations) {
807
+ let transformedLine = "";
808
+ const transformedToLogMap = [];
809
+ let lastLogPos = 0;
810
+ const cursorIsOnThisLine = logIndex === logicalCursor[0];
811
+ const cursorCol = logicalCursor[1];
812
+ for (const transform of transformations) {
813
+ const textBeforeTransformation = cpSlice(logLine, lastLogPos, transform.logStart);
814
+ transformedLine += textBeforeTransformation;
815
+ for (let i = 0; i < cpLen(textBeforeTransformation); i++) {
816
+ transformedToLogMap.push(lastLogPos + i);
817
+ }
818
+ const isExpanded = transform.type === "image" &&
819
+ cursorIsOnThisLine &&
820
+ cursorCol >= transform.logStart &&
821
+ cursorCol <= transform.logEnd;
822
+ const transformedText = isExpanded
823
+ ? transform.logicalText
824
+ : transform.collapsedText;
825
+ transformedLine += transformedText;
826
+ // Map transformed characters back to logical characters
827
+ const transformedLen = cpLen(transformedText);
828
+ if (isExpanded) {
829
+ for (let i = 0; i < transformedLen; i++) {
830
+ transformedToLogMap.push(transform.logStart + i);
831
+ }
832
+ }
833
+ else {
834
+ // Collapsed: distribute transformed positions monotonically across the raw span.
835
+ // This preserves ordering across wrapped slices so logicalToVisualMap has
836
+ // increasing startColInLogical and visual cursor mapping remains consistent.
837
+ const logicalLength = Math.max(0, transform.logEnd - transform.logStart);
838
+ for (let i = 0; i < transformedLen; i++) {
839
+ // Map the i-th transformed code point into [logStart, logEnd)
840
+ const transformationToLogicalOffset = logicalLength === 0
841
+ ? 0
842
+ : Math.floor((i * logicalLength) / transformedLen);
843
+ const transformationToLogicalIndex = transform.logStart +
844
+ Math.min(transformationToLogicalOffset, Math.max(logicalLength - 1, 0));
845
+ transformedToLogMap.push(transformationToLogicalIndex);
846
+ }
847
+ }
848
+ lastLogPos = transform.logEnd;
849
+ }
850
+ // Append text after last transform
851
+ const remainingUntransformedText = cpSlice(logLine, lastLogPos);
852
+ transformedLine += remainingUntransformedText;
853
+ for (let i = 0; i < cpLen(remainingUntransformedText); i++) {
854
+ transformedToLogMap.push(lastLogPos + i);
855
+ }
856
+ // For a cursor at the very end of the transformed line
857
+ transformedToLogMap.push(cpLen(logLine));
858
+ return { transformedLine, transformedToLogMap };
859
+ }
860
+ const lineLayoutCache = new LRUCache(LRU_BUFFER_PERF_CACHE_LIMIT);
861
+ function getLineLayoutCacheKey(line, viewportWidth, isCursorOnLine, cursorCol) {
862
+ // Most lines (99.9% in a large buffer) are not cursor lines.
863
+ // We use a simpler key for them to reduce string allocation overhead.
864
+ if (!isCursorOnLine) {
865
+ return `${viewportWidth}:N:${line}`;
866
+ }
867
+ return `${viewportWidth}:C:${cursorCol}:${line}`;
868
+ }
869
+ // Calculates the visual wrapping of lines and the mapping between logical and visual coordinates.
870
+ // This is an expensive operation and should be memoized.
871
+ function calculateLayout(logicalLines, viewportWidth, logicalCursor) {
872
+ const visualLines = [];
873
+ const logicalToVisualMap = [];
874
+ const visualToLogicalMap = [];
875
+ const transformedToLogicalMaps = [];
876
+ const visualToTransformedMap = [];
877
+ logicalLines.forEach((logLine, logIndex) => {
878
+ logicalToVisualMap[logIndex] = [];
879
+ const isCursorOnLine = logIndex === logicalCursor[0];
880
+ const cacheKey = getLineLayoutCacheKey(logLine, viewportWidth, isCursorOnLine, logicalCursor[1]);
881
+ const cached = lineLayoutCache.get(cacheKey);
882
+ if (cached) {
883
+ const visualLineOffset = visualLines.length;
884
+ visualLines.push(...cached.visualLines);
885
+ cached.logicalToVisualMap.forEach(([relVisualIdx, logCol]) => {
886
+ logicalToVisualMap[logIndex].push([
887
+ visualLineOffset + relVisualIdx,
888
+ logCol,
889
+ ]);
890
+ });
891
+ cached.visualToLogicalMap.forEach(([, logCol]) => {
892
+ visualToLogicalMap.push([logIndex, logCol]);
893
+ });
894
+ transformedToLogicalMaps[logIndex] = cached.transformedToLogMap;
895
+ visualToTransformedMap.push(...cached.visualToTransformedMap);
896
+ return;
897
+ }
898
+ // Not in cache, calculate
899
+ const transformations = calculateTransformationsForLine(logLine);
900
+ const { transformedLine, transformedToLogMap } = calculateTransformedLine(logLine, logIndex, logicalCursor, transformations);
901
+ const lineVisualLines = [];
902
+ const lineLogicalToVisualMap = [];
903
+ const lineVisualToLogicalMap = [];
904
+ const lineVisualToTransformedMap = [];
905
+ if (transformedLine.length === 0) {
906
+ // Handle empty logical line
907
+ lineLogicalToVisualMap.push([0, 0]);
908
+ lineVisualToLogicalMap.push([logIndex, 0]);
909
+ lineVisualToTransformedMap.push(0);
910
+ lineVisualLines.push("");
911
+ }
912
+ else {
913
+ // Non-empty logical line
914
+ let currentPosInLogLine = 0; // Tracks position within the current logical line (code point index)
915
+ const codePointsInLogLine = toCodePoints(transformedLine);
916
+ while (currentPosInLogLine < codePointsInLogLine.length) {
917
+ let currentChunk = "";
918
+ let currentChunkVisualWidth = 0;
919
+ let numCodePointsInChunk = 0;
920
+ let lastWordBreakPoint = -1; // Index in codePointsInLogLine for word break
921
+ let numCodePointsAtLastWordBreak = 0;
922
+ // Iterate through code points to build the current visual line (chunk)
923
+ for (let i = currentPosInLogLine; i < codePointsInLogLine.length; i++) {
924
+ const char = codePointsInLogLine[i];
925
+ const charVisualWidth = getCachedStringWidth(char);
926
+ if (currentChunkVisualWidth + charVisualWidth > viewportWidth) {
927
+ // Character would exceed viewport width
928
+ if (lastWordBreakPoint !== -1 &&
929
+ numCodePointsAtLastWordBreak > 0 &&
930
+ currentPosInLogLine + numCodePointsAtLastWordBreak < i) {
931
+ // We have a valid word break point to use, and it's not the start of the current segment
932
+ currentChunk = codePointsInLogLine
933
+ .slice(currentPosInLogLine, currentPosInLogLine + numCodePointsAtLastWordBreak)
934
+ .join("");
935
+ numCodePointsInChunk = numCodePointsAtLastWordBreak;
936
+ }
937
+ else {
938
+ // No word break, or word break is at the start of this potential chunk, or word break leads to empty chunk.
939
+ // Hard break: take characters up to viewportWidth, or just the current char if it alone is too wide.
940
+ if (numCodePointsInChunk === 0 &&
941
+ charVisualWidth > viewportWidth) {
942
+ // Single character is wider than viewport, take it anyway
943
+ currentChunk = char;
944
+ numCodePointsInChunk = 1;
945
+ }
946
+ }
947
+ break; // Break from inner loop to finalize this chunk
948
+ }
949
+ currentChunk += char;
950
+ currentChunkVisualWidth += charVisualWidth;
951
+ numCodePointsInChunk++;
952
+ // Check for word break opportunity (space)
953
+ if (char === " ") {
954
+ lastWordBreakPoint = i; // Store code point index of the space
955
+ // Store the state *before* adding the space, if we decide to break here.
956
+ numCodePointsAtLastWordBreak = numCodePointsInChunk - 1; // Chars *before* the space
957
+ }
958
+ }
959
+ if (numCodePointsInChunk === 0 &&
960
+ currentPosInLogLine < codePointsInLogLine.length) {
961
+ const firstChar = codePointsInLogLine[currentPosInLogLine];
962
+ currentChunk = firstChar;
963
+ numCodePointsInChunk = 1;
964
+ }
965
+ const logicalStartCol = transformedToLogMap[currentPosInLogLine] ?? 0;
966
+ lineLogicalToVisualMap.push([lineVisualLines.length, logicalStartCol]);
967
+ lineVisualToLogicalMap.push([logIndex, logicalStartCol]);
968
+ lineVisualToTransformedMap.push(currentPosInLogLine);
969
+ lineVisualLines.push(currentChunk);
970
+ const logicalStartOfThisChunk = currentPosInLogLine;
971
+ currentPosInLogLine += numCodePointsInChunk;
972
+ if (logicalStartOfThisChunk + numCodePointsInChunk <
973
+ codePointsInLogLine.length &&
974
+ currentPosInLogLine < codePointsInLogLine.length &&
975
+ codePointsInLogLine[currentPosInLogLine] === " ") {
976
+ currentPosInLogLine++;
977
+ }
978
+ }
979
+ }
980
+ // Cache the result for this line
981
+ lineLayoutCache.set(cacheKey, {
982
+ visualLines: lineVisualLines,
983
+ logicalToVisualMap: lineLogicalToVisualMap,
984
+ visualToLogicalMap: lineVisualToLogicalMap,
985
+ transformedToLogMap,
986
+ visualToTransformedMap: lineVisualToTransformedMap,
987
+ });
988
+ const visualLineOffset = visualLines.length;
989
+ visualLines.push(...lineVisualLines);
990
+ lineLogicalToVisualMap.forEach(([relVisualIdx, logCol]) => {
991
+ logicalToVisualMap[logIndex].push([
992
+ visualLineOffset + relVisualIdx,
993
+ logCol,
994
+ ]);
995
+ });
996
+ lineVisualToLogicalMap.forEach(([, logCol]) => {
997
+ visualToLogicalMap.push([logIndex, logCol]);
998
+ });
999
+ transformedToLogicalMaps[logIndex] = transformedToLogMap;
1000
+ visualToTransformedMap.push(...lineVisualToTransformedMap);
1001
+ });
1002
+ // If the entire logical text was empty, ensure there's one empty visual line.
1003
+ if (logicalLines.length === 0 ||
1004
+ (logicalLines.length === 1 && logicalLines[0] === "")) {
1005
+ if (visualLines.length === 0) {
1006
+ visualLines.push("");
1007
+ if (!logicalToVisualMap[0])
1008
+ logicalToVisualMap[0] = [];
1009
+ logicalToVisualMap[0].push([0, 0]);
1010
+ visualToLogicalMap.push([0, 0]);
1011
+ visualToTransformedMap.push(0);
1012
+ }
1013
+ }
1014
+ return {
1015
+ visualLines,
1016
+ logicalToVisualMap,
1017
+ visualToLogicalMap,
1018
+ transformedToLogicalMaps,
1019
+ visualToTransformedMap,
1020
+ };
1021
+ }
1022
+ // Calculates the visual cursor position based on a pre-calculated layout.
1023
+ // This is a lightweight operation.
1024
+ function calculateVisualCursorFromLayout(layout, logicalCursor) {
1025
+ const { logicalToVisualMap, visualLines, transformedToLogicalMaps } = layout;
1026
+ const [logicalRow, logicalCol] = logicalCursor;
1027
+ const segmentsForLogicalLine = logicalToVisualMap[logicalRow];
1028
+ if (!segmentsForLogicalLine || segmentsForLogicalLine.length === 0) {
1029
+ // This can happen for an empty document.
1030
+ return [0, 0];
1031
+ }
1032
+ // Find the segment where the logical column fits.
1033
+ // The segments are sorted by startColInLogical.
1034
+ let targetSegmentIndex = segmentsForLogicalLine.findIndex(([, startColInLogical], index) => {
1035
+ const nextStartColInLogical = index + 1 < segmentsForLogicalLine.length
1036
+ ? segmentsForLogicalLine[index + 1][1]
1037
+ : Infinity;
1038
+ return (logicalCol >= startColInLogical && logicalCol < nextStartColInLogical);
1039
+ });
1040
+ // If not found, it means the cursor is at the end of the logical line.
1041
+ if (targetSegmentIndex === -1) {
1042
+ if (logicalCol === 0) {
1043
+ targetSegmentIndex = 0;
1044
+ }
1045
+ else {
1046
+ targetSegmentIndex = segmentsForLogicalLine.length - 1;
1047
+ }
1048
+ }
1049
+ const [visualRow, startColInLogical] = segmentsForLogicalLine[targetSegmentIndex];
1050
+ // Find the coordinates in transformed space in order to conver to visual
1051
+ const transformedToLogicalMap = transformedToLogicalMaps[logicalRow] ?? [];
1052
+ let transformedCol = 0;
1053
+ for (let i = 0; i < transformedToLogicalMap.length; i++) {
1054
+ if (transformedToLogicalMap[i] > logicalCol) {
1055
+ transformedCol = Math.max(0, i - 1);
1056
+ break;
1057
+ }
1058
+ if (i === transformedToLogicalMap.length - 1) {
1059
+ transformedCol = transformedToLogicalMap.length - 1;
1060
+ }
1061
+ }
1062
+ let startColInTransformed = 0;
1063
+ while (startColInTransformed < transformedToLogicalMap.length &&
1064
+ transformedToLogicalMap[startColInTransformed] < startColInLogical) {
1065
+ startColInTransformed++;
1066
+ }
1067
+ const clampedTransformedCol = Math.min(transformedCol, Math.max(0, transformedToLogicalMap.length - 1));
1068
+ const visualCol = clampedTransformedCol - startColInTransformed;
1069
+ const clampedVisualCol = Math.min(Math.max(visualCol, 0), cpLen(visualLines[visualRow] ?? ""));
1070
+ return [visualRow, clampedVisualCol];
1071
+ }
1072
+ const historyLimit = 100;
1073
+ export const pushUndo = (currentState) => {
1074
+ const snapshot = {
1075
+ lines: [...currentState.lines],
1076
+ cursorRow: currentState.cursorRow,
1077
+ cursorCol: currentState.cursorCol,
1078
+ pastedContent: { ...currentState.pastedContent },
1079
+ expandedPaste: currentState.expandedPaste
1080
+ ? { ...currentState.expandedPaste }
1081
+ : null,
1082
+ };
1083
+ const newStack = [...currentState.undoStack, snapshot];
1084
+ if (newStack.length > historyLimit) {
1085
+ newStack.shift();
1086
+ }
1087
+ return { ...currentState, undoStack: newStack, redoStack: [] };
1088
+ };
1089
+ function generatePastedTextId(content, lineCount, pastedContent) {
1090
+ const base = lineCount > LARGE_PASTE_LINE_THRESHOLD
1091
+ ? `[Pasted Text: ${lineCount} lines]`
1092
+ : `[Pasted Text: ${content.length} chars]`;
1093
+ let id = base;
1094
+ let suffix = 2;
1095
+ while (pastedContent[id]) {
1096
+ id = base.replace("]", ` #${suffix}]`);
1097
+ suffix++;
1098
+ }
1099
+ return id;
1100
+ }
1101
+ function collectPlaceholderIdsFromLines(lines) {
1102
+ const ids = new Set();
1103
+ const pasteRegex = new RegExp(PASTED_TEXT_PLACEHOLDER_REGEX.source, "g");
1104
+ for (const line of lines) {
1105
+ if (!line)
1106
+ continue;
1107
+ for (const match of line.matchAll(pasteRegex)) {
1108
+ const placeholderId = match[0];
1109
+ if (placeholderId) {
1110
+ ids.add(placeholderId);
1111
+ }
1112
+ }
1113
+ }
1114
+ return ids;
1115
+ }
1116
+ function pruneOrphanedPastedContent(pastedContent, expandedPasteId, beforeChangedLines, allLines) {
1117
+ if (Object.keys(pastedContent).length === 0)
1118
+ return pastedContent;
1119
+ const beforeIds = collectPlaceholderIdsFromLines(beforeChangedLines);
1120
+ if (beforeIds.size === 0)
1121
+ return pastedContent;
1122
+ const afterIds = collectPlaceholderIdsFromLines(allLines);
1123
+ const removedIds = [...beforeIds].filter((id) => !afterIds.has(id) && id !== expandedPasteId);
1124
+ if (removedIds.length === 0)
1125
+ return pastedContent;
1126
+ const pruned = { ...pastedContent };
1127
+ for (const id of removedIds) {
1128
+ if (pruned[id]) {
1129
+ delete pruned[id];
1130
+ }
1131
+ }
1132
+ return pruned;
1133
+ }
1134
+ function textBufferReducerLogic(state, action, options = {}) {
1135
+ const pushUndoLocal = pushUndo;
1136
+ const currentLine = (r) => state.lines[r] ?? "";
1137
+ const currentLineLen = (r) => cpLen(currentLine(r));
1138
+ switch (action.type) {
1139
+ case "set_text": {
1140
+ let nextState = state;
1141
+ if (action.pushToUndo !== false) {
1142
+ nextState = pushUndoLocal(state);
1143
+ }
1144
+ const newContentLines = action.payload
1145
+ .replace(/\r\n?/g, "\n")
1146
+ .split("\n");
1147
+ const lines = newContentLines.length === 0 ? [""] : newContentLines;
1148
+ let newCursorRow;
1149
+ let newCursorCol;
1150
+ if (typeof action.cursorPosition === "number") {
1151
+ [newCursorRow, newCursorCol] = offsetToLogicalPos(action.payload, action.cursorPosition);
1152
+ }
1153
+ else if (action.cursorPosition === "start") {
1154
+ newCursorRow = 0;
1155
+ newCursorCol = 0;
1156
+ }
1157
+ else {
1158
+ // Default to 'end'
1159
+ newCursorRow = lines.length - 1;
1160
+ newCursorCol = cpLen(lines[newCursorRow] ?? "");
1161
+ }
1162
+ return {
1163
+ ...nextState,
1164
+ lines,
1165
+ cursorRow: newCursorRow,
1166
+ cursorCol: newCursorCol,
1167
+ preferredCol: null,
1168
+ pastedContent: action.payload === "" ? {} : nextState.pastedContent,
1169
+ };
1170
+ }
1171
+ case "insert": {
1172
+ const nextState = detachExpandedPaste(pushUndoLocal(state));
1173
+ const newLines = [...nextState.lines];
1174
+ let newCursorRow = nextState.cursorRow;
1175
+ let newCursorCol = nextState.cursorCol;
1176
+ const currentLine = (r) => newLines[r] ?? "";
1177
+ let payload = action.payload;
1178
+ let newPastedContent = nextState.pastedContent;
1179
+ if (action.isPaste) {
1180
+ // Normalize line endings for pastes
1181
+ payload = payload.replace(/\r\n|\r/g, "\n");
1182
+ const lineCount = payload.split("\n").length;
1183
+ if (lineCount > LARGE_PASTE_LINE_THRESHOLD ||
1184
+ payload.length > LARGE_PASTE_CHAR_THRESHOLD) {
1185
+ const id = generatePastedTextId(payload, lineCount, newPastedContent);
1186
+ newPastedContent = {
1187
+ ...newPastedContent,
1188
+ [id]: payload,
1189
+ };
1190
+ payload = id;
1191
+ }
1192
+ }
1193
+ if (options.singleLine) {
1194
+ payload = payload.replace(/[\r\n]/g, "");
1195
+ }
1196
+ if (options.inputFilter) {
1197
+ payload = options.inputFilter(payload);
1198
+ }
1199
+ if (payload.length === 0) {
1200
+ return state;
1201
+ }
1202
+ const str = stripUnsafeCharacters(payload.replace(/\r\n/g, "\n").replace(/\r/g, "\n"));
1203
+ const parts = str.split("\n");
1204
+ const lineContent = currentLine(newCursorRow);
1205
+ const before = cpSlice(lineContent, 0, newCursorCol);
1206
+ const after = cpSlice(lineContent, newCursorCol);
1207
+ let lineDelta = 0;
1208
+ if (parts.length > 1) {
1209
+ newLines[newCursorRow] = before + parts[0];
1210
+ const remainingParts = parts.slice(1);
1211
+ const lastPartOriginal = remainingParts.pop() ?? "";
1212
+ newLines.splice(newCursorRow + 1, 0, ...remainingParts);
1213
+ newLines.splice(newCursorRow + parts.length - 1, 0, lastPartOriginal + after);
1214
+ lineDelta = parts.length - 1;
1215
+ newCursorRow = newCursorRow + parts.length - 1;
1216
+ newCursorCol = cpLen(lastPartOriginal);
1217
+ }
1218
+ else {
1219
+ newLines[newCursorRow] = before + parts[0] + after;
1220
+ newCursorCol = cpLen(before) + cpLen(parts[0]);
1221
+ }
1222
+ const { newInfo: newExpandedPaste, isDetached } = shiftExpandedRegions(nextState.expandedPaste, nextState.cursorRow, lineDelta);
1223
+ if (isDetached && newExpandedPaste === null && nextState.expandedPaste) {
1224
+ delete newPastedContent[nextState.expandedPaste.id];
1225
+ }
1226
+ return {
1227
+ ...nextState,
1228
+ lines: newLines,
1229
+ cursorRow: newCursorRow,
1230
+ cursorCol: newCursorCol,
1231
+ preferredCol: null,
1232
+ pastedContent: newPastedContent,
1233
+ expandedPaste: newExpandedPaste,
1234
+ };
1235
+ }
1236
+ case "add_pasted_content": {
1237
+ const { id, text } = action.payload;
1238
+ return {
1239
+ ...state,
1240
+ pastedContent: {
1241
+ ...state.pastedContent,
1242
+ [id]: text,
1243
+ },
1244
+ };
1245
+ }
1246
+ case "backspace": {
1247
+ const stateWithUndo = pushUndoLocal(state);
1248
+ const currentState = detachExpandedPaste(stateWithUndo);
1249
+ const { cursorRow, cursorCol, lines, transformationsByLine } = currentState;
1250
+ // Early return if at start of buffer
1251
+ if (cursorCol === 0 && cursorRow === 0)
1252
+ return currentState;
1253
+ // Check if cursor is at end of an atomic placeholder
1254
+ const transformations = transformationsByLine[cursorRow] ?? [];
1255
+ const placeholder = findAtomicPlaceholderForBackspace(lines[cursorRow], cursorCol, transformations);
1256
+ if (placeholder) {
1257
+ const nextState = currentState;
1258
+ const newLines = [...nextState.lines];
1259
+ newLines[cursorRow] =
1260
+ cpSlice(newLines[cursorRow], 0, placeholder.start) +
1261
+ cpSlice(newLines[cursorRow], placeholder.end);
1262
+ // Recalculate transformations for the modified line
1263
+ const newTransformations = [...nextState.transformationsByLine];
1264
+ newTransformations[cursorRow] = calculateTransformationsForLine(newLines[cursorRow]);
1265
+ // Clean up pastedContent if this was a paste placeholder
1266
+ let newPastedContent = nextState.pastedContent;
1267
+ if (placeholder.type === "paste" && placeholder.id) {
1268
+ const { [placeholder.id]: _, ...remaining } = nextState.pastedContent;
1269
+ newPastedContent = remaining;
1270
+ }
1271
+ return {
1272
+ ...nextState,
1273
+ lines: newLines,
1274
+ cursorCol: placeholder.start,
1275
+ preferredCol: null,
1276
+ transformationsByLine: newTransformations,
1277
+ pastedContent: newPastedContent,
1278
+ };
1279
+ }
1280
+ // Standard backspace logic
1281
+ const nextState = currentState;
1282
+ const newLines = [...nextState.lines];
1283
+ let newCursorRow = nextState.cursorRow;
1284
+ let newCursorCol = nextState.cursorCol;
1285
+ const currentLine = (r) => newLines[r] ?? "";
1286
+ let lineDelta = 0;
1287
+ if (newCursorCol > 0) {
1288
+ const lineContent = currentLine(newCursorRow);
1289
+ newLines[newCursorRow] =
1290
+ cpSlice(lineContent, 0, newCursorCol - 1) +
1291
+ cpSlice(lineContent, newCursorCol);
1292
+ newCursorCol--;
1293
+ }
1294
+ else if (newCursorRow > 0) {
1295
+ const prevLineContent = currentLine(newCursorRow - 1);
1296
+ const currentLineContentVal = currentLine(newCursorRow);
1297
+ const newCol = cpLen(prevLineContent);
1298
+ newLines[newCursorRow - 1] = prevLineContent + currentLineContentVal;
1299
+ newLines.splice(newCursorRow, 1);
1300
+ lineDelta = -1;
1301
+ newCursorRow--;
1302
+ newCursorCol = newCol;
1303
+ }
1304
+ const { newInfo: newExpandedPaste, isDetached } = shiftExpandedRegions(nextState.expandedPaste, nextState.cursorRow + lineDelta, // shift based on the line that was removed
1305
+ lineDelta, nextState.cursorRow);
1306
+ const newPastedContent = { ...nextState.pastedContent };
1307
+ if (isDetached && nextState.expandedPaste) {
1308
+ delete newPastedContent[nextState.expandedPaste.id];
1309
+ }
1310
+ return {
1311
+ ...nextState,
1312
+ lines: newLines,
1313
+ cursorRow: newCursorRow,
1314
+ cursorCol: newCursorCol,
1315
+ preferredCol: null,
1316
+ pastedContent: newPastedContent,
1317
+ expandedPaste: newExpandedPaste,
1318
+ };
1319
+ }
1320
+ case "set_viewport": {
1321
+ const { width, height } = action.payload;
1322
+ if (width === state.viewportWidth && height === state.viewportHeight) {
1323
+ return state;
1324
+ }
1325
+ return {
1326
+ ...state,
1327
+ viewportWidth: width,
1328
+ viewportHeight: height,
1329
+ };
1330
+ }
1331
+ case "move": {
1332
+ const { dir } = action.payload;
1333
+ const { cursorRow, cursorCol, lines, visualLayout, preferredCol } = state;
1334
+ // Visual movements
1335
+ if (dir === "left" ||
1336
+ dir === "right" ||
1337
+ dir === "up" ||
1338
+ dir === "down" ||
1339
+ dir === "home" ||
1340
+ dir === "end") {
1341
+ const visualCursor = calculateVisualCursorFromLayout(visualLayout, [
1342
+ cursorRow,
1343
+ cursorCol,
1344
+ ]);
1345
+ const { visualLines, visualToLogicalMap } = visualLayout;
1346
+ let newVisualRow = visualCursor[0];
1347
+ let newVisualCol = visualCursor[1];
1348
+ let newPreferredCol = preferredCol;
1349
+ const currentVisLineLen = cpLen(visualLines[newVisualRow] ?? "");
1350
+ switch (dir) {
1351
+ case "left":
1352
+ newPreferredCol = null;
1353
+ if (newVisualCol > 0) {
1354
+ newVisualCol--;
1355
+ }
1356
+ else if (newVisualRow > 0) {
1357
+ newVisualRow--;
1358
+ newVisualCol = cpLen(visualLines[newVisualRow] ?? "");
1359
+ }
1360
+ break;
1361
+ case "right":
1362
+ newPreferredCol = null;
1363
+ if (newVisualCol < currentVisLineLen) {
1364
+ newVisualCol++;
1365
+ }
1366
+ else if (newVisualRow < visualLines.length - 1) {
1367
+ newVisualRow++;
1368
+ newVisualCol = 0;
1369
+ }
1370
+ break;
1371
+ case "up":
1372
+ if (newVisualRow > 0) {
1373
+ if (newPreferredCol === null)
1374
+ newPreferredCol = newVisualCol;
1375
+ newVisualRow--;
1376
+ newVisualCol = clamp(newPreferredCol, 0, cpLen(visualLines[newVisualRow] ?? ""));
1377
+ }
1378
+ break;
1379
+ case "down":
1380
+ if (newVisualRow < visualLines.length - 1) {
1381
+ if (newPreferredCol === null)
1382
+ newPreferredCol = newVisualCol;
1383
+ newVisualRow++;
1384
+ newVisualCol = clamp(newPreferredCol, 0, cpLen(visualLines[newVisualRow] ?? ""));
1385
+ }
1386
+ break;
1387
+ case "home":
1388
+ newPreferredCol = null;
1389
+ newVisualCol = 0;
1390
+ break;
1391
+ case "end":
1392
+ newPreferredCol = null;
1393
+ newVisualCol = currentVisLineLen;
1394
+ break;
1395
+ default: {
1396
+ const exhaustiveCheck = dir;
1397
+ debugLogger.error(`Unknown visual movement direction: ${exhaustiveCheck}`);
1398
+ return state;
1399
+ }
1400
+ }
1401
+ if (visualToLogicalMap[newVisualRow]) {
1402
+ const [logRow, logicalStartCol] = visualToLogicalMap[newVisualRow];
1403
+ const transformedToLogicalMap = visualLayout.transformedToLogicalMaps?.[logRow] ?? [];
1404
+ let transformedStartCol = 0;
1405
+ while (transformedStartCol < transformedToLogicalMap.length &&
1406
+ transformedToLogicalMap[transformedStartCol] < logicalStartCol) {
1407
+ transformedStartCol++;
1408
+ }
1409
+ const clampedTransformedCol = Math.min(transformedStartCol + newVisualCol, Math.max(0, transformedToLogicalMap.length - 1));
1410
+ const newLogicalCol = transformedToLogicalMap[clampedTransformedCol] ??
1411
+ cpLen(lines[logRow] ?? "");
1412
+ return {
1413
+ ...state,
1414
+ cursorRow: logRow,
1415
+ cursorCol: newLogicalCol,
1416
+ preferredCol: newPreferredCol,
1417
+ };
1418
+ }
1419
+ return state;
1420
+ }
1421
+ // Logical movements
1422
+ switch (dir) {
1423
+ case "wordLeft": {
1424
+ if (cursorCol === 0 && cursorRow === 0)
1425
+ return state;
1426
+ let newCursorRow = cursorRow;
1427
+ let newCursorCol = cursorCol;
1428
+ if (cursorCol === 0) {
1429
+ newCursorRow--;
1430
+ newCursorCol = cpLen(lines[newCursorRow] ?? "");
1431
+ }
1432
+ else {
1433
+ const lineContent = lines[cursorRow];
1434
+ newCursorCol = findPrevWordBoundary(lineContent, cursorCol);
1435
+ }
1436
+ return {
1437
+ ...state,
1438
+ cursorRow: newCursorRow,
1439
+ cursorCol: newCursorCol,
1440
+ preferredCol: null,
1441
+ };
1442
+ }
1443
+ case "wordRight": {
1444
+ const lineContent = lines[cursorRow] ?? "";
1445
+ if (cursorRow === lines.length - 1 &&
1446
+ cursorCol === cpLen(lineContent)) {
1447
+ return state;
1448
+ }
1449
+ let newCursorRow = cursorRow;
1450
+ let newCursorCol = cursorCol;
1451
+ const lineLen = cpLen(lineContent);
1452
+ if (cursorCol >= lineLen) {
1453
+ newCursorRow++;
1454
+ newCursorCol = 0;
1455
+ }
1456
+ else {
1457
+ newCursorCol = findNextWordBoundary(lineContent, cursorCol);
1458
+ }
1459
+ return {
1460
+ ...state,
1461
+ cursorRow: newCursorRow,
1462
+ cursorCol: newCursorCol,
1463
+ preferredCol: null,
1464
+ };
1465
+ }
1466
+ default:
1467
+ return state;
1468
+ }
1469
+ }
1470
+ case "set_cursor": {
1471
+ return {
1472
+ ...state,
1473
+ ...action.payload,
1474
+ };
1475
+ }
1476
+ case "delete": {
1477
+ const stateWithUndo = pushUndoLocal(state);
1478
+ const currentState = detachExpandedPaste(stateWithUndo);
1479
+ const { cursorRow, cursorCol, lines, transformationsByLine } = currentState;
1480
+ // Check if cursor is at start of an atomic placeholder
1481
+ const transformations = transformationsByLine[cursorRow] ?? [];
1482
+ const placeholder = findAtomicPlaceholderForDelete(lines[cursorRow], cursorCol, transformations);
1483
+ if (placeholder) {
1484
+ const nextState = currentState;
1485
+ const newLines = [...nextState.lines];
1486
+ newLines[cursorRow] =
1487
+ cpSlice(newLines[cursorRow], 0, placeholder.start) +
1488
+ cpSlice(newLines[cursorRow], placeholder.end);
1489
+ // Recalculate transformations for the modified line
1490
+ const newTransformations = [...nextState.transformationsByLine];
1491
+ newTransformations[cursorRow] = calculateTransformationsForLine(newLines[cursorRow]);
1492
+ // Clean up pastedContent if this was a paste placeholder
1493
+ let newPastedContent = nextState.pastedContent;
1494
+ if (placeholder.type === "paste" && placeholder.id) {
1495
+ const { [placeholder.id]: _, ...remaining } = nextState.pastedContent;
1496
+ newPastedContent = remaining;
1497
+ }
1498
+ return {
1499
+ ...nextState,
1500
+ lines: newLines,
1501
+ // cursorCol stays the same
1502
+ preferredCol: null,
1503
+ transformationsByLine: newTransformations,
1504
+ pastedContent: newPastedContent,
1505
+ };
1506
+ }
1507
+ // Standard delete logic
1508
+ const lineContent = currentLine(cursorRow);
1509
+ let lineDelta = 0;
1510
+ const nextState = currentState;
1511
+ const newLines = [...nextState.lines];
1512
+ if (cursorCol < currentLineLen(cursorRow)) {
1513
+ newLines[cursorRow] =
1514
+ cpSlice(lineContent, 0, cursorCol) +
1515
+ cpSlice(lineContent, cursorCol + 1);
1516
+ }
1517
+ else if (cursorRow < lines.length - 1) {
1518
+ const nextLineContent = currentLine(cursorRow + 1);
1519
+ newLines[cursorRow] = lineContent + nextLineContent;
1520
+ newLines.splice(cursorRow + 1, 1);
1521
+ lineDelta = -1;
1522
+ }
1523
+ else {
1524
+ return currentState;
1525
+ }
1526
+ const { newInfo: newExpandedPaste, isDetached } = shiftExpandedRegions(nextState.expandedPaste, nextState.cursorRow, lineDelta, nextState.cursorRow + (lineDelta < 0 ? 1 : 0));
1527
+ const newPastedContent = { ...nextState.pastedContent };
1528
+ if (isDetached && nextState.expandedPaste) {
1529
+ delete newPastedContent[nextState.expandedPaste.id];
1530
+ }
1531
+ return {
1532
+ ...nextState,
1533
+ lines: newLines,
1534
+ preferredCol: null,
1535
+ pastedContent: newPastedContent,
1536
+ expandedPaste: newExpandedPaste,
1537
+ };
1538
+ }
1539
+ case "delete_word_left": {
1540
+ const stateWithUndo = pushUndoLocal(state);
1541
+ const currentState = detachExpandedPaste(stateWithUndo);
1542
+ const { cursorRow, cursorCol } = currentState;
1543
+ if (cursorCol === 0 && cursorRow === 0)
1544
+ return currentState;
1545
+ const nextState = currentState;
1546
+ const newLines = [...nextState.lines];
1547
+ let newCursorRow = cursorRow;
1548
+ let newCursorCol = cursorCol;
1549
+ let beforeChangedLines = [];
1550
+ if (newCursorCol > 0) {
1551
+ const lineContent = currentLine(newCursorRow);
1552
+ beforeChangedLines = [lineContent];
1553
+ const prevWordStart = findPrevWordStartInLine(lineContent, newCursorCol);
1554
+ const start = prevWordStart === null ? 0 : prevWordStart;
1555
+ newLines[newCursorRow] =
1556
+ cpSlice(lineContent, 0, start) + cpSlice(lineContent, newCursorCol);
1557
+ newCursorCol = start;
1558
+ }
1559
+ else {
1560
+ // Act as a backspace
1561
+ const prevLineContent = currentLine(cursorRow - 1);
1562
+ const currentLineContentVal = currentLine(cursorRow);
1563
+ beforeChangedLines = [prevLineContent, currentLineContentVal];
1564
+ const newCol = cpLen(prevLineContent);
1565
+ newLines[cursorRow - 1] = prevLineContent + currentLineContentVal;
1566
+ newLines.splice(cursorRow, 1);
1567
+ newCursorRow--;
1568
+ newCursorCol = newCol;
1569
+ }
1570
+ const newPastedContent = pruneOrphanedPastedContent(nextState.pastedContent, nextState.expandedPaste?.id ?? null, beforeChangedLines, newLines);
1571
+ return {
1572
+ ...nextState,
1573
+ lines: newLines,
1574
+ cursorRow: newCursorRow,
1575
+ cursorCol: newCursorCol,
1576
+ preferredCol: null,
1577
+ pastedContent: newPastedContent,
1578
+ };
1579
+ }
1580
+ case "delete_word_right": {
1581
+ const stateWithUndo = pushUndoLocal(state);
1582
+ const currentState = detachExpandedPaste(stateWithUndo);
1583
+ const { cursorRow, cursorCol, lines } = currentState;
1584
+ const lineContent = currentLine(cursorRow);
1585
+ const lineLen = cpLen(lineContent);
1586
+ if (cursorCol >= lineLen && cursorRow === lines.length - 1) {
1587
+ return currentState;
1588
+ }
1589
+ const nextState = currentState;
1590
+ const newLines = [...nextState.lines];
1591
+ let beforeChangedLines = [];
1592
+ if (cursorCol >= lineLen) {
1593
+ // Act as a delete, joining with the next line
1594
+ const nextLineContent = currentLine(cursorRow + 1);
1595
+ beforeChangedLines = [lineContent, nextLineContent];
1596
+ newLines[cursorRow] = lineContent + nextLineContent;
1597
+ newLines.splice(cursorRow + 1, 1);
1598
+ }
1599
+ else {
1600
+ beforeChangedLines = [lineContent];
1601
+ const nextWordStart = findNextWordStartInLine(lineContent, cursorCol);
1602
+ const end = nextWordStart === null ? lineLen : nextWordStart;
1603
+ newLines[cursorRow] =
1604
+ cpSlice(lineContent, 0, cursorCol) + cpSlice(lineContent, end);
1605
+ }
1606
+ const newPastedContent = pruneOrphanedPastedContent(nextState.pastedContent, nextState.expandedPaste?.id ?? null, beforeChangedLines, newLines);
1607
+ return {
1608
+ ...nextState,
1609
+ lines: newLines,
1610
+ preferredCol: null,
1611
+ pastedContent: newPastedContent,
1612
+ };
1613
+ }
1614
+ case "kill_line_right": {
1615
+ const stateWithUndo = pushUndoLocal(state);
1616
+ const currentState = detachExpandedPaste(stateWithUndo);
1617
+ const { cursorRow, cursorCol, lines } = currentState;
1618
+ const lineContent = currentLine(cursorRow);
1619
+ if (cursorCol < currentLineLen(cursorRow)) {
1620
+ const nextState = currentState;
1621
+ const newLines = [...nextState.lines];
1622
+ const beforeChangedLines = [lineContent];
1623
+ newLines[cursorRow] = cpSlice(lineContent, 0, cursorCol);
1624
+ const newPastedContent = pruneOrphanedPastedContent(nextState.pastedContent, nextState.expandedPaste?.id ?? null, beforeChangedLines, newLines);
1625
+ return {
1626
+ ...nextState,
1627
+ lines: newLines,
1628
+ preferredCol: null,
1629
+ pastedContent: newPastedContent,
1630
+ };
1631
+ }
1632
+ else if (cursorRow < lines.length - 1) {
1633
+ // Act as a delete
1634
+ const nextState = currentState;
1635
+ const nextLineContent = currentLine(cursorRow + 1);
1636
+ const newLines = [...nextState.lines];
1637
+ const beforeChangedLines = [lineContent, nextLineContent];
1638
+ newLines[cursorRow] = lineContent + nextLineContent;
1639
+ newLines.splice(cursorRow + 1, 1);
1640
+ const newPastedContent = pruneOrphanedPastedContent(nextState.pastedContent, nextState.expandedPaste?.id ?? null, beforeChangedLines, newLines);
1641
+ return {
1642
+ ...nextState,
1643
+ lines: newLines,
1644
+ preferredCol: null,
1645
+ pastedContent: newPastedContent,
1646
+ };
1647
+ }
1648
+ return currentState;
1649
+ }
1650
+ case "kill_line_left": {
1651
+ const stateWithUndo = pushUndoLocal(state);
1652
+ const currentState = detachExpandedPaste(stateWithUndo);
1653
+ const { cursorRow, cursorCol } = currentState;
1654
+ if (cursorCol > 0) {
1655
+ const nextState = currentState;
1656
+ const lineContent = currentLine(cursorRow);
1657
+ const newLines = [...nextState.lines];
1658
+ const beforeChangedLines = [lineContent];
1659
+ newLines[cursorRow] = cpSlice(lineContent, cursorCol);
1660
+ const newPastedContent = pruneOrphanedPastedContent(nextState.pastedContent, nextState.expandedPaste?.id ?? null, beforeChangedLines, newLines);
1661
+ return {
1662
+ ...nextState,
1663
+ lines: newLines,
1664
+ cursorCol: 0,
1665
+ preferredCol: null,
1666
+ pastedContent: newPastedContent,
1667
+ };
1668
+ }
1669
+ return currentState;
1670
+ }
1671
+ case "undo": {
1672
+ const stateToRestore = state.undoStack[state.undoStack.length - 1];
1673
+ if (!stateToRestore)
1674
+ return state;
1675
+ const currentSnapshot = {
1676
+ lines: [...state.lines],
1677
+ cursorRow: state.cursorRow,
1678
+ cursorCol: state.cursorCol,
1679
+ pastedContent: { ...state.pastedContent },
1680
+ expandedPaste: state.expandedPaste ? { ...state.expandedPaste } : null,
1681
+ };
1682
+ return {
1683
+ ...state,
1684
+ ...stateToRestore,
1685
+ undoStack: state.undoStack.slice(0, -1),
1686
+ redoStack: [...state.redoStack, currentSnapshot],
1687
+ };
1688
+ }
1689
+ case "redo": {
1690
+ const stateToRestore = state.redoStack[state.redoStack.length - 1];
1691
+ if (!stateToRestore)
1692
+ return state;
1693
+ const currentSnapshot = {
1694
+ lines: [...state.lines],
1695
+ cursorRow: state.cursorRow,
1696
+ cursorCol: state.cursorCol,
1697
+ pastedContent: { ...state.pastedContent },
1698
+ expandedPaste: state.expandedPaste ? { ...state.expandedPaste } : null,
1699
+ };
1700
+ return {
1701
+ ...state,
1702
+ ...stateToRestore,
1703
+ redoStack: state.redoStack.slice(0, -1),
1704
+ undoStack: [...state.undoStack, currentSnapshot],
1705
+ };
1706
+ }
1707
+ case "replace_range": {
1708
+ const { startRow, startCol, endRow, endCol, text } = action.payload;
1709
+ const nextState = pushUndoLocal(state);
1710
+ const newState = replaceRangeInternal(nextState, startRow, startCol, endRow, endCol, text);
1711
+ const oldLineCount = endRow - startRow + 1;
1712
+ const newLineCount = newState.lines.length - (nextState.lines.length - oldLineCount);
1713
+ const lineDelta = newLineCount - oldLineCount;
1714
+ const { newInfo: newExpandedPaste, isDetached } = shiftExpandedRegions(nextState.expandedPaste, startRow, lineDelta, endRow);
1715
+ const newPastedContent = { ...newState.pastedContent };
1716
+ if (isDetached && nextState.expandedPaste) {
1717
+ delete newPastedContent[nextState.expandedPaste.id];
1718
+ }
1719
+ return {
1720
+ ...newState,
1721
+ pastedContent: newPastedContent,
1722
+ expandedPaste: newExpandedPaste,
1723
+ };
1724
+ }
1725
+ case "move_to_offset": {
1726
+ const { offset } = action.payload;
1727
+ const [newRow, newCol] = offsetToLogicalPos(state.lines.join("\n"), offset);
1728
+ return {
1729
+ ...state,
1730
+ cursorRow: newRow,
1731
+ cursorCol: newCol,
1732
+ preferredCol: null,
1733
+ };
1734
+ }
1735
+ case "create_undo_snapshot": {
1736
+ return pushUndoLocal(state);
1737
+ }
1738
+ // Vim-specific operations
1739
+ case "vim_delete_word_forward":
1740
+ case "vim_delete_word_backward":
1741
+ case "vim_delete_word_end":
1742
+ case "vim_delete_big_word_forward":
1743
+ case "vim_delete_big_word_backward":
1744
+ case "vim_delete_big_word_end":
1745
+ case "vim_change_word_forward":
1746
+ case "vim_change_word_backward":
1747
+ case "vim_change_word_end":
1748
+ case "vim_change_big_word_forward":
1749
+ case "vim_change_big_word_backward":
1750
+ case "vim_change_big_word_end":
1751
+ case "vim_delete_line":
1752
+ case "vim_change_line":
1753
+ case "vim_delete_to_end_of_line":
1754
+ case "vim_delete_to_start_of_line":
1755
+ case "vim_change_to_end_of_line":
1756
+ case "vim_change_movement":
1757
+ case "vim_move_left":
1758
+ case "vim_move_right":
1759
+ case "vim_move_up":
1760
+ case "vim_move_down":
1761
+ case "vim_move_word_forward":
1762
+ case "vim_move_word_backward":
1763
+ case "vim_move_word_end":
1764
+ case "vim_move_big_word_forward":
1765
+ case "vim_move_big_word_backward":
1766
+ case "vim_move_big_word_end":
1767
+ case "vim_delete_char":
1768
+ case "vim_insert_at_cursor":
1769
+ case "vim_append_at_cursor":
1770
+ case "vim_open_line_below":
1771
+ case "vim_open_line_above":
1772
+ case "vim_append_at_line_end":
1773
+ case "vim_insert_at_line_start":
1774
+ case "vim_move_to_line_start":
1775
+ case "vim_move_to_line_end":
1776
+ case "vim_move_to_first_nonwhitespace":
1777
+ case "vim_move_to_first_line":
1778
+ case "vim_move_to_last_line":
1779
+ case "vim_move_to_line":
1780
+ case "vim_escape_insert_mode":
1781
+ case "vim_delete_to_first_nonwhitespace":
1782
+ case "vim_change_to_start_of_line":
1783
+ case "vim_change_to_first_nonwhitespace":
1784
+ case "vim_delete_to_first_line":
1785
+ case "vim_delete_to_last_line":
1786
+ case "vim_delete_char_before":
1787
+ case "vim_toggle_case":
1788
+ case "vim_replace_char":
1789
+ case "vim_find_char_forward":
1790
+ case "vim_find_char_backward":
1791
+ case "vim_delete_to_char_forward":
1792
+ case "vim_delete_to_char_backward":
1793
+ case "vim_yank_line":
1794
+ case "vim_yank_word_forward":
1795
+ case "vim_yank_big_word_forward":
1796
+ case "vim_yank_word_end":
1797
+ case "vim_yank_big_word_end":
1798
+ case "vim_yank_to_end_of_line":
1799
+ case "vim_paste_after":
1800
+ case "vim_paste_before":
1801
+ return handleVimAction(state, action);
1802
+ case "toggle_paste_expansion": {
1803
+ const { id, row, col } = action.payload;
1804
+ const expandedPaste = state.expandedPaste;
1805
+ if (expandedPaste && expandedPaste.id === id) {
1806
+ const nextState = pushUndoLocal(state);
1807
+ // COLLAPSE: Restore original line with placeholder
1808
+ const newLines = [...nextState.lines];
1809
+ newLines.splice(expandedPaste.startLine, expandedPaste.lineCount, expandedPaste.prefix + id + expandedPaste.suffix);
1810
+ // Move cursor to end of collapsed placeholder
1811
+ const newCursorRow = expandedPaste.startLine;
1812
+ const newCursorCol = cpLen(expandedPaste.prefix) + cpLen(id);
1813
+ return {
1814
+ ...nextState,
1815
+ lines: newLines,
1816
+ cursorRow: newCursorRow,
1817
+ cursorCol: newCursorCol,
1818
+ preferredCol: null,
1819
+ expandedPaste: null,
1820
+ };
1821
+ }
1822
+ else {
1823
+ // EXPAND: Replace placeholder with content
1824
+ // Collapse any existing expanded paste first
1825
+ let currentState = state;
1826
+ let targetRow = row;
1827
+ if (state.expandedPaste) {
1828
+ const existingInfo = state.expandedPaste;
1829
+ const lineDelta = 1 - existingInfo.lineCount;
1830
+ if (targetRow !== undefined && targetRow > existingInfo.startLine) {
1831
+ // If we collapsed something above our target, our target row shifted up
1832
+ targetRow += lineDelta;
1833
+ }
1834
+ currentState = textBufferReducerLogic(state, {
1835
+ type: "toggle_paste_expansion",
1836
+ payload: {
1837
+ id: existingInfo.id,
1838
+ row: existingInfo.startLine,
1839
+ col: 0,
1840
+ },
1841
+ });
1842
+ // Update transformations because they are needed for finding the next placeholder
1843
+ currentState.transformationsByLine = calculateTransformations(currentState.lines);
1844
+ }
1845
+ const content = currentState.pastedContent[id];
1846
+ if (!content)
1847
+ return currentState;
1848
+ // Find line and position containing exactly this placeholder
1849
+ let lineIndex = -1;
1850
+ let placeholderStart = -1;
1851
+ const tryFindOnLine = (idx) => {
1852
+ const transforms = currentState.transformationsByLine[idx] ?? [];
1853
+ // Precise match by col
1854
+ let transform = transforms.find((t) => t.type === "paste" &&
1855
+ t.id === id &&
1856
+ col >= t.logStart &&
1857
+ col <= t.logEnd);
1858
+ if (!transform) {
1859
+ // Fallback to first match on line
1860
+ transform = transforms.find((t) => t.type === "paste" && t.id === id);
1861
+ }
1862
+ if (transform) {
1863
+ lineIndex = idx;
1864
+ placeholderStart = transform.logStart;
1865
+ return true;
1866
+ }
1867
+ return false;
1868
+ };
1869
+ // Try provided row first for precise targeting
1870
+ if (targetRow >= 0 && targetRow < currentState.lines.length) {
1871
+ tryFindOnLine(targetRow);
1872
+ }
1873
+ if (lineIndex === -1) {
1874
+ for (let i = 0; i < currentState.lines.length; i++) {
1875
+ if (tryFindOnLine(i))
1876
+ break;
1877
+ }
1878
+ }
1879
+ if (lineIndex === -1)
1880
+ return currentState;
1881
+ const nextState = pushUndoLocal(currentState);
1882
+ const line = nextState.lines[lineIndex];
1883
+ const prefix = cpSlice(line, 0, placeholderStart);
1884
+ const suffix = cpSlice(line, placeholderStart + cpLen(id));
1885
+ // Split content into lines
1886
+ const contentLines = content.split("\n");
1887
+ const newLines = [...nextState.lines];
1888
+ let expandedLines;
1889
+ if (contentLines.length === 1) {
1890
+ // Single-line content
1891
+ expandedLines = [prefix + contentLines[0] + suffix];
1892
+ }
1893
+ else {
1894
+ // Multi-line content
1895
+ expandedLines = [
1896
+ prefix + contentLines[0],
1897
+ ...contentLines.slice(1, -1),
1898
+ contentLines[contentLines.length - 1] + suffix,
1899
+ ];
1900
+ }
1901
+ newLines.splice(lineIndex, 1, ...expandedLines);
1902
+ // Move cursor to end of expanded content (before suffix)
1903
+ const newCursorRow = lineIndex + expandedLines.length - 1;
1904
+ const lastExpandedLine = expandedLines[expandedLines.length - 1];
1905
+ const newCursorCol = cpLen(lastExpandedLine) - cpLen(suffix);
1906
+ return {
1907
+ ...nextState,
1908
+ lines: newLines,
1909
+ cursorRow: newCursorRow,
1910
+ cursorCol: newCursorCol,
1911
+ preferredCol: null,
1912
+ expandedPaste: {
1913
+ id,
1914
+ startLine: lineIndex,
1915
+ lineCount: expandedLines.length,
1916
+ prefix,
1917
+ suffix,
1918
+ },
1919
+ };
1920
+ }
1921
+ }
1922
+ default: {
1923
+ const exhaustiveCheck = action;
1924
+ debugLogger.error(`Unknown action encountered: ${exhaustiveCheck}`);
1925
+ return state;
1926
+ }
1927
+ }
1928
+ }
1929
+ export function textBufferReducer(state, action, options = {}) {
1930
+ const newState = textBufferReducerLogic(state, action, options);
1931
+ const newTransformedLines = newState.lines !== state.lines
1932
+ ? calculateTransformations(newState.lines)
1933
+ : state.transformationsByLine;
1934
+ const oldTransform = getTransformUnderCursor(state.cursorRow, state.cursorCol, state.transformationsByLine);
1935
+ const newTransform = getTransformUnderCursor(newState.cursorRow, newState.cursorCol, newTransformedLines);
1936
+ const oldInside = oldTransform !== null;
1937
+ const newInside = newTransform !== null;
1938
+ const movedBetweenTransforms = oldTransform !== newTransform &&
1939
+ (oldTransform !== null || newTransform !== null);
1940
+ if (newState.lines !== state.lines ||
1941
+ newState.viewportWidth !== state.viewportWidth ||
1942
+ oldInside !== newInside ||
1943
+ movedBetweenTransforms) {
1944
+ const shouldResetPreferred = oldInside !== newInside || movedBetweenTransforms;
1945
+ return {
1946
+ ...newState,
1947
+ preferredCol: shouldResetPreferred ? null : newState.preferredCol,
1948
+ visualLayout: calculateLayout(newState.lines, newState.viewportWidth, [
1949
+ newState.cursorRow,
1950
+ newState.cursorCol,
1951
+ ]),
1952
+ transformationsByLine: newTransformedLines,
1953
+ };
1954
+ }
1955
+ return newState;
1956
+ }
1957
+ // --- End of reducer logic ---
1958
+ export function useTextBuffer({ initialText = "", initialCursorOffset = 0, viewport, stdin, setRawMode, onChange, escapePastedPaths = false, shellModeActive = false, inputFilter, singleLine = false, getPreferredEditor, }) {
1959
+ const keyMatchers = useKeyMatchers();
1960
+ const initialState = useMemo(() => {
1961
+ const lines = initialText.split("\n");
1962
+ const [initialCursorRow, initialCursorCol] = calculateInitialCursorPosition(lines.length === 0 ? [""] : lines, initialCursorOffset);
1963
+ const transformationsByLine = calculateTransformations(lines.length === 0 ? [""] : lines);
1964
+ const visualLayout = calculateLayout(lines.length === 0 ? [""] : lines, viewport.width, [initialCursorRow, initialCursorCol]);
1965
+ return {
1966
+ lines: lines.length === 0 ? [""] : lines,
1967
+ cursorRow: initialCursorRow,
1968
+ cursorCol: initialCursorCol,
1969
+ transformationsByLine,
1970
+ preferredCol: null,
1971
+ undoStack: [],
1972
+ redoStack: [],
1973
+ clipboard: null,
1974
+ selectionAnchor: null,
1975
+ viewportWidth: viewport.width,
1976
+ viewportHeight: viewport.height,
1977
+ visualLayout,
1978
+ pastedContent: {},
1979
+ expandedPaste: null,
1980
+ yankRegister: null,
1981
+ };
1982
+ }, [initialText, initialCursorOffset, viewport.width, viewport.height]);
1983
+ const [state, dispatch] = useReducer((s, a) => textBufferReducer(s, a, { inputFilter, singleLine }), initialState);
1984
+ const { lines, cursorRow, cursorCol, preferredCol, selectionAnchor, visualLayout, transformationsByLine, pastedContent, expandedPaste, } = state;
1985
+ const text = useMemo(() => lines.join("\n"), [lines]);
1986
+ const visualCursor = useMemo(() => calculateVisualCursorFromLayout(visualLayout, [cursorRow, cursorCol]), [visualLayout, cursorRow, cursorCol]);
1987
+ const { visualLines, visualToLogicalMap, transformedToLogicalMaps, visualToTransformedMap, } = visualLayout;
1988
+ const [scrollRowState, setScrollRowState] = useState(0);
1989
+ const { height } = viewport;
1990
+ const totalVisualLines = visualLines.length;
1991
+ const maxScrollStart = Math.max(0, totalVisualLines - height);
1992
+ let newVisualScrollRow = scrollRowState;
1993
+ if (visualCursor[0] < scrollRowState) {
1994
+ newVisualScrollRow = visualCursor[0];
1995
+ }
1996
+ else if (visualCursor[0] >= scrollRowState + height) {
1997
+ newVisualScrollRow = visualCursor[0] - height + 1;
1998
+ }
1999
+ newVisualScrollRow = clamp(newVisualScrollRow, 0, maxScrollStart);
2000
+ if (newVisualScrollRow !== scrollRowState) {
2001
+ setScrollRowState(newVisualScrollRow);
2002
+ }
2003
+ const actualScrollRowState = newVisualScrollRow;
2004
+ useEffect(() => {
2005
+ if (onChange) {
2006
+ onChange(text);
2007
+ }
2008
+ }, [text, onChange]);
2009
+ useEffect(() => {
2010
+ dispatch({
2011
+ type: "set_viewport",
2012
+ payload: { width: viewport.width, height: viewport.height },
2013
+ });
2014
+ }, [viewport.width, viewport.height]);
2015
+ const insert = useCallback((ch, { paste = false } = {}) => {
2016
+ if (typeof ch !== "string") {
2017
+ return;
2018
+ }
2019
+ let textToInsert = ch;
2020
+ const minLengthToInferAsDragDrop = 3;
2021
+ if (ch.length >= minLengthToInferAsDragDrop &&
2022
+ !shellModeActive &&
2023
+ paste &&
2024
+ escapePastedPaths) {
2025
+ const processed = parsePastedPaths(ch.trim());
2026
+ if (processed) {
2027
+ textToInsert = processed;
2028
+ }
2029
+ }
2030
+ let currentText = "";
2031
+ for (const char of toCodePoints(textToInsert)) {
2032
+ if (char.codePointAt(0) === 127) {
2033
+ if (currentText.length > 0) {
2034
+ dispatch({ type: "insert", payload: currentText, isPaste: paste });
2035
+ currentText = "";
2036
+ }
2037
+ dispatch({ type: "backspace" });
2038
+ }
2039
+ else {
2040
+ currentText += char;
2041
+ }
2042
+ }
2043
+ if (currentText.length > 0) {
2044
+ dispatch({ type: "insert", payload: currentText, isPaste: paste });
2045
+ }
2046
+ }, [shellModeActive, escapePastedPaths]);
2047
+ const newline = useCallback(() => {
2048
+ if (singleLine) {
2049
+ return;
2050
+ }
2051
+ dispatch({ type: "insert", payload: "\n" });
2052
+ }, [singleLine]);
2053
+ const backspace = useCallback(() => {
2054
+ dispatch({ type: "backspace" });
2055
+ }, []);
2056
+ const del = useCallback(() => {
2057
+ dispatch({ type: "delete" });
2058
+ }, []);
2059
+ const move = useCallback((dir) => {
2060
+ dispatch({ type: "move", payload: { dir } });
2061
+ }, []);
2062
+ const undo = useCallback(() => {
2063
+ dispatch({ type: "undo" });
2064
+ }, []);
2065
+ const redo = useCallback(() => {
2066
+ dispatch({ type: "redo" });
2067
+ }, []);
2068
+ const setText = useCallback((newText, cursorPosition) => {
2069
+ dispatch({ type: "set_text", payload: newText, cursorPosition });
2070
+ }, []);
2071
+ const deleteWordLeft = useCallback(() => {
2072
+ dispatch({ type: "delete_word_left" });
2073
+ }, []);
2074
+ const deleteWordRight = useCallback(() => {
2075
+ dispatch({ type: "delete_word_right" });
2076
+ }, []);
2077
+ const killLineRight = useCallback(() => {
2078
+ dispatch({ type: "kill_line_right" });
2079
+ }, []);
2080
+ const killLineLeft = useCallback(() => {
2081
+ dispatch({ type: "kill_line_left" });
2082
+ }, []);
2083
+ // Vim-specific operations
2084
+ const vimDeleteWordForward = useCallback((count) => {
2085
+ dispatch({ type: "vim_delete_word_forward", payload: { count } });
2086
+ }, []);
2087
+ const vimDeleteWordBackward = useCallback((count) => {
2088
+ dispatch({ type: "vim_delete_word_backward", payload: { count } });
2089
+ }, []);
2090
+ const vimDeleteWordEnd = useCallback((count) => {
2091
+ dispatch({ type: "vim_delete_word_end", payload: { count } });
2092
+ }, []);
2093
+ const vimDeleteBigWordForward = useCallback((count) => {
2094
+ dispatch({ type: "vim_delete_big_word_forward", payload: { count } });
2095
+ }, []);
2096
+ const vimDeleteBigWordBackward = useCallback((count) => {
2097
+ dispatch({ type: "vim_delete_big_word_backward", payload: { count } });
2098
+ }, []);
2099
+ const vimDeleteBigWordEnd = useCallback((count) => {
2100
+ dispatch({ type: "vim_delete_big_word_end", payload: { count } });
2101
+ }, []);
2102
+ const vimChangeWordForward = useCallback((count) => {
2103
+ dispatch({ type: "vim_change_word_forward", payload: { count } });
2104
+ }, []);
2105
+ const vimChangeWordBackward = useCallback((count) => {
2106
+ dispatch({ type: "vim_change_word_backward", payload: { count } });
2107
+ }, []);
2108
+ const vimChangeWordEnd = useCallback((count) => {
2109
+ dispatch({ type: "vim_change_word_end", payload: { count } });
2110
+ }, []);
2111
+ const vimChangeBigWordForward = useCallback((count) => {
2112
+ dispatch({ type: "vim_change_big_word_forward", payload: { count } });
2113
+ }, []);
2114
+ const vimChangeBigWordBackward = useCallback((count) => {
2115
+ dispatch({ type: "vim_change_big_word_backward", payload: { count } });
2116
+ }, []);
2117
+ const vimChangeBigWordEnd = useCallback((count) => {
2118
+ dispatch({ type: "vim_change_big_word_end", payload: { count } });
2119
+ }, []);
2120
+ const vimDeleteLine = useCallback((count) => {
2121
+ dispatch({ type: "vim_delete_line", payload: { count } });
2122
+ }, []);
2123
+ const vimChangeLine = useCallback((count) => {
2124
+ dispatch({ type: "vim_change_line", payload: { count } });
2125
+ }, []);
2126
+ const vimDeleteToEndOfLine = useCallback((count = 1) => {
2127
+ dispatch({ type: "vim_delete_to_end_of_line", payload: { count } });
2128
+ }, []);
2129
+ const vimDeleteToStartOfLine = useCallback(() => {
2130
+ dispatch({ type: "vim_delete_to_start_of_line" });
2131
+ }, []);
2132
+ const vimChangeToEndOfLine = useCallback((count = 1) => {
2133
+ dispatch({ type: "vim_change_to_end_of_line", payload: { count } });
2134
+ }, []);
2135
+ const vimDeleteToFirstNonWhitespace = useCallback(() => {
2136
+ dispatch({ type: "vim_delete_to_first_nonwhitespace" });
2137
+ }, []);
2138
+ const vimChangeToStartOfLine = useCallback(() => {
2139
+ dispatch({ type: "vim_change_to_start_of_line" });
2140
+ }, []);
2141
+ const vimChangeToFirstNonWhitespace = useCallback(() => {
2142
+ dispatch({ type: "vim_change_to_first_nonwhitespace" });
2143
+ }, []);
2144
+ const vimDeleteToFirstLine = useCallback((count) => {
2145
+ dispatch({ type: "vim_delete_to_first_line", payload: { count } });
2146
+ }, []);
2147
+ const vimDeleteToLastLine = useCallback((count) => {
2148
+ dispatch({ type: "vim_delete_to_last_line", payload: { count } });
2149
+ }, []);
2150
+ const vimChangeMovement = useCallback((movement, count) => {
2151
+ dispatch({ type: "vim_change_movement", payload: { movement, count } });
2152
+ }, []);
2153
+ // New vim navigation and operation methods
2154
+ const vimMoveLeft = useCallback((count) => {
2155
+ dispatch({ type: "vim_move_left", payload: { count } });
2156
+ }, []);
2157
+ const vimMoveRight = useCallback((count) => {
2158
+ dispatch({ type: "vim_move_right", payload: { count } });
2159
+ }, []);
2160
+ const vimMoveUp = useCallback((count) => {
2161
+ dispatch({ type: "vim_move_up", payload: { count } });
2162
+ }, []);
2163
+ const vimMoveDown = useCallback((count) => {
2164
+ dispatch({ type: "vim_move_down", payload: { count } });
2165
+ }, []);
2166
+ const vimMoveWordForward = useCallback((count) => {
2167
+ dispatch({ type: "vim_move_word_forward", payload: { count } });
2168
+ }, []);
2169
+ const vimMoveWordBackward = useCallback((count) => {
2170
+ dispatch({ type: "vim_move_word_backward", payload: { count } });
2171
+ }, []);
2172
+ const vimMoveWordEnd = useCallback((count) => {
2173
+ dispatch({ type: "vim_move_word_end", payload: { count } });
2174
+ }, []);
2175
+ const vimMoveBigWordForward = useCallback((count) => {
2176
+ dispatch({ type: "vim_move_big_word_forward", payload: { count } });
2177
+ }, []);
2178
+ const vimMoveBigWordBackward = useCallback((count) => {
2179
+ dispatch({ type: "vim_move_big_word_backward", payload: { count } });
2180
+ }, []);
2181
+ const vimMoveBigWordEnd = useCallback((count) => {
2182
+ dispatch({ type: "vim_move_big_word_end", payload: { count } });
2183
+ }, []);
2184
+ const vimDeleteChar = useCallback((count) => {
2185
+ dispatch({ type: "vim_delete_char", payload: { count } });
2186
+ }, []);
2187
+ const vimDeleteCharBefore = useCallback((count) => {
2188
+ dispatch({ type: "vim_delete_char_before", payload: { count } });
2189
+ }, []);
2190
+ const vimToggleCase = useCallback((count) => {
2191
+ dispatch({ type: "vim_toggle_case", payload: { count } });
2192
+ }, []);
2193
+ const vimReplaceChar = useCallback((char, count) => {
2194
+ dispatch({ type: "vim_replace_char", payload: { char, count } });
2195
+ }, []);
2196
+ const vimFindCharForward = useCallback((char, count, till) => {
2197
+ dispatch({
2198
+ type: "vim_find_char_forward",
2199
+ payload: { char, count, till },
2200
+ });
2201
+ }, []);
2202
+ const vimFindCharBackward = useCallback((char, count, till) => {
2203
+ dispatch({
2204
+ type: "vim_find_char_backward",
2205
+ payload: { char, count, till },
2206
+ });
2207
+ }, []);
2208
+ const vimDeleteToCharForward = useCallback((char, count, till) => {
2209
+ dispatch({
2210
+ type: "vim_delete_to_char_forward",
2211
+ payload: { char, count, till },
2212
+ });
2213
+ }, []);
2214
+ const vimDeleteToCharBackward = useCallback((char, count, till) => {
2215
+ dispatch({
2216
+ type: "vim_delete_to_char_backward",
2217
+ payload: { char, count, till },
2218
+ });
2219
+ }, []);
2220
+ const vimInsertAtCursor = useCallback(() => {
2221
+ dispatch({ type: "vim_insert_at_cursor" });
2222
+ }, []);
2223
+ const vimAppendAtCursor = useCallback(() => {
2224
+ dispatch({ type: "vim_append_at_cursor" });
2225
+ }, []);
2226
+ const vimOpenLineBelow = useCallback(() => {
2227
+ dispatch({ type: "vim_open_line_below" });
2228
+ }, []);
2229
+ const vimOpenLineAbove = useCallback(() => {
2230
+ dispatch({ type: "vim_open_line_above" });
2231
+ }, []);
2232
+ const vimAppendAtLineEnd = useCallback(() => {
2233
+ dispatch({ type: "vim_append_at_line_end" });
2234
+ }, []);
2235
+ const vimInsertAtLineStart = useCallback(() => {
2236
+ dispatch({ type: "vim_insert_at_line_start" });
2237
+ }, []);
2238
+ const vimMoveToLineStart = useCallback(() => {
2239
+ dispatch({ type: "vim_move_to_line_start" });
2240
+ }, []);
2241
+ const vimMoveToLineEnd = useCallback(() => {
2242
+ dispatch({ type: "vim_move_to_line_end" });
2243
+ }, []);
2244
+ const vimMoveToFirstNonWhitespace = useCallback(() => {
2245
+ dispatch({ type: "vim_move_to_first_nonwhitespace" });
2246
+ }, []);
2247
+ const vimMoveToFirstLine = useCallback(() => {
2248
+ dispatch({ type: "vim_move_to_first_line" });
2249
+ }, []);
2250
+ const vimMoveToLastLine = useCallback(() => {
2251
+ dispatch({ type: "vim_move_to_last_line" });
2252
+ }, []);
2253
+ const vimMoveToLine = useCallback((lineNumber) => {
2254
+ dispatch({ type: "vim_move_to_line", payload: { lineNumber } });
2255
+ }, []);
2256
+ const vimEscapeInsertMode = useCallback(() => {
2257
+ dispatch({ type: "vim_escape_insert_mode" });
2258
+ }, []);
2259
+ const vimYankLine = useCallback((count) => {
2260
+ dispatch({ type: "vim_yank_line", payload: { count } });
2261
+ }, []);
2262
+ const vimYankWordForward = useCallback((count) => {
2263
+ dispatch({ type: "vim_yank_word_forward", payload: { count } });
2264
+ }, []);
2265
+ const vimYankBigWordForward = useCallback((count) => {
2266
+ dispatch({ type: "vim_yank_big_word_forward", payload: { count } });
2267
+ }, []);
2268
+ const vimYankWordEnd = useCallback((count) => {
2269
+ dispatch({ type: "vim_yank_word_end", payload: { count } });
2270
+ }, []);
2271
+ const vimYankBigWordEnd = useCallback((count) => {
2272
+ dispatch({ type: "vim_yank_big_word_end", payload: { count } });
2273
+ }, []);
2274
+ const vimYankToEndOfLine = useCallback((count) => {
2275
+ dispatch({ type: "vim_yank_to_end_of_line", payload: { count } });
2276
+ }, []);
2277
+ const vimPasteAfter = useCallback((count) => {
2278
+ dispatch({ type: "vim_paste_after", payload: { count } });
2279
+ }, []);
2280
+ const vimPasteBefore = useCallback((count) => {
2281
+ dispatch({ type: "vim_paste_before", payload: { count } });
2282
+ }, []);
2283
+ const openInExternalEditor = useCallback(async () => {
2284
+ const tmpDir = fs.mkdtempSync(pathMod.join(os.tmpdir(), "gemini-edit-"));
2285
+ const filePath = pathMod.join(tmpDir, "buffer.txt");
2286
+ // Expand paste placeholders so user sees full content in editor
2287
+ const expandedText = expandPastePlaceholders(text, pastedContent);
2288
+ fs.writeFileSync(filePath, expandedText, "utf8");
2289
+ dispatch({ type: "create_undo_snapshot" });
2290
+ try {
2291
+ await openFileInEditor(filePath, stdin, setRawMode, getPreferredEditor?.());
2292
+ let newText = fs.readFileSync(filePath, "utf8");
2293
+ newText = newText.replace(/\r\n?/g, "\n");
2294
+ // Attempt to re-collapse unchanged pasted content back into placeholders
2295
+ const sortedPlaceholders = Object.entries(pastedContent).sort((a, b) => b[1].length - a[1].length);
2296
+ for (const [id, content] of sortedPlaceholders) {
2297
+ if (newText.includes(content)) {
2298
+ newText = newText.replace(content, id);
2299
+ }
2300
+ }
2301
+ dispatch({ type: "set_text", payload: newText, pushToUndo: false });
2302
+ }
2303
+ catch (err) {
2304
+ coreEvents.emitFeedback("error", "[useTextBuffer] external editor error", err);
2305
+ }
2306
+ finally {
2307
+ try {
2308
+ fs.unlinkSync(filePath);
2309
+ }
2310
+ catch {
2311
+ /* ignore */
2312
+ }
2313
+ try {
2314
+ fs.rmdirSync(tmpDir);
2315
+ }
2316
+ catch {
2317
+ /* ignore */
2318
+ }
2319
+ }
2320
+ }, [text, pastedContent, stdin, setRawMode, getPreferredEditor]);
2321
+ const handleInput = useCallback((key) => {
2322
+ const { sequence: input } = key;
2323
+ if (key.name === "paste") {
2324
+ insert(input, { paste: true });
2325
+ return true;
2326
+ }
2327
+ if (keyMatchers[Command.RETURN](key)) {
2328
+ if (singleLine) {
2329
+ return false;
2330
+ }
2331
+ newline();
2332
+ return true;
2333
+ }
2334
+ if (keyMatchers[Command.NEWLINE](key)) {
2335
+ if (singleLine) {
2336
+ return false;
2337
+ }
2338
+ newline();
2339
+ return true;
2340
+ }
2341
+ if (keyMatchers[Command.MOVE_LEFT](key)) {
2342
+ if (cursorRow === 0 && cursorCol === 0)
2343
+ return false;
2344
+ move("left");
2345
+ return true;
2346
+ }
2347
+ if (keyMatchers[Command.MOVE_RIGHT](key)) {
2348
+ const lastLineIdx = lines.length - 1;
2349
+ if (cursorRow === lastLineIdx &&
2350
+ cursorCol === cpLen(lines[lastLineIdx] ?? "")) {
2351
+ return false;
2352
+ }
2353
+ move("right");
2354
+ return true;
2355
+ }
2356
+ if (keyMatchers[Command.MOVE_UP](key)) {
2357
+ if (visualCursor[0] === 0)
2358
+ return false;
2359
+ move("up");
2360
+ return true;
2361
+ }
2362
+ if (keyMatchers[Command.MOVE_DOWN](key)) {
2363
+ if (visualCursor[0] === visualLines.length - 1)
2364
+ return false;
2365
+ move("down");
2366
+ return true;
2367
+ }
2368
+ if (keyMatchers[Command.MOVE_WORD_LEFT](key)) {
2369
+ move("wordLeft");
2370
+ return true;
2371
+ }
2372
+ if (keyMatchers[Command.MOVE_WORD_RIGHT](key)) {
2373
+ move("wordRight");
2374
+ return true;
2375
+ }
2376
+ if (keyMatchers[Command.HOME](key)) {
2377
+ move("home");
2378
+ return true;
2379
+ }
2380
+ if (keyMatchers[Command.END](key)) {
2381
+ move("end");
2382
+ return true;
2383
+ }
2384
+ if (keyMatchers[Command.CLEAR_INPUT](key)) {
2385
+ if (text.length > 0) {
2386
+ setText("");
2387
+ return true;
2388
+ }
2389
+ return false;
2390
+ }
2391
+ if (keyMatchers[Command.DELETE_WORD_BACKWARD](key)) {
2392
+ deleteWordLeft();
2393
+ return true;
2394
+ }
2395
+ if (keyMatchers[Command.DELETE_WORD_FORWARD](key)) {
2396
+ deleteWordRight();
2397
+ return true;
2398
+ }
2399
+ if (keyMatchers[Command.DELETE_CHAR_LEFT](key)) {
2400
+ backspace();
2401
+ return true;
2402
+ }
2403
+ if (keyMatchers[Command.DELETE_CHAR_RIGHT](key)) {
2404
+ const lastLineIdx = lines.length - 1;
2405
+ if (cursorRow === lastLineIdx &&
2406
+ cursorCol === cpLen(lines[lastLineIdx] ?? "")) {
2407
+ return false;
2408
+ }
2409
+ del();
2410
+ return true;
2411
+ }
2412
+ if (keyMatchers[Command.UNDO](key)) {
2413
+ undo();
2414
+ return true;
2415
+ }
2416
+ if (keyMatchers[Command.REDO](key)) {
2417
+ redo();
2418
+ return true;
2419
+ }
2420
+ if (key.insertable) {
2421
+ insert(input, { paste: false });
2422
+ return true;
2423
+ }
2424
+ return false;
2425
+ }, [
2426
+ newline,
2427
+ move,
2428
+ deleteWordLeft,
2429
+ deleteWordRight,
2430
+ backspace,
2431
+ del,
2432
+ insert,
2433
+ undo,
2434
+ redo,
2435
+ cursorRow,
2436
+ cursorCol,
2437
+ lines,
2438
+ singleLine,
2439
+ setText,
2440
+ text,
2441
+ visualCursor,
2442
+ visualLines,
2443
+ keyMatchers,
2444
+ ]);
2445
+ const visualScrollRow = useMemo(() => {
2446
+ const totalVisualLines = visualLines.length;
2447
+ return Math.min(actualScrollRowState, Math.max(0, totalVisualLines - viewport.height));
2448
+ }, [visualLines.length, actualScrollRowState, viewport.height]);
2449
+ const renderedVisualLines = useMemo(() => visualLines.slice(visualScrollRow, visualScrollRow + viewport.height), [visualLines, visualScrollRow, viewport.height]);
2450
+ const replaceRange = useCallback((startRow, startCol, endRow, endCol, text) => {
2451
+ dispatch({
2452
+ type: "replace_range",
2453
+ payload: { startRow, startCol, endRow, endCol, text },
2454
+ });
2455
+ }, []);
2456
+ const replaceRangeByOffset = useCallback((startOffset, endOffset, replacementText) => {
2457
+ const [startRow, startCol] = offsetToLogicalPos(text, startOffset);
2458
+ const [endRow, endCol] = offsetToLogicalPos(text, endOffset);
2459
+ replaceRange(startRow, startCol, endRow, endCol, replacementText);
2460
+ }, [text, replaceRange]);
2461
+ const moveToOffset = useCallback((offset) => {
2462
+ dispatch({ type: "move_to_offset", payload: { offset } });
2463
+ }, []);
2464
+ const moveToVisualPosition = useCallback((visRow, visCol) => {
2465
+ const { visualLines, visualToLogicalMap, transformedToLogicalMaps, visualToTransformedMap, } = visualLayout;
2466
+ // Clamp visRow to valid range
2467
+ const clampedVisRow = Math.max(0, Math.min(visRow, visualLines.length - 1));
2468
+ const visualLine = visualLines[clampedVisRow] || "";
2469
+ if (visualToLogicalMap[clampedVisRow]) {
2470
+ const [logRow] = visualToLogicalMap[clampedVisRow];
2471
+ const transformedToLogicalMap = transformedToLogicalMaps?.[logRow] ?? [];
2472
+ // Where does this visual line begin within the transformed line?
2473
+ const startColInTransformed = visualToTransformedMap?.[clampedVisRow] ?? 0;
2474
+ // Handle wide characters: convert visual X position to character offset
2475
+ const codePoints = toCodePoints(visualLine);
2476
+ let currentVisX = 0;
2477
+ let charOffset = 0;
2478
+ for (const char of codePoints) {
2479
+ const charWidth = getCachedStringWidth(char);
2480
+ // If the click is within this character
2481
+ if (visCol < currentVisX + charWidth) {
2482
+ // Check if we clicked the second half of a wide character
2483
+ if (charWidth > 1 && visCol >= currentVisX + charWidth / 2) {
2484
+ charOffset++;
2485
+ }
2486
+ break;
2487
+ }
2488
+ currentVisX += charWidth;
2489
+ charOffset++;
2490
+ }
2491
+ // Clamp charOffset to length
2492
+ charOffset = Math.min(charOffset, codePoints.length);
2493
+ // Map character offset through transformations to get logical position
2494
+ const transformedCol = Math.min(startColInTransformed + charOffset, Math.max(0, transformedToLogicalMap.length - 1));
2495
+ const newCursorRow = logRow;
2496
+ const newCursorCol = transformedToLogicalMap[transformedCol] ?? cpLen(lines[logRow] ?? "");
2497
+ dispatch({
2498
+ type: "set_cursor",
2499
+ payload: {
2500
+ cursorRow: newCursorRow,
2501
+ cursorCol: newCursorCol,
2502
+ preferredCol: charOffset,
2503
+ },
2504
+ });
2505
+ }
2506
+ }, [visualLayout, lines]);
2507
+ const getLogicalPositionFromVisual = useCallback((visRow, visCol) => {
2508
+ const { visualLines, visualToLogicalMap, transformedToLogicalMaps, visualToTransformedMap, } = visualLayout;
2509
+ // Clamp visRow to valid range
2510
+ const clampedVisRow = Math.max(0, Math.min(visRow, visualLines.length - 1));
2511
+ const visualLine = visualLines[clampedVisRow] || "";
2512
+ if (!visualToLogicalMap[clampedVisRow]) {
2513
+ return null;
2514
+ }
2515
+ const [logRow] = visualToLogicalMap[clampedVisRow];
2516
+ const transformedToLogicalMap = transformedToLogicalMaps?.[logRow] ?? [];
2517
+ // Where does this visual line begin within the transformed line?
2518
+ const startColInTransformed = visualToTransformedMap?.[clampedVisRow] ?? 0;
2519
+ // Handle wide characters: convert visual X position to character offset
2520
+ const codePoints = toCodePoints(visualLine);
2521
+ let currentVisX = 0;
2522
+ let charOffset = 0;
2523
+ for (const char of codePoints) {
2524
+ const charWidth = getCachedStringWidth(char);
2525
+ if (visCol < currentVisX + charWidth) {
2526
+ if (charWidth > 1 && visCol >= currentVisX + charWidth / 2) {
2527
+ charOffset++;
2528
+ }
2529
+ break;
2530
+ }
2531
+ currentVisX += charWidth;
2532
+ charOffset++;
2533
+ }
2534
+ charOffset = Math.min(charOffset, codePoints.length);
2535
+ const transformedCol = Math.min(startColInTransformed + charOffset, Math.max(0, transformedToLogicalMap.length - 1));
2536
+ const row = logRow;
2537
+ const col = transformedToLogicalMap[transformedCol] ?? cpLen(lines[logRow] ?? "");
2538
+ return { row, col };
2539
+ }, [visualLayout, lines]);
2540
+ const getOffset = useCallback(() => logicalPosToOffset(lines, cursorRow, cursorCol), [lines, cursorRow, cursorCol]);
2541
+ const togglePasteExpansion = useCallback((id, row, col) => {
2542
+ dispatch({ type: "toggle_paste_expansion", payload: { id, row, col } });
2543
+ }, []);
2544
+ const getExpandedPasteAtLineCallback = useCallback((lineIndex) => getExpandedPasteAtLine(lineIndex, expandedPaste), [expandedPaste]);
2545
+ const returnValue = useMemo(() => ({
2546
+ lines,
2547
+ text,
2548
+ cursor: [cursorRow, cursorCol],
2549
+ preferredCol,
2550
+ selectionAnchor,
2551
+ pastedContent,
2552
+ allVisualLines: visualLines,
2553
+ viewportVisualLines: renderedVisualLines,
2554
+ visualCursor,
2555
+ visualScrollRow,
2556
+ viewportHeight: viewport.height,
2557
+ visualToLogicalMap,
2558
+ transformedToLogicalMaps,
2559
+ visualToTransformedMap,
2560
+ transformationsByLine,
2561
+ visualLayout,
2562
+ setText,
2563
+ insert,
2564
+ newline,
2565
+ backspace,
2566
+ del,
2567
+ move,
2568
+ undo,
2569
+ redo,
2570
+ replaceRange,
2571
+ replaceRangeByOffset,
2572
+ moveToOffset,
2573
+ getOffset,
2574
+ moveToVisualPosition,
2575
+ getLogicalPositionFromVisual,
2576
+ getExpandedPasteAtLine: getExpandedPasteAtLineCallback,
2577
+ togglePasteExpansion,
2578
+ expandedPaste,
2579
+ deleteWordLeft,
2580
+ deleteWordRight,
2581
+ killLineRight,
2582
+ killLineLeft,
2583
+ handleInput,
2584
+ openInExternalEditor,
2585
+ // Vim-specific operations
2586
+ vimDeleteWordForward,
2587
+ vimDeleteWordBackward,
2588
+ vimDeleteWordEnd,
2589
+ vimDeleteBigWordForward,
2590
+ vimDeleteBigWordBackward,
2591
+ vimDeleteBigWordEnd,
2592
+ vimChangeWordForward,
2593
+ vimChangeWordBackward,
2594
+ vimChangeWordEnd,
2595
+ vimChangeBigWordForward,
2596
+ vimChangeBigWordBackward,
2597
+ vimChangeBigWordEnd,
2598
+ vimDeleteLine,
2599
+ vimChangeLine,
2600
+ vimDeleteToEndOfLine,
2601
+ vimDeleteToStartOfLine,
2602
+ vimChangeToEndOfLine,
2603
+ vimDeleteToFirstNonWhitespace,
2604
+ vimChangeToStartOfLine,
2605
+ vimChangeToFirstNonWhitespace,
2606
+ vimDeleteToFirstLine,
2607
+ vimDeleteToLastLine,
2608
+ vimChangeMovement,
2609
+ vimMoveLeft,
2610
+ vimMoveRight,
2611
+ vimMoveUp,
2612
+ vimMoveDown,
2613
+ vimMoveWordForward,
2614
+ vimMoveWordBackward,
2615
+ vimMoveWordEnd,
2616
+ vimMoveBigWordForward,
2617
+ vimMoveBigWordBackward,
2618
+ vimMoveBigWordEnd,
2619
+ vimDeleteChar,
2620
+ vimDeleteCharBefore,
2621
+ vimToggleCase,
2622
+ vimReplaceChar,
2623
+ vimFindCharForward,
2624
+ vimFindCharBackward,
2625
+ vimDeleteToCharForward,
2626
+ vimDeleteToCharBackward,
2627
+ vimInsertAtCursor,
2628
+ vimAppendAtCursor,
2629
+ vimOpenLineBelow,
2630
+ vimOpenLineAbove,
2631
+ vimAppendAtLineEnd,
2632
+ vimInsertAtLineStart,
2633
+ vimMoveToLineStart,
2634
+ vimMoveToLineEnd,
2635
+ vimMoveToFirstNonWhitespace,
2636
+ vimMoveToFirstLine,
2637
+ vimMoveToLastLine,
2638
+ vimMoveToLine,
2639
+ vimEscapeInsertMode,
2640
+ vimYankLine,
2641
+ vimYankWordForward,
2642
+ vimYankBigWordForward,
2643
+ vimYankWordEnd,
2644
+ vimYankBigWordEnd,
2645
+ vimYankToEndOfLine,
2646
+ vimPasteAfter,
2647
+ vimPasteBefore,
2648
+ }), [
2649
+ lines,
2650
+ text,
2651
+ cursorRow,
2652
+ cursorCol,
2653
+ preferredCol,
2654
+ selectionAnchor,
2655
+ pastedContent,
2656
+ visualLines,
2657
+ renderedVisualLines,
2658
+ visualCursor,
2659
+ visualScrollRow,
2660
+ viewport.height,
2661
+ visualToLogicalMap,
2662
+ transformedToLogicalMaps,
2663
+ visualToTransformedMap,
2664
+ transformationsByLine,
2665
+ visualLayout,
2666
+ setText,
2667
+ insert,
2668
+ newline,
2669
+ backspace,
2670
+ del,
2671
+ move,
2672
+ undo,
2673
+ redo,
2674
+ replaceRange,
2675
+ replaceRangeByOffset,
2676
+ moveToOffset,
2677
+ getOffset,
2678
+ moveToVisualPosition,
2679
+ getLogicalPositionFromVisual,
2680
+ getExpandedPasteAtLineCallback,
2681
+ togglePasteExpansion,
2682
+ expandedPaste,
2683
+ deleteWordLeft,
2684
+ deleteWordRight,
2685
+ killLineRight,
2686
+ killLineLeft,
2687
+ handleInput,
2688
+ openInExternalEditor,
2689
+ vimDeleteWordForward,
2690
+ vimDeleteWordBackward,
2691
+ vimDeleteWordEnd,
2692
+ vimDeleteBigWordForward,
2693
+ vimDeleteBigWordBackward,
2694
+ vimDeleteBigWordEnd,
2695
+ vimChangeWordForward,
2696
+ vimChangeWordBackward,
2697
+ vimChangeWordEnd,
2698
+ vimChangeBigWordForward,
2699
+ vimChangeBigWordBackward,
2700
+ vimChangeBigWordEnd,
2701
+ vimDeleteLine,
2702
+ vimChangeLine,
2703
+ vimDeleteToEndOfLine,
2704
+ vimDeleteToStartOfLine,
2705
+ vimChangeToEndOfLine,
2706
+ vimDeleteToFirstNonWhitespace,
2707
+ vimChangeToStartOfLine,
2708
+ vimChangeToFirstNonWhitespace,
2709
+ vimDeleteToFirstLine,
2710
+ vimDeleteToLastLine,
2711
+ vimChangeMovement,
2712
+ vimMoveLeft,
2713
+ vimMoveRight,
2714
+ vimMoveUp,
2715
+ vimMoveDown,
2716
+ vimMoveWordForward,
2717
+ vimMoveWordBackward,
2718
+ vimMoveWordEnd,
2719
+ vimMoveBigWordForward,
2720
+ vimMoveBigWordBackward,
2721
+ vimMoveBigWordEnd,
2722
+ vimDeleteChar,
2723
+ vimDeleteCharBefore,
2724
+ vimToggleCase,
2725
+ vimReplaceChar,
2726
+ vimFindCharForward,
2727
+ vimFindCharBackward,
2728
+ vimDeleteToCharForward,
2729
+ vimDeleteToCharBackward,
2730
+ vimInsertAtCursor,
2731
+ vimAppendAtCursor,
2732
+ vimOpenLineBelow,
2733
+ vimOpenLineAbove,
2734
+ vimAppendAtLineEnd,
2735
+ vimInsertAtLineStart,
2736
+ vimMoveToLineStart,
2737
+ vimMoveToLineEnd,
2738
+ vimMoveToFirstNonWhitespace,
2739
+ vimMoveToFirstLine,
2740
+ vimMoveToLastLine,
2741
+ vimMoveToLine,
2742
+ vimEscapeInsertMode,
2743
+ vimYankLine,
2744
+ vimYankWordForward,
2745
+ vimYankBigWordForward,
2746
+ vimYankWordEnd,
2747
+ vimYankBigWordEnd,
2748
+ vimYankToEndOfLine,
2749
+ vimPasteAfter,
2750
+ vimPasteBefore,
2751
+ ]);
2752
+ return returnValue;
2753
+ }
2754
+ //# sourceMappingURL=text-buffer.js.map