rovecode 0.4.0-beta.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (428) hide show
  1. package/README.md +67 -69
  2. package/THIRD_PARTY_NOTICES.md +0 -44
  3. package/bin/rovecode.ts +21 -0
  4. package/package.json +16 -37
  5. package/src/account/keys.ts +97 -0
  6. package/src/account/login.ts +158 -0
  7. package/src/account/provision.ts +47 -0
  8. package/src/account/store.ts +63 -0
  9. package/src/acp/server.ts +373 -0
  10. package/src/cli/account-cmd.ts +116 -0
  11. package/src/cli/connect.ts +244 -0
  12. package/src/cli/context-cmd.ts +199 -0
  13. package/src/cli/dispatch.ts +109 -0
  14. package/src/cli/doctor.ts +324 -0
  15. package/src/cli/export.ts +278 -0
  16. package/src/cli/help.ts +240 -0
  17. package/src/cli/is-tui-invocation.ts +8 -0
  18. package/src/cli/main.ts +599 -0
  19. package/src/cli/market-cmd.ts +658 -0
  20. package/src/cli/mcp-market-cmd.ts +299 -0
  21. package/src/cli/output.ts +382 -0
  22. package/src/cli/repl.ts +172 -0
  23. package/src/cli/resume.ts +32 -0
  24. package/src/cli/run-limits.ts +78 -0
  25. package/src/cli/runtime.ts +792 -0
  26. package/src/cli/setup.ts +187 -0
  27. package/src/cli/update-cmd.ts +78 -0
  28. package/src/cli/workflow-cmd.ts +100 -0
  29. package/src/coding/checkpoints.ts +270 -0
  30. package/src/coding/diff.ts +136 -0
  31. package/src/coding/files.ts +339 -0
  32. package/src/coding/hashline.ts +319 -0
  33. package/src/coding/lsp.ts +406 -0
  34. package/src/coding/repomap-cache.ts +99 -0
  35. package/src/coding/repomap-files.ts +110 -0
  36. package/src/coding/repomap.ts +392 -0
  37. package/src/core/compaction.ts +399 -0
  38. package/src/core/config.ts +289 -0
  39. package/src/core/context-report.ts +228 -0
  40. package/src/core/context.ts +60 -0
  41. package/src/core/count-remote.ts +107 -0
  42. package/src/core/execpolicy-rules.ts +196 -0
  43. package/src/core/execpolicy.ts +385 -0
  44. package/src/core/executor.ts +397 -0
  45. package/src/core/guardrails.ts +400 -0
  46. package/src/core/hooks.ts +398 -0
  47. package/src/core/images.ts +230 -0
  48. package/src/core/intro.ts +236 -0
  49. package/src/core/loop.ts +621 -0
  50. package/src/core/modes.ts +372 -0
  51. package/src/core/orchestrator.ts +207 -0
  52. package/src/core/reflection.ts +165 -0
  53. package/src/core/sandbox-config.ts +167 -0
  54. package/src/core/session-images.ts +73 -0
  55. package/src/core/session.ts +398 -0
  56. package/src/core/settings.ts +98 -0
  57. package/src/core/stuck-detector.ts +273 -0
  58. package/src/core/tasks.ts +374 -0
  59. package/src/core/token-scale.ts +108 -0
  60. package/src/core/tool-output-budget.ts +166 -0
  61. package/src/core/tools.ts +288 -0
  62. package/src/core/types.ts +330 -0
  63. package/src/core/update-check.ts +171 -0
  64. package/src/core/update.ts +158 -0
  65. package/src/core/usage.ts +204 -0
  66. package/src/core/validate.ts +121 -0
  67. package/src/core/verify-gate.ts +159 -0
  68. package/src/core/verify.ts +237 -0
  69. package/src/core/voice.ts +158 -0
  70. package/src/core/win-job.ts +183 -0
  71. package/src/design/audit.ts +797 -0
  72. package/src/design/direction.ts +190 -0
  73. package/src/design/rules.ts +157 -0
  74. package/src/eval/bench.ts +150 -0
  75. package/src/eval/gauntlet-runner.ts +218 -0
  76. package/src/eval/gauntlet.ts +226 -0
  77. package/src/eval/grader.ts +186 -0
  78. package/src/eval/record.ts +202 -0
  79. package/src/eval/redact.ts +141 -0
  80. package/src/eval/replay.ts +147 -0
  81. package/src/eval/trajectory.ts +373 -0
  82. package/src/index.ts +17 -0
  83. package/src/market/catalogs/mcp-docs.json +111 -0
  84. package/src/market/catalogs/plugins.json +111 -0
  85. package/src/market/catalogs/skills.json +478 -0
  86. package/src/market/clone.ts +72 -0
  87. package/src/market/context-cost.ts +121 -0
  88. package/src/market/digest.ts +106 -0
  89. package/src/market/index.ts +22 -0
  90. package/src/market/install.ts +578 -0
  91. package/src/market/manifest.ts +187 -0
  92. package/src/market/prereq.ts +145 -0
  93. package/src/market/registry.ts +363 -0
  94. package/src/market/resolve.ts +111 -0
  95. package/src/market/types.ts +236 -0
  96. package/src/market/validate.ts +227 -0
  97. package/src/mcp/client.ts +431 -0
  98. package/src/mcp/config.ts +239 -0
  99. package/src/mcp/local-package.ts +211 -0
  100. package/src/mcp/market-catalog.ts +84 -0
  101. package/src/mcp/market-install.ts +289 -0
  102. package/src/mcp/market.ts +0 -0
  103. package/src/mcp/tools.ts +131 -0
  104. package/src/mcp/trust.ts +49 -0
  105. package/src/memory/blocks.ts +175 -0
  106. package/src/memory/recall.ts +355 -0
  107. package/src/memory/store.ts +105 -0
  108. package/src/memory/tools.ts +99 -0
  109. package/src/plugins/cli.ts +123 -0
  110. package/src/plugins/discover.ts +108 -0
  111. package/src/plugins/index.ts +50 -0
  112. package/src/plugins/init.ts +140 -0
  113. package/src/plugins/install.ts +184 -0
  114. package/src/plugins/load.ts +149 -0
  115. package/src/plugins/manifest.ts +106 -0
  116. package/src/plugins/state.ts +83 -0
  117. package/src/providers/auth.ts +293 -0
  118. package/src/providers/cache.ts +223 -0
  119. package/src/providers/catalog-local.ts +160 -0
  120. package/src/providers/catalog.ts +408 -0
  121. package/src/providers/middleware-context.ts +86 -0
  122. package/src/providers/middleware.ts +373 -0
  123. package/src/providers/profile-glm53.ts +111 -0
  124. package/src/providers/profile-sonnet5-persona.ts +65 -0
  125. package/src/providers/profile-sonnet5-voice.ts +23 -0
  126. package/src/providers/profiles.ts +156 -0
  127. package/src/providers/provider-config.ts +311 -0
  128. package/src/providers/registry.ts +302 -0
  129. package/src/providers/response-validation.ts +80 -0
  130. package/src/providers/retry.ts +234 -0
  131. package/src/providers/router.ts +294 -0
  132. package/src/providers/sse.ts +26 -0
  133. package/src/providers/stream-errors.ts +117 -0
  134. package/src/providers/stream.ts +569 -0
  135. package/src/providers/thinking.ts +189 -0
  136. package/src/providers/wire-messages.ts +129 -0
  137. package/src/sdk/client.ts +225 -0
  138. package/src/sdk/index.ts +3 -0
  139. package/src/server/dashboard.ts +144 -0
  140. package/src/server/http.ts +343 -0
  141. package/src/server/openapi.ts +246 -0
  142. package/src/sextant/card-hits.ts +102 -0
  143. package/src/sextant/card-keys.ts +55 -0
  144. package/src/sextant/context-source.ts +157 -0
  145. package/src/sextant/draw-agents.ts +273 -0
  146. package/src/sextant/draw-code.ts +388 -0
  147. package/src/sextant/draw-context.ts +222 -0
  148. package/src/sextant/draw-frame.ts +164 -0
  149. package/src/sextant/draw-market.ts +573 -0
  150. package/src/sextant/draw-messages.ts +386 -0
  151. package/src/sextant/draw-pet.ts +230 -0
  152. package/src/sextant/draw-plan.ts +159 -0
  153. package/src/sextant/draw-tabs.ts +85 -0
  154. package/src/sextant/draw-util.ts +65 -0
  155. package/src/sextant/engine.ts +230 -0
  156. package/src/sextant/frame-hits.ts +25 -0
  157. package/src/sextant/frame.ts +101 -0
  158. package/src/sextant/git-status.ts +197 -0
  159. package/src/sextant/grid.ts +59 -0
  160. package/src/sextant/input.ts +119 -0
  161. package/src/sextant/keys.ts +488 -0
  162. package/src/sextant/layout.ts +86 -0
  163. package/src/sextant/local-commands.ts +156 -0
  164. package/src/sextant/market-source.ts +287 -0
  165. package/src/sextant/mentions.ts +141 -0
  166. package/src/sextant/message-hits.ts +26 -0
  167. package/src/sextant/model.ts +387 -0
  168. package/src/sextant/overlays.ts +451 -0
  169. package/src/sextant/panel-hits.ts +38 -0
  170. package/src/sextant/pet.ts +399 -0
  171. package/src/sextant/screen.ts +324 -0
  172. package/src/sextant/scroll-hits.ts +66 -0
  173. package/src/sextant/scrollbar.ts +82 -0
  174. package/src/sextant/selection.ts +123 -0
  175. package/src/sextant/sextant-bridge.ts +174 -0
  176. package/src/sextant/sextant-cards.ts +142 -0
  177. package/src/sextant/sextant-diff-base.ts +63 -0
  178. package/src/sextant/sextant-files.ts +154 -0
  179. package/src/sextant/sextant-frame-loop.ts +314 -0
  180. package/src/sextant/sextant-renderer.ts +478 -0
  181. package/src/sextant/sextant-repo.ts +131 -0
  182. package/src/sextant/theme.ts +66 -0
  183. package/src/sextant/tool-rows.ts +189 -0
  184. package/src/sextant/types.ts +473 -0
  185. package/src/skills/index.ts +306 -0
  186. package/src/skills/tools.ts +69 -0
  187. package/src/skills/versioned.ts +227 -0
  188. package/src/telemetry/otel.ts +353 -0
  189. package/src/telemetry/otlp.ts +68 -0
  190. package/src/tools/ask-user.ts +156 -0
  191. package/src/tools/design.ts +151 -0
  192. package/src/tools/evalcell.ts +338 -0
  193. package/src/tools/html-text.ts +139 -0
  194. package/src/tools/provider.ts +149 -0
  195. package/src/tools/task.ts +216 -0
  196. package/src/tools/todo.ts +320 -0
  197. package/src/tools/webfetch.ts +331 -0
  198. package/src/tui/app.ts +608 -0
  199. package/src/tui/attach.ts +127 -0
  200. package/src/tui/checkpoints-cmd.ts +70 -0
  201. package/src/tui/clipboard-image.ts +81 -0
  202. package/src/tui/commands.ts +277 -0
  203. package/src/tui/cost.ts +108 -0
  204. package/src/tui/info-cmd.ts +144 -0
  205. package/src/tui/mcp-cmd.ts +128 -0
  206. package/src/tui/modes-cmd.ts +45 -0
  207. package/src/tui/overlays.ts +97 -0
  208. package/src/tui/pi-renderer.ts +424 -0
  209. package/src/tui/providers-cmd.ts +366 -0
  210. package/src/tui/renderer.ts +101 -0
  211. package/src/tui/replay-marker.ts +29 -0
  212. package/src/tui/session-cmd.ts +146 -0
  213. package/src/tui/sextant-attach.ts +68 -0
  214. package/src/tui/sextant-io.ts +184 -0
  215. package/src/tui/sextant-smoke.ts +110 -0
  216. package/src/tui/smoke.ts +72 -0
  217. package/src/tui/theme.ts +59 -0
  218. package/src/tui/todo-label.ts +7 -0
  219. package/src/workflow/engine.ts +266 -0
  220. package/tsconfig.json +30 -0
  221. package/vendor/pi-tui/LICENSE +21 -0
  222. package/vendor/pi-tui/PATCHES.md +12 -0
  223. package/vendor/pi-tui/PROVENANCE.md +12 -0
  224. package/vendor/pi-tui/README.upstream.md +854 -0
  225. package/vendor/pi-tui/native/win32/prebuilds/win32-arm64/win32-console-mode.node +0 -0
  226. package/vendor/pi-tui/native/win32/prebuilds/win32-x64/win32-console-mode.node +0 -0
  227. package/vendor/pi-tui/src/alt-screen-search.ts +158 -0
  228. package/vendor/pi-tui/src/autocomplete.ts +827 -0
  229. package/vendor/pi-tui/src/components/alt-screen-flash.ts +52 -0
  230. package/vendor/pi-tui/src/components/box.ts +138 -0
  231. package/vendor/pi-tui/src/components/cancellable-loader.ts +41 -0
  232. package/vendor/pi-tui/src/components/editor.ts +2364 -0
  233. package/vendor/pi-tui/src/components/h-stack.ts +45 -0
  234. package/vendor/pi-tui/src/components/image.ts +128 -0
  235. package/vendor/pi-tui/src/components/input.ts +448 -0
  236. package/vendor/pi-tui/src/components/loader.ts +93 -0
  237. package/vendor/pi-tui/src/components/markdown.ts +1016 -0
  238. package/vendor/pi-tui/src/components/scroll-view.ts +217 -0
  239. package/vendor/pi-tui/src/components/select-list.ts +230 -0
  240. package/vendor/pi-tui/src/components/settings-list.ts +277 -0
  241. package/vendor/pi-tui/src/components/spacer.ts +29 -0
  242. package/vendor/pi-tui/src/components/stack.ts +155 -0
  243. package/vendor/pi-tui/src/components/text.ts +108 -0
  244. package/vendor/pi-tui/src/components/truncated-text.ts +66 -0
  245. package/vendor/pi-tui/src/components/v-stack.ts +34 -0
  246. package/vendor/pi-tui/src/editor-component.ts +75 -0
  247. package/vendor/pi-tui/src/fuzzy.ts +138 -0
  248. package/vendor/pi-tui/src/index.ts +149 -0
  249. package/vendor/pi-tui/src/keybindings.ts +321 -0
  250. package/vendor/pi-tui/src/keys.ts +1402 -0
  251. package/vendor/pi-tui/src/kill-ring.ts +47 -0
  252. package/vendor/pi-tui/src/latex.ts +1381 -0
  253. package/vendor/pi-tui/src/layout-node.ts +52 -0
  254. package/vendor/pi-tui/src/layout.ts +411 -0
  255. package/vendor/pi-tui/src/native-modifiers.ts +60 -0
  256. package/vendor/pi-tui/src/native-module-path.ts +32 -0
  257. package/vendor/pi-tui/src/stdin-buffer.ts +445 -0
  258. package/vendor/pi-tui/src/terminal-colors.ts +74 -0
  259. package/vendor/pi-tui/src/terminal-image.ts +701 -0
  260. package/vendor/pi-tui/src/terminal.ts +554 -0
  261. package/vendor/pi-tui/src/tui-alt-screen.ts +1379 -0
  262. package/vendor/pi-tui/src/tui-main-screen.ts +655 -0
  263. package/vendor/pi-tui/src/tui.ts +1264 -0
  264. package/vendor/pi-tui/src/undo-stack.ts +29 -0
  265. package/vendor/pi-tui/src/utils.ts +1327 -0
  266. package/vendor/pi-tui/src/word-navigation.ts +118 -0
  267. package/vendor/pi-tui/test/test-themes.ts +39 -0
  268. package/vendor/pi-tui/test/virtual-terminal.ts +219 -0
  269. package/CHANGELOG.md +0 -512
  270. package/bin/rovecode.js +0 -24
  271. package/dist/cli/app-dybnr56b.js +0 -2
  272. package/dist/cli/ask-user-p8hq4xgj.js +0 -2
  273. package/dist/cli/auth-login-ewpgw5sm.js +0 -2
  274. package/dist/cli/auth-m8p9grty.js +0 -2
  275. package/dist/cli/bench-xv3ypwev.js +0 -9
  276. package/dist/cli/catalog-737wb2s0.js +0 -2
  277. package/dist/cli/cli-arhg40m0.js +0 -2
  278. package/dist/cli/client-cf2pxx8q.js +0 -2
  279. package/dist/cli/commands-3p7e4xxs.js +0 -2
  280. package/dist/cli/connect-3q93d7cb.js +0 -2
  281. package/dist/cli/context-cmd-eqxmxhzq.js +0 -2
  282. package/dist/cli/context-report-hbw9zfes.js +0 -2
  283. package/dist/cli/count-remote-mby98cd0.js +0 -2
  284. package/dist/cli/design-122y0axd.js +0 -2
  285. package/dist/cli/dispatch-b4egzvvh.js +0 -2
  286. package/dist/cli/doctor-x4jkv72e.js +0 -3
  287. package/dist/cli/executor-ftvg6tsy.js +0 -2
  288. package/dist/cli/export-pdgdhkch.js +0 -2
  289. package/dist/cli/files-cez9a96p.js +0 -2
  290. package/dist/cli/gauntlet-r3xxaszc.js +0 -2
  291. package/dist/cli/gauntlet-runner-r515m7kk.js +0 -10
  292. package/dist/cli/gauntlet-wave3-bnkjk2v2.js +0 -5
  293. package/dist/cli/gauntlet-wave4-acs9s60q.js +0 -14
  294. package/dist/cli/hashline-ewg5hbe3.js +0 -2
  295. package/dist/cli/http-n0kehsk8.js +0 -5
  296. package/dist/cli/index-z5qt1s76.js +0 -2
  297. package/dist/cli/install-80mp63kx.js +0 -2
  298. package/dist/cli/loop-12twjcat.js +0 -2
  299. package/dist/cli/main-01pv9206.js +0 -4
  300. package/dist/cli/main-0jys2ccn.js +0 -3
  301. package/dist/cli/main-1ztz6fkj.js +0 -10
  302. package/dist/cli/main-23q7cmww.js +0 -9
  303. package/dist/cli/main-2rzbexn2.js +0 -3
  304. package/dist/cli/main-2wyax8k9.js +0 -9
  305. package/dist/cli/main-2yeveeve.js +0 -6
  306. package/dist/cli/main-2z3dek0b.js +0 -3
  307. package/dist/cli/main-2zgsknth.js +0 -3
  308. package/dist/cli/main-45ejth3a.js +0 -4
  309. package/dist/cli/main-45rn3trk.js +0 -22
  310. package/dist/cli/main-4p4e2w7x.js +0 -4
  311. package/dist/cli/main-4y0tnfpa.js +0 -16
  312. package/dist/cli/main-5py0rkmc.js +0 -4
  313. package/dist/cli/main-6dtqmbt6.js +0 -7
  314. package/dist/cli/main-6h9x282m.js +0 -4
  315. package/dist/cli/main-6vjeds42.js +0 -3
  316. package/dist/cli/main-78gq4bt9.js +0 -6
  317. package/dist/cli/main-7jd5vh3x.js +0 -4
  318. package/dist/cli/main-7kt6r53y.js +0 -4
  319. package/dist/cli/main-8c1tbazx.js +0 -58
  320. package/dist/cli/main-9a9rnh47.js +0 -19
  321. package/dist/cli/main-9ht36z12.js +0 -3
  322. package/dist/cli/main-a2yfvcy9.js +0 -7
  323. package/dist/cli/main-a3f51n0x.js +0 -5
  324. package/dist/cli/main-b8zq261k.js +0 -3
  325. package/dist/cli/main-bxtvnf6d.js +0 -13
  326. package/dist/cli/main-edxc3yzt.js +0 -4
  327. package/dist/cli/main-evgz4mp5.js +0 -21
  328. package/dist/cli/main-f33fc5je.js +0 -9
  329. package/dist/cli/main-fvnpq46y.js +0 -12
  330. package/dist/cli/main-gbbty4d4.js +0 -3
  331. package/dist/cli/main-gth53dnt.js +0 -25
  332. package/dist/cli/main-hqbz10aw.js +0 -9
  333. package/dist/cli/main-hrrvcfan.js +0 -38
  334. package/dist/cli/main-hzwtsb2m.js +0 -5
  335. package/dist/cli/main-j7ttv0sd.js +0 -34
  336. package/dist/cli/main-jak598k9.js +0 -5
  337. package/dist/cli/main-kba6zeyd.js +0 -6
  338. package/dist/cli/main-kwwsz6rq.js +0 -3
  339. package/dist/cli/main-m8vm17zq.js +0 -3
  340. package/dist/cli/main-mg4f96e1.js +0 -3
  341. package/dist/cli/main-mg9b20ac.js +0 -18
  342. package/dist/cli/main-mgb9ccnx.js +0 -3
  343. package/dist/cli/main-mjt2p7aj.js +0 -3
  344. package/dist/cli/main-n6qrdbmy.js +0 -3
  345. package/dist/cli/main-na7wse0x.js +0 -5
  346. package/dist/cli/main-nqveez48.js +0 -4
  347. package/dist/cli/main-ntqef02r.js +0 -10
  348. package/dist/cli/main-nvc3yjay.js +0 -136
  349. package/dist/cli/main-p0cfn6nr.js +0 -16
  350. package/dist/cli/main-qj2djy17.js +0 -19
  351. package/dist/cli/main-qsevpgsv.js +0 -3
  352. package/dist/cli/main-qvarybsp.js +0 -3
  353. package/dist/cli/main-rebtt91r.js +0 -5
  354. package/dist/cli/main-rpg7h8mb.js +0 -3
  355. package/dist/cli/main-rsy72qmw.js +0 -15
  356. package/dist/cli/main-rvetps99.js +0 -18
  357. package/dist/cli/main-s4bb0jav.js +0 -3
  358. package/dist/cli/main-s9v8k74e.js +0 -3
  359. package/dist/cli/main-tjvwmscs.js +0 -3
  360. package/dist/cli/main-tkgarpjj.js +0 -4
  361. package/dist/cli/main-v8y60bb2.js +0 -3
  362. package/dist/cli/main-vhrrq337.js +0 -3
  363. package/dist/cli/main-vp2dfb7s.js +0 -4
  364. package/dist/cli/main-vqbr22sz.js +0 -8
  365. package/dist/cli/main-vxnwe5xx.js +0 -18
  366. package/dist/cli/main-wgph00xf.js +0 -5
  367. package/dist/cli/main-wk2csfnj.js +0 -5
  368. package/dist/cli/main-wm997zjx.js +0 -3
  369. package/dist/cli/main-wpkyraxh.js +0 -3
  370. package/dist/cli/main-wqt32p5x.js +0 -4
  371. package/dist/cli/main-x9ct6y1a.js +0 -3
  372. package/dist/cli/main-xfekqh9m.js +0 -7
  373. package/dist/cli/main-xt9zc3n6.js +0 -7
  374. package/dist/cli/main-xx2z3zh5.js +0 -4
  375. package/dist/cli/main-y5c82rxr.js +0 -3
  376. package/dist/cli/main-yrjt2sqt.js +0 -14
  377. package/dist/cli/main-ys6zj3yr.js +0 -3
  378. package/dist/cli/main-ywbxshqc.js +0 -8
  379. package/dist/cli/main-z13755t8.js +0 -25
  380. package/dist/cli/main-zc7pyrbj.js +0 -4
  381. package/dist/cli/main.js +0 -279
  382. package/dist/cli/market-cmd-bm5xvn9f.js +0 -5
  383. package/dist/cli/mcp-login-bthtfpt7.js +0 -2
  384. package/dist/cli/mcp-market-cmd-mbeshfyd.js +0 -2
  385. package/dist/cli/notify-54v5z9dz.js +0 -2
  386. package/dist/cli/oauth-g5gme95c.js +0 -2
  387. package/dist/cli/output-satndjap.js +0 -16
  388. package/dist/cli/profiles-sfhpbq3m.js +0 -2
  389. package/dist/cli/provider-config-hv3xtdt4.js +0 -2
  390. package/dist/cli/provider-kwzq6g84.js +0 -2
  391. package/dist/cli/registry-fh0hdnyn.js +0 -2
  392. package/dist/cli/registry-y1y8e94r.js +0 -2
  393. package/dist/cli/repl-t4z03mqq.js +0 -11
  394. package/dist/cli/resume-fqt4chg8.js +0 -2
  395. package/dist/cli/run-flags-rysbag9t.js +0 -2
  396. package/dist/cli/runtime-j19fjbsa.js +0 -2
  397. package/dist/cli/sandbox-config-g4qxd7y5.js +0 -2
  398. package/dist/cli/server-r0b6bksk.js +0 -5
  399. package/dist/cli/session-arg-txmn5g4x.js +0 -2
  400. package/dist/cli/session-ed250d9j.js +0 -2
  401. package/dist/cli/sessions-cmd-adw7svfn.js +0 -7
  402. package/dist/cli/settings-y9rzcqx8.js +0 -2
  403. package/dist/cli/setup-jmbr11j0.js +0 -2
  404. package/dist/cli/sextant-smoke-tcth0vea.js +0 -5
  405. package/dist/cli/skills-cmd-zbdy99v6.js +0 -2
  406. package/dist/cli/smoke-1bg937kx.js +0 -8
  407. package/dist/cli/start-chat-p01cdks3.js +0 -12
  408. package/dist/cli/stream-4wmyaypz.js +0 -2
  409. package/dist/cli/task-eg4s093s.js +0 -2
  410. package/dist/cli/tasks-12v9rr9k.js +0 -2
  411. package/dist/cli/thinking-a5ngvqyh.js +0 -2
  412. package/dist/cli/todo-1wxpcecx.js +0 -2
  413. package/dist/cli/tools-2ftsya7w.js +0 -2
  414. package/dist/cli/tools-x1tj4fxm.js +0 -2
  415. package/dist/cli/trust-cmd-hccxehzb.js +0 -2
  416. package/dist/cli/update-check-ygt3vd7m.js +0 -2
  417. package/dist/cli/update-cmd-v23qhr8c.js +0 -2
  418. package/dist/cli/voice-g1gtck92.js +0 -2
  419. package/dist/cli/webfetch-0nnrjgb5.js +0 -2
  420. package/dist/cli/websearch-f0vr2p7d.js +0 -2
  421. package/dist/cli/workspace-9rq1w4ta.js +0 -2
  422. package/dist/lib/index.js +0 -62
  423. package/dist/lib/models-index.json +0 -1
  424. package/dist/lib/plugins.js +0 -6
  425. package/dist/lib/providers.js +0 -17
  426. package/dist/lib/public-api.js +0 -20
  427. package/dist/rovecode.exe +0 -4
  428. /package/{dist/cli → src/providers}/models-index.json +0 -0
@@ -0,0 +1,2364 @@
1
+ // @ts-nocheck -- vendored by rovecode: upstream-checked at pinned SHA 853a80d2; see ../PATCHES.md
2
+ import type { AutocompleteProvider, AutocompleteSuggestions } from "../autocomplete.ts";
3
+ import { getKeybindings } from "../keybindings.ts";
4
+ import { decodePrintableKey, matchesKey } from "../keys.ts";
5
+ import { KillRing } from "../kill-ring.ts";
6
+ import { type Component, CURSOR_MARKER, type Focusable, type TUI } from "../tui.ts";
7
+ import { UndoStack } from "../undo-stack.ts";
8
+ import {
9
+ cjkBreakRegex,
10
+ getGraphemeSegmenter,
11
+ getWordSegmenter,
12
+ isWhitespaceChar,
13
+ sliceByColumn,
14
+ visibleWidth,
15
+ } from "../utils.ts";
16
+ import { findWordBackward, findWordForward } from "../word-navigation.ts";
17
+ import { SelectList, type SelectListLayoutOptions, type SelectListTheme } from "./select-list.ts";
18
+
19
+ const graphemeSegmenter = getGraphemeSegmenter();
20
+ const wordSegmenter = getWordSegmenter();
21
+
22
+ /** Regex matching paste markers like `[paste #1 +123 lines]` or `[paste #2 1234 chars]`. */
23
+ const PASTE_MARKER_REGEX = /\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g;
24
+
25
+ /** Non-global version for single-segment testing. */
26
+ const PASTE_MARKER_SINGLE = /^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;
27
+
28
+ /** Check if a segment is a paste marker (i.e. was merged by segmentWithMarkers). */
29
+ function isPasteMarker(segment: string): boolean {
30
+ return segment.length >= 10 && PASTE_MARKER_SINGLE.test(segment);
31
+ }
32
+
33
+ /**
34
+ * A segmenter that wraps Intl.Segmenter and merges graphemes that fall
35
+ * within paste markers into single atomic segments. This makes cursor
36
+ * movement, deletion, word-wrap, etc. treat paste markers as single units.
37
+ *
38
+ * Only markers whose numeric ID exists in `validIds` are merged.
39
+ */
40
+ function segmentWithMarkers(
41
+ text: string,
42
+ baseSegmenter: Intl.Segmenter,
43
+ validIds: Set<number>,
44
+ ): Iterable<Intl.SegmentData> {
45
+ // Fast path: no paste markers in the text or no valid IDs.
46
+ if (validIds.size === 0 || !text.includes("[paste #")) {
47
+ return baseSegmenter.segment(text);
48
+ }
49
+
50
+ // Find all marker spans with valid IDs.
51
+ const markers: Array<{ start: number; end: number }> = [];
52
+ for (const m of text.matchAll(PASTE_MARKER_REGEX)) {
53
+ const id = Number.parseInt(m[1]!, 10);
54
+ if (!validIds.has(id)) continue;
55
+ markers.push({ start: m.index, end: m.index + m[0].length });
56
+ }
57
+ if (markers.length === 0) {
58
+ return baseSegmenter.segment(text);
59
+ }
60
+
61
+ // Build merged segment list.
62
+ const baseSegments = baseSegmenter.segment(text);
63
+ const result: Intl.SegmentData[] = [];
64
+ let markerIdx = 0;
65
+
66
+ for (const seg of baseSegments) {
67
+ // Skip past markers that are entirely before this segment.
68
+ while (markerIdx < markers.length && markers[markerIdx]!.end <= seg.index) {
69
+ markerIdx++;
70
+ }
71
+
72
+ const marker = markerIdx < markers.length ? markers[markerIdx]! : null;
73
+
74
+ if (marker && seg.index >= marker.start && seg.index < marker.end) {
75
+ // This segment falls inside a marker.
76
+ // If this is the first segment of the marker, emit a merged segment.
77
+ if (seg.index === marker.start) {
78
+ const markerText = text.slice(marker.start, marker.end);
79
+ result.push({
80
+ segment: markerText,
81
+ index: marker.start,
82
+ input: text,
83
+ });
84
+ }
85
+ // Otherwise skip (already merged into the first segment).
86
+ } else {
87
+ result.push(seg);
88
+ }
89
+ }
90
+
91
+ return result;
92
+ }
93
+
94
+ /**
95
+ * Represents a chunk of text for word-wrap layout.
96
+ * Tracks both the text content and its position in the original line.
97
+ */
98
+ export interface TextChunk {
99
+ text: string;
100
+ startIndex: number;
101
+ endIndex: number;
102
+ }
103
+
104
+ /**
105
+ * Split a line into word-wrapped chunks.
106
+ * Wraps at word boundaries when possible, falling back to character-level
107
+ * wrapping for words longer than the available width.
108
+ *
109
+ * @param line - The text line to wrap
110
+ * @param maxWidth - Maximum visible width per chunk
111
+ * @param preSegmented - Optional pre-segmented graphemes (e.g. with paste-marker awareness).
112
+ * When omitted the default Intl.Segmenter is used.
113
+ * @returns Array of chunks with text and position information
114
+ */
115
+ export function wordWrapLine(line: string, maxWidth: number, preSegmented?: Intl.SegmentData[]): TextChunk[] {
116
+ if (!line || maxWidth <= 0) {
117
+ return [{ text: "", startIndex: 0, endIndex: 0 }];
118
+ }
119
+
120
+ const lineWidth = visibleWidth(line);
121
+ if (lineWidth <= maxWidth) {
122
+ return [{ text: line, startIndex: 0, endIndex: line.length }];
123
+ }
124
+
125
+ const chunks: TextChunk[] = [];
126
+ const segments = preSegmented ?? [...graphemeSegmenter.segment(line)];
127
+
128
+ let currentWidth = 0;
129
+ let chunkStart = 0;
130
+
131
+ // Wrap opportunity: the position after the last whitespace before a non-whitespace
132
+ // grapheme, i.e. where a line break is allowed.
133
+ let wrapOppIndex = -1;
134
+ let wrapOppWidth = 0;
135
+
136
+ for (let i = 0; i < segments.length; i++) {
137
+ const seg = segments[i]!;
138
+ const grapheme = seg.segment;
139
+ const gWidth = visibleWidth(grapheme);
140
+ const charIndex = seg.index;
141
+ const isWs = !isPasteMarker(grapheme) && isWhitespaceChar(grapheme);
142
+
143
+ // Overflow check before advancing.
144
+ if (currentWidth + gWidth > maxWidth) {
145
+ if (wrapOppIndex >= 0 && currentWidth - wrapOppWidth + gWidth <= maxWidth) {
146
+ // Backtrack to last wrap opportunity (the remaining content
147
+ // plus the current grapheme still fits within maxWidth).
148
+ chunks.push({ text: line.slice(chunkStart, wrapOppIndex), startIndex: chunkStart, endIndex: wrapOppIndex });
149
+ chunkStart = wrapOppIndex;
150
+ currentWidth -= wrapOppWidth;
151
+ } else if (chunkStart < charIndex) {
152
+ // No viable wrap opportunity: force-break at current position.
153
+ // This also handles the case where backtracking to a word
154
+ // boundary wouldn't help because the remaining content plus
155
+ // the current grapheme (e.g. a wide character) still exceeds
156
+ // maxWidth.
157
+ chunks.push({ text: line.slice(chunkStart, charIndex), startIndex: chunkStart, endIndex: charIndex });
158
+ chunkStart = charIndex;
159
+ currentWidth = 0;
160
+ }
161
+ wrapOppIndex = -1;
162
+ }
163
+
164
+ if (gWidth > maxWidth) {
165
+ // Single atomic segment wider than maxWidth (e.g. paste marker
166
+ // in a narrow terminal). Re-wrap it at grapheme granularity.
167
+
168
+ // The segment remains logically atomic for cursor
169
+ // movement / editing — the split is purely visual for word-wrap layout.
170
+ const subChunks = wordWrapLine(grapheme, maxWidth);
171
+ for (let j = 0; j < subChunks.length - 1; j++) {
172
+ const sc = subChunks[j]!;
173
+ chunks.push({ text: sc.text, startIndex: charIndex + sc.startIndex, endIndex: charIndex + sc.endIndex });
174
+ }
175
+ const last = subChunks[subChunks.length - 1]!;
176
+ chunkStart = charIndex + last.startIndex;
177
+ currentWidth = visibleWidth(last.text);
178
+ wrapOppIndex = -1;
179
+ continue;
180
+ }
181
+
182
+ // Advance.
183
+ currentWidth += gWidth;
184
+
185
+ // Record wrap opportunity: whitespace followed by non-whitespace
186
+ // (multiple spaces join; the break point is after the last space),
187
+ // or at a boundary where either side is CJK (CJK allows breaking
188
+ // between any adjacent characters).
189
+ const next = segments[i + 1];
190
+ if (isWs && next && (isPasteMarker(next.segment) || !isWhitespaceChar(next.segment))) {
191
+ wrapOppIndex = next.index;
192
+ wrapOppWidth = currentWidth;
193
+ } else if (!isWs && next && !isWhitespaceChar(next.segment)) {
194
+ const isCjk = !isPasteMarker(grapheme) && cjkBreakRegex.test(grapheme);
195
+ const nextIsCjk = !isPasteMarker(next.segment) && cjkBreakRegex.test(next.segment);
196
+ if (isCjk || nextIsCjk) {
197
+ wrapOppIndex = next.index;
198
+ wrapOppWidth = currentWidth;
199
+ }
200
+ }
201
+ }
202
+
203
+ // Push final chunk.
204
+ chunks.push({ text: line.slice(chunkStart), startIndex: chunkStart, endIndex: line.length });
205
+
206
+ return chunks;
207
+ }
208
+
209
+ // Kitty CSI-u sequences for printable keys, including optional shifted/base codepoints.
210
+ interface EditorState {
211
+ lines: string[];
212
+ cursorLine: number;
213
+ cursorCol: number;
214
+ }
215
+
216
+ /** Undo snapshot: editor text state plus the paste registry. */
217
+ interface EditorSnapshot {
218
+ state: EditorState;
219
+ pastes: Map<number, string>;
220
+ pasteCounter: number;
221
+ }
222
+
223
+ interface LayoutLine {
224
+ text: string;
225
+ hasCursor: boolean;
226
+ cursorPos?: number;
227
+ }
228
+
229
+ export interface EditorTheme {
230
+ borderColor: (str: string) => string;
231
+ selectList: SelectListTheme;
232
+ }
233
+
234
+ export interface EditorOptions {
235
+ paddingX?: number;
236
+ autocompleteMaxVisible?: number;
237
+ }
238
+
239
+ const SLASH_COMMAND_SELECT_LIST_LAYOUT: SelectListLayoutOptions = {
240
+ minPrimaryColumnWidth: 12,
241
+ maxPrimaryColumnWidth: 32,
242
+ };
243
+
244
+ const ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS = 20;
245
+ const DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS = ["@", "#"];
246
+
247
+ function escapeCharacterClass(value: string): string {
248
+ return value.replace(/[\\^$.*+?()[\]{}|-]/g, "\\$&");
249
+ }
250
+
251
+ function buildTriggerPattern(triggerCharacters: string[]): RegExp {
252
+ return new RegExp(`(?:^|[\\s])[${triggerCharacters.map(escapeCharacterClass).join("")}][^\\s]*$`);
253
+ }
254
+
255
+ function buildDebouncePattern(triggerCharacters: string[]): RegExp {
256
+ const escapedWithoutAt = triggerCharacters.filter((character) => character !== "@").map(escapeCharacterClass);
257
+ return new RegExp(`(?:^|[ \\t])(?:@(?:"[^"]*|[^\\s]*)|[${escapedWithoutAt.join("")}][^\\s]*)$`);
258
+ }
259
+
260
+ function createScrollBorder(direction: "↑" | "↓", hiddenLineCount: number, width: number): string {
261
+ const availableWidth = Math.max(0, width);
262
+ const indicator = `─── ${direction} ${hiddenLineCount} more `;
263
+ const remaining = availableWidth - visibleWidth(indicator);
264
+ if (remaining >= 0) return indicator + "─".repeat(remaining);
265
+
266
+ const ellipsis = "...".slice(0, availableWidth);
267
+ const indicatorWidth = availableWidth - visibleWidth(ellipsis);
268
+ return sliceByColumn(indicator, 0, indicatorWidth, true) + ellipsis;
269
+ }
270
+
271
+ export class Editor implements Component, Focusable {
272
+ private state: EditorState = {
273
+ lines: [""],
274
+ cursorLine: 0,
275
+ cursorCol: 0,
276
+ };
277
+
278
+ /** Focusable interface - set by TUI when focus changes */
279
+ focused: boolean = false;
280
+
281
+ protected tui: TUI;
282
+ private theme: EditorTheme;
283
+ private paddingX: number = 0;
284
+
285
+ // Store last render width for cursor navigation
286
+ private lastWidth: number = 80;
287
+
288
+ // Vertical scrolling support
289
+ private scrollOffset: number = 0;
290
+
291
+ // Border color (can be changed dynamically)
292
+ public borderColor: (str: string) => string;
293
+
294
+ // Autocomplete support
295
+ private autocompleteProvider?: AutocompleteProvider;
296
+ private autocompleteTriggerCharacters = [...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS];
297
+ private autocompleteTriggerPattern = buildTriggerPattern(this.autocompleteTriggerCharacters);
298
+ private autocompleteDebouncePattern = buildDebouncePattern(this.autocompleteTriggerCharacters);
299
+ private autocompleteList?: SelectList;
300
+ private autocompleteState: "regular" | "force" | null = null;
301
+ private autocompletePrefix: string = "";
302
+ private autocompleteMaxVisible: number = 5;
303
+ private autocompleteAbort?: AbortController;
304
+ private autocompleteDebounceTimer?: ReturnType<typeof setTimeout>;
305
+ private autocompleteRequestTask: Promise<void> = Promise.resolve();
306
+ private autocompleteStartToken: number = 0;
307
+ private autocompleteRequestId: number = 0;
308
+
309
+ // Paste tracking for large pastes
310
+ private pastes: Map<number, string> = new Map();
311
+ private pasteCounter: number = 0;
312
+
313
+ // Bracketed paste mode buffering
314
+ private pasteBuffer: string = "";
315
+ private isInPaste: boolean = false;
316
+
317
+ // Prompt history for up/down navigation
318
+ private history: string[] = [];
319
+ private historyIndex: number = -1; // -1 = not browsing, 0 = most recent, 1 = older, etc.
320
+ private historyDraft: EditorState | null = null;
321
+
322
+ // Kill ring for Emacs-style kill/yank operations
323
+ private killRing = new KillRing();
324
+ private lastAction: "kill" | "yank" | "type-word" | null = null;
325
+
326
+ // Character jump mode
327
+ private jumpMode: "forward" | "backward" | null = null;
328
+
329
+ // Preferred visual column for vertical cursor movement (sticky column)
330
+ private preferredVisualCol: number | null = null;
331
+
332
+ // When the cursor is snapped to the start of an atomic segment, e.g. a
333
+ // paste marker, cursorCol no longer reflects where the cursor would have
334
+ // landed. This field stores the pre-snap cursorCol so that the next
335
+ // vertical move can resolve it to a visual column on whatever VL it belongs
336
+ // to.
337
+ private snappedFromCursorCol: number | null = null;
338
+
339
+ // Undo support
340
+ private undoStack = new UndoStack<EditorSnapshot>();
341
+
342
+ public onSubmit?: (text: string) => void;
343
+ public onChange?: (text: string) => void;
344
+ public disableSubmit: boolean = false;
345
+
346
+ constructor(tui: TUI, theme: EditorTheme, options: EditorOptions = {}) {
347
+ this.tui = tui;
348
+ this.theme = theme;
349
+ this.borderColor = theme.borderColor;
350
+ const paddingX = options.paddingX ?? 0;
351
+ this.paddingX = Number.isFinite(paddingX) ? Math.max(0, Math.floor(paddingX)) : 0;
352
+ const maxVisible = options.autocompleteMaxVisible ?? 5;
353
+ this.autocompleteMaxVisible = Number.isFinite(maxVisible) ? Math.max(3, Math.min(20, Math.floor(maxVisible))) : 5;
354
+ }
355
+
356
+ /** Set of currently valid paste IDs, for marker-aware segmentation. */
357
+ private validPasteIds(): Set<number> {
358
+ return new Set(this.pastes.keys());
359
+ }
360
+
361
+ /** Segment text with paste-marker awareness, only merging markers with valid IDs. */
362
+ private segment(text: string, mode: "word" | "grapheme"): Iterable<Intl.SegmentData> {
363
+ return segmentWithMarkers(text, mode === "word" ? wordSegmenter : graphemeSegmenter, this.validPasteIds());
364
+ }
365
+
366
+ getPaddingX(): number {
367
+ return this.paddingX;
368
+ }
369
+
370
+ setPaddingX(padding: number): void {
371
+ const newPadding = Number.isFinite(padding) ? Math.max(0, Math.floor(padding)) : 0;
372
+ if (this.paddingX !== newPadding) {
373
+ this.paddingX = newPadding;
374
+ this.tui.requestRender();
375
+ }
376
+ }
377
+
378
+ getAutocompleteMaxVisible(): number {
379
+ return this.autocompleteMaxVisible;
380
+ }
381
+
382
+ setAutocompleteMaxVisible(maxVisible: number): void {
383
+ const newMaxVisible = Number.isFinite(maxVisible) ? Math.max(3, Math.min(20, Math.floor(maxVisible))) : 5;
384
+ if (this.autocompleteMaxVisible !== newMaxVisible) {
385
+ this.autocompleteMaxVisible = newMaxVisible;
386
+ this.tui.requestRender();
387
+ }
388
+ }
389
+
390
+ setAutocompleteProvider(provider: AutocompleteProvider): void {
391
+ this.cancelAutocomplete();
392
+ this.autocompleteProvider = provider;
393
+ this.setAutocompleteTriggerCharacters(provider.triggerCharacters ?? []);
394
+ }
395
+
396
+ /**
397
+ * Add a prompt to history for up/down arrow navigation.
398
+ * Called after successful submission.
399
+ */
400
+ addToHistory(text: string): void {
401
+ const trimmed = text.trim();
402
+ if (!trimmed) return;
403
+ // Don't add consecutive duplicates
404
+ if (this.history.length > 0 && this.history[0] === trimmed) return;
405
+ this.history.unshift(trimmed);
406
+ // Limit history size
407
+ if (this.history.length > 100) {
408
+ this.history.pop();
409
+ }
410
+ }
411
+
412
+ private isEditorEmpty(): boolean {
413
+ return this.state.lines.length === 1 && this.state.lines[0] === "";
414
+ }
415
+
416
+ private isOnFirstVisualLine(): boolean {
417
+ const visualLines = this.buildVisualLineMap(this.lastWidth);
418
+ const currentVisualLine = this.findCurrentVisualLine(visualLines);
419
+ return currentVisualLine === 0;
420
+ }
421
+
422
+ private isOnLastVisualLine(): boolean {
423
+ const visualLines = this.buildVisualLineMap(this.lastWidth);
424
+ const currentVisualLine = this.findCurrentVisualLine(visualLines);
425
+ return currentVisualLine === visualLines.length - 1;
426
+ }
427
+
428
+ private navigateHistory(direction: 1 | -1): void {
429
+ this.lastAction = null;
430
+ if (this.history.length === 0) return;
431
+
432
+ const newIndex = this.historyIndex - direction; // Up(-1) increases index, Down(1) decreases
433
+ if (newIndex < -1 || newIndex >= this.history.length) return;
434
+
435
+ // Capture state when first entering history browsing mode
436
+ if (this.historyIndex === -1 && newIndex >= 0) {
437
+ this.pushUndoSnapshot();
438
+ this.historyDraft = structuredClone(this.state);
439
+ }
440
+
441
+ this.historyIndex = newIndex;
442
+
443
+ if (this.historyIndex === -1) {
444
+ const draft = this.historyDraft;
445
+ this.historyDraft = null;
446
+ if (draft) {
447
+ this.state = draft;
448
+ this.preferredVisualCol = null;
449
+ this.snappedFromCursorCol = null;
450
+ this.scrollOffset = 0;
451
+ if (this.onChange) this.onChange(this.getText());
452
+ } else {
453
+ this.setTextInternal("");
454
+ }
455
+ } else {
456
+ this.setTextInternal(this.history[this.historyIndex] || "", direction === -1 ? "start" : "end");
457
+ }
458
+ }
459
+
460
+ private exitHistoryBrowsing(): void {
461
+ this.historyIndex = -1;
462
+ this.historyDraft = null;
463
+ }
464
+
465
+ /** Internal setText that doesn't reset history state - used by navigateHistory */
466
+ private setTextInternal(text: string, cursorPlacement: "start" | "end" = "end"): void {
467
+ const lines = text.split("\n");
468
+ this.state.lines = lines.length === 0 ? [""] : lines;
469
+ this.state.cursorLine = cursorPlacement === "start" ? 0 : this.state.lines.length - 1;
470
+ this.setCursorCol(cursorPlacement === "start" ? 0 : this.state.lines[this.state.cursorLine]?.length || 0);
471
+ // Reset scroll - render() will adjust to show cursor
472
+ this.scrollOffset = 0;
473
+
474
+ if (this.onChange) {
475
+ this.onChange(this.getText());
476
+ }
477
+ }
478
+
479
+ invalidate(): void {
480
+ // No cached state to invalidate currently
481
+ }
482
+
483
+ render(width: number): string[] {
484
+ const maxPadding = Math.max(0, Math.floor((width - 1) / 2));
485
+ const paddingX = Math.min(this.paddingX, maxPadding);
486
+ const contentWidth = Math.max(1, width - paddingX * 2);
487
+
488
+ // Layout width: with padding the cursor can overflow into it,
489
+ // without padding we reserve 1 column for the cursor.
490
+ const layoutWidth = Math.max(1, contentWidth - (paddingX ? 0 : 1));
491
+
492
+ // Store for cursor navigation (must match wrapping width)
493
+ this.lastWidth = layoutWidth;
494
+
495
+ const horizontal = this.borderColor("─");
496
+
497
+ // Layout the text
498
+ const layoutLines = this.layoutText(layoutWidth);
499
+
500
+ // Calculate max visible lines: 30% of terminal height, minimum 5 lines
501
+ const terminalRows = this.tui.terminal.rows;
502
+ const maxVisibleLines = Math.max(5, Math.floor(terminalRows * 0.3));
503
+
504
+ // Find the cursor line index in layoutLines
505
+ let cursorLineIndex = layoutLines.findIndex((line) => line.hasCursor);
506
+ if (cursorLineIndex === -1) cursorLineIndex = 0;
507
+
508
+ // Adjust scroll offset to keep cursor visible
509
+ if (cursorLineIndex < this.scrollOffset) {
510
+ this.scrollOffset = cursorLineIndex;
511
+ } else if (cursorLineIndex >= this.scrollOffset + maxVisibleLines) {
512
+ this.scrollOffset = cursorLineIndex - maxVisibleLines + 1;
513
+ }
514
+
515
+ // Clamp scroll offset to valid range
516
+ const maxScrollOffset = Math.max(0, layoutLines.length - maxVisibleLines);
517
+ this.scrollOffset = Math.max(0, Math.min(this.scrollOffset, maxScrollOffset));
518
+
519
+ // Get visible lines slice
520
+ const visibleLines = layoutLines.slice(this.scrollOffset, this.scrollOffset + maxVisibleLines);
521
+
522
+ const result: string[] = [];
523
+ const leftPadding = " ".repeat(paddingX);
524
+ const rightPadding = leftPadding;
525
+
526
+ // Render top border (with scroll indicator if scrolled down)
527
+ if (this.scrollOffset > 0) {
528
+ const border = createScrollBorder("↑", this.scrollOffset, width);
529
+ result.push(this.borderColor(border));
530
+ } else {
531
+ result.push(horizontal.repeat(width));
532
+ }
533
+
534
+ // Render each visible layout line
535
+ // Emit hardware cursor marker when focused so TUI can position the
536
+ // hardware cursor for IME candidate-window placement even while
537
+ // autocomplete (e.g. slash-command menu) is visible.
538
+ const emitCursorMarker = this.focused;
539
+
540
+ for (const layoutLine of visibleLines) {
541
+ let displayText = layoutLine.text;
542
+ let lineVisibleWidth = visibleWidth(layoutLine.text);
543
+ let cursorInPadding = false;
544
+
545
+ // Add cursor if this line has it
546
+ if (layoutLine.hasCursor && layoutLine.cursorPos !== undefined) {
547
+ const before = displayText.slice(0, layoutLine.cursorPos);
548
+ const after = displayText.slice(layoutLine.cursorPos);
549
+
550
+ // Hardware cursor marker (zero-width, emitted before fake cursor for IME positioning)
551
+ const marker = emitCursorMarker ? CURSOR_MARKER : "";
552
+
553
+ if (after.length > 0) {
554
+ // Cursor is on a character (grapheme) - replace it with highlighted version
555
+ // Get the first grapheme from 'after'
556
+ const afterGraphemes = [...this.segment(after, "grapheme")];
557
+ const firstGrapheme = afterGraphemes[0]?.segment || "";
558
+ const restAfter = after.slice(firstGrapheme.length);
559
+ const cursor = `\x1b[7m${firstGrapheme}\x1b[0m`;
560
+ displayText = before + marker + cursor + restAfter;
561
+ // lineVisibleWidth stays the same - we're replacing, not adding
562
+ } else {
563
+ // Cursor is at the end - add highlighted space
564
+ const cursor = "\x1b[7m \x1b[0m";
565
+ displayText = before + marker + cursor;
566
+ lineVisibleWidth = lineVisibleWidth + 1;
567
+ // If cursor overflows content width into the padding, flag it
568
+ if (lineVisibleWidth > contentWidth && paddingX > 0) {
569
+ cursorInPadding = true;
570
+ }
571
+ }
572
+ }
573
+
574
+ // Calculate padding based on actual visible width
575
+ const padding = " ".repeat(Math.max(0, contentWidth - lineVisibleWidth));
576
+ const lineRightPadding = cursorInPadding ? rightPadding.slice(1) : rightPadding;
577
+
578
+ // Render the line (no side borders, just horizontal lines above and below)
579
+ result.push(`${leftPadding}${displayText}${padding}${lineRightPadding}`);
580
+ }
581
+
582
+ // Render bottom border (with scroll indicator if more content below)
583
+ const linesBelow = layoutLines.length - (this.scrollOffset + visibleLines.length);
584
+ if (linesBelow > 0) {
585
+ const border = createScrollBorder("↓", linesBelow, width);
586
+ result.push(this.borderColor(border));
587
+ } else {
588
+ result.push(horizontal.repeat(width));
589
+ }
590
+
591
+ // Add autocomplete list if active
592
+ if (this.autocompleteState && this.autocompleteList) {
593
+ const autocompleteResult = this.autocompleteList.render(contentWidth);
594
+ for (const line of autocompleteResult) {
595
+ const lineWidth = visibleWidth(line);
596
+ const linePadding = " ".repeat(Math.max(0, contentWidth - lineWidth));
597
+ result.push(`${leftPadding}${line}${linePadding}${rightPadding}`);
598
+ }
599
+ }
600
+
601
+ return result;
602
+ }
603
+
604
+ handleInput(data: string): void {
605
+ const kb = getKeybindings();
606
+
607
+ // Handle character jump mode (awaiting next character to jump to)
608
+ if (this.jumpMode !== null) {
609
+ // Cancel if the hotkey is pressed again
610
+ if (kb.matches(data, "tui.editor.jumpForward") || kb.matches(data, "tui.editor.jumpBackward")) {
611
+ this.jumpMode = null;
612
+ return;
613
+ }
614
+
615
+ const printable = decodePrintableKey(data) ?? (data.charCodeAt(0) >= 32 ? data : undefined);
616
+ if (printable !== undefined) {
617
+ // Printable character - perform the jump
618
+ const direction = this.jumpMode;
619
+ this.jumpMode = null;
620
+ this.jumpToChar(printable, direction);
621
+ return;
622
+ }
623
+
624
+ // Control character - cancel and fall through to normal handling
625
+ this.jumpMode = null;
626
+ }
627
+
628
+ // Handle bracketed paste mode
629
+ if (data.includes("\x1b[200~")) {
630
+ this.isInPaste = true;
631
+ this.pasteBuffer = "";
632
+ data = data.replace("\x1b[200~", "");
633
+ }
634
+
635
+ if (this.isInPaste) {
636
+ this.pasteBuffer += data;
637
+ const endIndex = this.pasteBuffer.indexOf("\x1b[201~");
638
+ if (endIndex !== -1) {
639
+ const pasteContent = this.pasteBuffer.substring(0, endIndex);
640
+ if (pasteContent.length > 0) {
641
+ this.handlePaste(pasteContent);
642
+ }
643
+ this.isInPaste = false;
644
+ const remaining = this.pasteBuffer.substring(endIndex + 6);
645
+ this.pasteBuffer = "";
646
+ if (remaining.length > 0) {
647
+ this.handleInput(remaining);
648
+ }
649
+ return;
650
+ }
651
+ return;
652
+ }
653
+
654
+ // Ctrl+C - let parent handle (exit/clear)
655
+ if (kb.matches(data, "tui.input.copy")) {
656
+ return;
657
+ }
658
+
659
+ // Undo
660
+ if (kb.matches(data, "tui.editor.undo")) {
661
+ this.undo();
662
+ return;
663
+ }
664
+
665
+ // Handle autocomplete mode
666
+ if (this.autocompleteState && this.autocompleteList) {
667
+ if (kb.matches(data, "tui.select.cancel")) {
668
+ this.cancelAutocomplete();
669
+ return;
670
+ }
671
+
672
+ if (kb.matches(data, "tui.select.up") || kb.matches(data, "tui.select.down")) {
673
+ this.autocompleteList.handleInput(data);
674
+ return;
675
+ }
676
+
677
+ if (kb.matches(data, "tui.input.tab")) {
678
+ const selected = this.autocompleteList.getSelectedItem();
679
+ if (selected && this.autocompleteProvider) {
680
+ this.pushUndoSnapshot();
681
+ this.lastAction = null;
682
+ const result = this.autocompleteProvider.applyCompletion(
683
+ this.state.lines,
684
+ this.state.cursorLine,
685
+ this.state.cursorCol,
686
+ selected,
687
+ this.autocompletePrefix,
688
+ );
689
+ this.state.lines = result.lines;
690
+ this.state.cursorLine = result.cursorLine;
691
+ this.setCursorCol(result.cursorCol);
692
+ this.cancelAutocomplete();
693
+ if (this.onChange) this.onChange(this.getText());
694
+ }
695
+ return;
696
+ }
697
+
698
+ if (kb.matches(data, "tui.select.confirm")) {
699
+ const selected = this.autocompleteList.getSelectedItem();
700
+ if (selected && this.autocompleteProvider) {
701
+ this.pushUndoSnapshot();
702
+ this.lastAction = null;
703
+ const result = this.autocompleteProvider.applyCompletion(
704
+ this.state.lines,
705
+ this.state.cursorLine,
706
+ this.state.cursorCol,
707
+ selected,
708
+ this.autocompletePrefix,
709
+ );
710
+ this.state.lines = result.lines;
711
+ this.state.cursorLine = result.cursorLine;
712
+ this.setCursorCol(result.cursorCol);
713
+
714
+ if (this.autocompletePrefix.startsWith("/")) {
715
+ this.cancelAutocomplete();
716
+ // Fall through to submit
717
+ } else {
718
+ this.cancelAutocomplete();
719
+ if (this.onChange) this.onChange(this.getText());
720
+ return;
721
+ }
722
+ }
723
+ }
724
+ }
725
+
726
+ // Tab - trigger completion
727
+ if (kb.matches(data, "tui.input.tab") && !this.autocompleteState) {
728
+ this.handleTabCompletion();
729
+ return;
730
+ }
731
+
732
+ // Deletion actions
733
+ if (kb.matches(data, "tui.editor.deleteToLineEnd")) {
734
+ this.deleteToEndOfLine();
735
+ return;
736
+ }
737
+ if (kb.matches(data, "tui.editor.deleteToLineStart")) {
738
+ this.deleteToStartOfLine();
739
+ return;
740
+ }
741
+ if (kb.matches(data, "tui.editor.deleteWordBackward")) {
742
+ this.deleteWordBackwards();
743
+ return;
744
+ }
745
+ if (kb.matches(data, "tui.editor.deleteWordForward")) {
746
+ this.deleteWordForward();
747
+ return;
748
+ }
749
+ if (kb.matches(data, "tui.editor.deleteCharBackward") || matchesKey(data, "shift+backspace")) {
750
+ this.handleBackspace();
751
+ return;
752
+ }
753
+ if (kb.matches(data, "tui.editor.deleteCharForward") || matchesKey(data, "shift+delete")) {
754
+ this.handleForwardDelete();
755
+ return;
756
+ }
757
+
758
+ // Kill ring actions
759
+ if (kb.matches(data, "tui.editor.yank")) {
760
+ this.yank();
761
+ return;
762
+ }
763
+ if (kb.matches(data, "tui.editor.yankPop")) {
764
+ this.yankPop();
765
+ return;
766
+ }
767
+
768
+ // Dedicated history actions always browse entries instead of moving the cursor.
769
+ if (kb.matches(data, "tui.editor.historyPrevious")) {
770
+ this.cancelAutocomplete();
771
+ this.navigateHistory(-1);
772
+ return;
773
+ }
774
+ if (kb.matches(data, "tui.editor.historyNext")) {
775
+ this.cancelAutocomplete();
776
+ this.navigateHistory(1);
777
+ return;
778
+ }
779
+
780
+ // Cursor movement actions
781
+ if (kb.matches(data, "tui.editor.cursorLineStart")) {
782
+ this.moveToLineStart();
783
+ return;
784
+ }
785
+ if (kb.matches(data, "tui.editor.cursorLineEnd")) {
786
+ this.moveToLineEnd();
787
+ return;
788
+ }
789
+ if (kb.matches(data, "tui.editor.cursorWordLeft")) {
790
+ this.moveWordBackwards();
791
+ return;
792
+ }
793
+ if (kb.matches(data, "tui.editor.cursorWordRight")) {
794
+ this.moveWordForwards();
795
+ return;
796
+ }
797
+
798
+ // New line
799
+ if (
800
+ kb.matches(data, "tui.input.newLine") ||
801
+ (data.charCodeAt(0) === 10 && data.length > 1) ||
802
+ data === "\x1b\r" ||
803
+ data === "\x1b[13;2~" ||
804
+ (data.length > 1 && data.includes("\x1b") && data.includes("\r")) ||
805
+ (data === "\n" && data.length === 1)
806
+ ) {
807
+ if (this.shouldSubmitOnBackslashEnter(data, kb)) {
808
+ this.handleBackspace();
809
+ this.submitValue();
810
+ return;
811
+ }
812
+ this.addNewLine();
813
+ return;
814
+ }
815
+
816
+ // Submit (Enter)
817
+ if (kb.matches(data, "tui.input.submit")) {
818
+ if (this.disableSubmit) return;
819
+
820
+ // Workaround for terminals without Shift+Enter support:
821
+ // If char before cursor is \, delete it and insert newline instead of submitting.
822
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
823
+ if (this.state.cursorCol > 0 && currentLine[this.state.cursorCol - 1] === "\\") {
824
+ this.handleBackspace();
825
+ this.addNewLine();
826
+ return;
827
+ }
828
+
829
+ this.submitValue();
830
+ return;
831
+ }
832
+
833
+ // Arrow key navigation (with history support)
834
+ if (kb.matches(data, "tui.editor.cursorUp")) {
835
+ if (
836
+ this.isOnFirstVisualLine() &&
837
+ (this.isEditorEmpty() || this.historyIndex > -1 || this.state.cursorCol === 0)
838
+ ) {
839
+ this.navigateHistory(-1);
840
+ } else if (this.isOnFirstVisualLine()) {
841
+ // Already at top - jump to start of line
842
+ this.moveToLineStart();
843
+ } else {
844
+ this.moveCursor(-1, 0);
845
+ }
846
+ return;
847
+ }
848
+ if (kb.matches(data, "tui.editor.cursorDown")) {
849
+ if (this.historyIndex > -1 && this.isOnLastVisualLine()) {
850
+ this.navigateHistory(1);
851
+ } else if (this.isOnLastVisualLine()) {
852
+ // Already at bottom - jump to end of line
853
+ this.moveToLineEnd();
854
+ } else {
855
+ this.moveCursor(1, 0);
856
+ }
857
+ return;
858
+ }
859
+ if (kb.matches(data, "tui.editor.cursorRight")) {
860
+ this.moveCursor(0, 1);
861
+ return;
862
+ }
863
+ if (kb.matches(data, "tui.editor.cursorLeft")) {
864
+ this.moveCursor(0, -1);
865
+ return;
866
+ }
867
+
868
+ // Page up/down - scroll by page and move cursor
869
+ if (kb.matches(data, "tui.editor.pageUp")) {
870
+ this.pageScroll(-1);
871
+ return;
872
+ }
873
+ if (kb.matches(data, "tui.editor.pageDown")) {
874
+ this.pageScroll(1);
875
+ return;
876
+ }
877
+
878
+ // Character jump mode triggers
879
+ if (kb.matches(data, "tui.editor.jumpForward")) {
880
+ this.jumpMode = "forward";
881
+ return;
882
+ }
883
+ if (kb.matches(data, "tui.editor.jumpBackward")) {
884
+ this.jumpMode = "backward";
885
+ return;
886
+ }
887
+
888
+ // Shift+Space - insert regular space
889
+ if (matchesKey(data, "shift+space")) {
890
+ this.insertCharacter(" ");
891
+ return;
892
+ }
893
+
894
+ const printable = decodePrintableKey(data);
895
+ if (printable !== undefined) {
896
+ this.insertCharacter(printable);
897
+ return;
898
+ }
899
+
900
+ // Regular characters
901
+ if (data.charCodeAt(0) >= 32) {
902
+ this.insertCharacter(data);
903
+ }
904
+ }
905
+
906
+ private layoutText(contentWidth: number): LayoutLine[] {
907
+ const layoutLines: LayoutLine[] = [];
908
+
909
+ if (this.state.lines.length === 0 || (this.state.lines.length === 1 && this.state.lines[0] === "")) {
910
+ // Empty editor
911
+ layoutLines.push({
912
+ text: "",
913
+ hasCursor: true,
914
+ cursorPos: 0,
915
+ });
916
+ return layoutLines;
917
+ }
918
+
919
+ // Process each logical line
920
+ for (let i = 0; i < this.state.lines.length; i++) {
921
+ const line = this.state.lines[i] || "";
922
+ const isCurrentLine = i === this.state.cursorLine;
923
+ const lineVisibleWidth = visibleWidth(line);
924
+
925
+ if (lineVisibleWidth <= contentWidth) {
926
+ // Line fits in one layout line
927
+ if (isCurrentLine) {
928
+ layoutLines.push({
929
+ text: line,
930
+ hasCursor: true,
931
+ cursorPos: this.state.cursorCol,
932
+ });
933
+ } else {
934
+ layoutLines.push({
935
+ text: line,
936
+ hasCursor: false,
937
+ });
938
+ }
939
+ } else {
940
+ // Line needs wrapping - use word-aware wrapping
941
+ const chunks = wordWrapLine(line, contentWidth, [...this.segment(line, "grapheme")]);
942
+
943
+ for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
944
+ const chunk = chunks[chunkIndex];
945
+ if (!chunk) continue;
946
+
947
+ const cursorPos = this.state.cursorCol;
948
+ const isLastChunk = chunkIndex === chunks.length - 1;
949
+
950
+ // Determine if cursor is in this chunk
951
+ // For word-wrapped chunks, we need to handle the case where
952
+ // cursor might be in trimmed whitespace at end of chunk
953
+ let hasCursorInChunk = false;
954
+ let adjustedCursorPos = 0;
955
+
956
+ if (isCurrentLine) {
957
+ if (isLastChunk) {
958
+ // Last chunk: cursor belongs here if >= startIndex
959
+ hasCursorInChunk = cursorPos >= chunk.startIndex;
960
+ adjustedCursorPos = cursorPos - chunk.startIndex;
961
+ } else {
962
+ // Non-last chunk: cursor belongs here if in range [startIndex, endIndex)
963
+ // But we need to handle the visual position in the trimmed text
964
+ hasCursorInChunk = cursorPos >= chunk.startIndex && cursorPos < chunk.endIndex;
965
+ if (hasCursorInChunk) {
966
+ adjustedCursorPos = cursorPos - chunk.startIndex;
967
+ // Clamp to text length (in case cursor was in trimmed whitespace)
968
+ if (adjustedCursorPos > chunk.text.length) {
969
+ adjustedCursorPos = chunk.text.length;
970
+ }
971
+ }
972
+ }
973
+ }
974
+
975
+ if (hasCursorInChunk) {
976
+ layoutLines.push({
977
+ text: chunk.text,
978
+ hasCursor: true,
979
+ cursorPos: adjustedCursorPos,
980
+ });
981
+ } else {
982
+ layoutLines.push({
983
+ text: chunk.text,
984
+ hasCursor: false,
985
+ });
986
+ }
987
+ }
988
+ }
989
+ }
990
+
991
+ return layoutLines;
992
+ }
993
+
994
+ getText(): string {
995
+ return this.state.lines.join("\n");
996
+ }
997
+
998
+ private expandPasteMarkers(text: string): string {
999
+ let result = text;
1000
+ for (const [pasteId, pasteContent] of this.pastes) {
1001
+ const markerRegex = new RegExp(`\\[paste #${pasteId}( (\\+\\d+ lines|\\d+ chars))?\\]`, "g");
1002
+ result = result.replace(markerRegex, () => pasteContent);
1003
+ }
1004
+ return result;
1005
+ }
1006
+
1007
+ /**
1008
+ * Get text with paste markers expanded to their actual content.
1009
+ * Use this when you need the full content (e.g., for external editor).
1010
+ */
1011
+ getExpandedText(): string {
1012
+ return this.expandPasteMarkers(this.state.lines.join("\n"));
1013
+ }
1014
+
1015
+ getLines(): string[] {
1016
+ return [...this.state.lines];
1017
+ }
1018
+
1019
+ getCursor(): { line: number; col: number } {
1020
+ return { line: this.state.cursorLine, col: this.state.cursorCol };
1021
+ }
1022
+
1023
+ setText(text: string): void {
1024
+ this.cancelAutocomplete();
1025
+ this.lastAction = null;
1026
+ this.exitHistoryBrowsing();
1027
+ const normalized = this.normalizeText(text);
1028
+ // Push undo snapshot if content differs (makes programmatic changes undoable)
1029
+ if (this.getText() !== normalized) {
1030
+ this.pushUndoSnapshot();
1031
+ }
1032
+ this.pastes.clear();
1033
+ this.pasteCounter = 0;
1034
+ this.setTextInternal(normalized);
1035
+ }
1036
+
1037
+ /**
1038
+ * Insert text at the current cursor position.
1039
+ * Used for programmatic insertion (e.g., clipboard image markers).
1040
+ * This is atomic for undo - single undo restores entire pre-insert state.
1041
+ */
1042
+ insertTextAtCursor(text: string): void {
1043
+ if (!text) return;
1044
+ this.cancelAutocomplete();
1045
+ this.pushUndoSnapshot();
1046
+ this.lastAction = null;
1047
+ this.exitHistoryBrowsing();
1048
+ this.insertTextAtCursorInternal(text);
1049
+ }
1050
+
1051
+ /**
1052
+ * Normalize text for editor storage:
1053
+ * - Normalize line endings (\r\n and \r -> \n)
1054
+ * - Expand tabs to 4 spaces
1055
+ */
1056
+ private normalizeText(text: string): string {
1057
+ return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n").replace(/\t/g, " ");
1058
+ }
1059
+
1060
+ /**
1061
+ * Internal text insertion at cursor. Handles single and multi-line text.
1062
+ * Does not push undo snapshots or trigger autocomplete - caller is responsible.
1063
+ * Normalizes line endings and calls onChange once at the end.
1064
+ */
1065
+ private insertTextAtCursorInternal(text: string): void {
1066
+ if (!text) return;
1067
+
1068
+ // Normalize line endings and tabs
1069
+ const normalized = this.normalizeText(text);
1070
+ const insertedLines = normalized.split("\n");
1071
+
1072
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1073
+ const beforeCursor = currentLine.slice(0, this.state.cursorCol);
1074
+ const afterCursor = currentLine.slice(this.state.cursorCol);
1075
+
1076
+ if (insertedLines.length === 1) {
1077
+ // Single line - insert at cursor position
1078
+ this.state.lines[this.state.cursorLine] = beforeCursor + normalized + afterCursor;
1079
+ this.setCursorCol(this.state.cursorCol + normalized.length);
1080
+ } else {
1081
+ // Multi-line insertion
1082
+ this.state.lines = [
1083
+ // All lines before current line
1084
+ ...this.state.lines.slice(0, this.state.cursorLine),
1085
+
1086
+ // The first inserted line merged with text before cursor
1087
+ beforeCursor + insertedLines[0],
1088
+
1089
+ // All middle inserted lines
1090
+ ...insertedLines.slice(1, -1),
1091
+
1092
+ // The last inserted line with text after cursor
1093
+ insertedLines[insertedLines.length - 1] + afterCursor,
1094
+
1095
+ // All lines after current line
1096
+ ...this.state.lines.slice(this.state.cursorLine + 1),
1097
+ ];
1098
+
1099
+ this.state.cursorLine += insertedLines.length - 1;
1100
+ this.setCursorCol((insertedLines[insertedLines.length - 1] || "").length);
1101
+ }
1102
+
1103
+ if (this.onChange) {
1104
+ this.onChange(this.getText());
1105
+ }
1106
+ }
1107
+
1108
+ // All the editor methods from before...
1109
+ private insertCharacter(char: string, skipUndoCoalescing?: boolean): void {
1110
+ this.exitHistoryBrowsing();
1111
+
1112
+ // Undo coalescing (fish-style):
1113
+ // - Consecutive word chars coalesce into one undo unit
1114
+ // - Space captures state before itself (so undo removes space+following word together)
1115
+ // - Each space is separately undoable
1116
+ // Skip coalescing when called from atomic operations (e.g., handlePaste)
1117
+ if (!skipUndoCoalescing) {
1118
+ if (isWhitespaceChar(char) || this.lastAction !== "type-word") {
1119
+ this.pushUndoSnapshot();
1120
+ }
1121
+ this.lastAction = "type-word";
1122
+ }
1123
+
1124
+ const line = this.state.lines[this.state.cursorLine] || "";
1125
+
1126
+ const before = line.slice(0, this.state.cursorCol);
1127
+ const after = line.slice(this.state.cursorCol);
1128
+
1129
+ this.state.lines[this.state.cursorLine] = before + char + after;
1130
+ this.setCursorCol(this.state.cursorCol + char.length);
1131
+
1132
+ if (this.onChange) {
1133
+ this.onChange(this.getText());
1134
+ }
1135
+
1136
+ // Check if we should trigger or update autocomplete
1137
+ if (!this.autocompleteState) {
1138
+ // Auto-trigger for "/" at the start of a line (slash commands)
1139
+ if (char === "/" && this.isAtStartOfMessage()) {
1140
+ this.tryTriggerAutocomplete();
1141
+ }
1142
+ // Auto-trigger for symbol-based completion like @, #, or provider triggers at token boundaries
1143
+ else if (this.autocompleteTriggerCharacters.includes(char)) {
1144
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1145
+ const textBeforeCursor = currentLine.slice(0, this.state.cursorCol);
1146
+ const charBeforeSymbol = textBeforeCursor[textBeforeCursor.length - 2];
1147
+ if (textBeforeCursor.length === 1 || charBeforeSymbol === " " || charBeforeSymbol === "\t") {
1148
+ this.tryTriggerAutocomplete();
1149
+ }
1150
+ }
1151
+ // Also auto-trigger when typing letters in a slash command or symbol completion context
1152
+ else if (/[a-zA-Z0-9.\-_]/.test(char)) {
1153
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1154
+ const textBeforeCursor = currentLine.slice(0, this.state.cursorCol);
1155
+ // Check if we're in a slash command (with or without space for arguments)
1156
+ if (this.isInSlashCommandContext(textBeforeCursor)) {
1157
+ this.tryTriggerAutocomplete();
1158
+ }
1159
+ // Check if we're in a symbol-based completion context like @, #, or provider triggers
1160
+ else if (this.autocompleteTriggerPattern.test(textBeforeCursor)) {
1161
+ this.tryTriggerAutocomplete();
1162
+ }
1163
+ }
1164
+ } else {
1165
+ this.updateAutocomplete();
1166
+ }
1167
+ }
1168
+
1169
+ private handlePaste(pastedText: string): void {
1170
+ this.cancelAutocomplete();
1171
+ this.exitHistoryBrowsing();
1172
+ this.lastAction = null;
1173
+
1174
+ this.pushUndoSnapshot();
1175
+
1176
+ // Some terminals (e.g. tmux popups with extended-keys-format=csi-u) re-encode
1177
+ // control bytes inside bracketed paste as CSI-u Ctrl+<letter> sequences
1178
+ // (ESC [ <codepoint> ; 5 u). Decode those back to their literal byte so the
1179
+ // per-char filter below preserves newlines instead of stripping ESC and
1180
+ // leaking the printable tail (e.g. "[106;5u") into the editor.
1181
+ const decodedText = pastedText.replace(/\x1b\[(\d+);5u/g, (match, code) => {
1182
+ const cp = Number(code);
1183
+ if (cp >= 97 && cp <= 122) return String.fromCharCode(cp - 96);
1184
+ if (cp >= 65 && cp <= 90) return String.fromCharCode(cp - 64);
1185
+ return match;
1186
+ });
1187
+
1188
+ // Clean the pasted text: normalize line endings, expand tabs
1189
+ const cleanText = this.normalizeText(decodedText);
1190
+
1191
+ // Filter out non-printable characters except newlines
1192
+ let filteredText = cleanText
1193
+ .split("")
1194
+ .filter((char) => char === "\n" || char.charCodeAt(0) >= 32)
1195
+ .join("");
1196
+
1197
+ // If pasting a file path (starts with /, ~, or .) and the character before
1198
+ // the cursor is a word character, prepend a space for better readability
1199
+ if (/^[/~.]/.test(filteredText)) {
1200
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1201
+ const charBeforeCursor = this.state.cursorCol > 0 ? currentLine[this.state.cursorCol - 1] : "";
1202
+ if (charBeforeCursor && /\w/.test(charBeforeCursor)) {
1203
+ filteredText = ` ${filteredText}`;
1204
+ }
1205
+ }
1206
+
1207
+ // Split into lines to check for large paste
1208
+ const pastedLines = filteredText.split("\n");
1209
+
1210
+ // Check if this is a large paste (> 10 lines or > 1000 characters)
1211
+ const totalChars = filteredText.length;
1212
+ if (pastedLines.length > 10 || totalChars > 1000) {
1213
+ // Store the paste and insert a marker
1214
+ this.pasteCounter++;
1215
+ const pasteId = this.pasteCounter;
1216
+ this.pastes.set(pasteId, filteredText);
1217
+
1218
+ // Insert marker like "[paste #1 +123 lines]" or "[paste #1 1234 chars]"
1219
+ const marker =
1220
+ pastedLines.length > 10
1221
+ ? `[paste #${pasteId} +${pastedLines.length} lines]`
1222
+ : `[paste #${pasteId} ${totalChars} chars]`;
1223
+ this.insertTextAtCursorInternal(marker);
1224
+ return;
1225
+ }
1226
+
1227
+ if (pastedLines.length === 1) {
1228
+ // Single line - insert atomically (do not trigger autocomplete during paste)
1229
+ this.insertTextAtCursorInternal(filteredText);
1230
+ return;
1231
+ }
1232
+
1233
+ // Multi-line paste - use direct state manipulation
1234
+ this.insertTextAtCursorInternal(filteredText);
1235
+ }
1236
+
1237
+ private addNewLine(): void {
1238
+ this.cancelAutocomplete();
1239
+ this.exitHistoryBrowsing();
1240
+ this.lastAction = null;
1241
+
1242
+ this.pushUndoSnapshot();
1243
+
1244
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1245
+
1246
+ const before = currentLine.slice(0, this.state.cursorCol);
1247
+ const after = currentLine.slice(this.state.cursorCol);
1248
+
1249
+ // Split current line
1250
+ this.state.lines[this.state.cursorLine] = before;
1251
+ this.state.lines.splice(this.state.cursorLine + 1, 0, after);
1252
+
1253
+ // Move cursor to start of new line
1254
+ this.state.cursorLine++;
1255
+ this.setCursorCol(0);
1256
+
1257
+ if (this.onChange) {
1258
+ this.onChange(this.getText());
1259
+ }
1260
+ }
1261
+
1262
+ private shouldSubmitOnBackslashEnter(data: string, kb: ReturnType<typeof getKeybindings>): boolean {
1263
+ if (this.disableSubmit) return false;
1264
+ if (!matchesKey(data, "enter")) return false;
1265
+ const submitKeys = kb.getKeys("tui.input.submit");
1266
+ const hasShiftEnter = submitKeys.includes("shift+enter") || submitKeys.includes("shift+return");
1267
+ if (!hasShiftEnter) return false;
1268
+
1269
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1270
+ return this.state.cursorCol > 0 && currentLine[this.state.cursorCol - 1] === "\\";
1271
+ }
1272
+
1273
+ private submitValue(): void {
1274
+ this.cancelAutocomplete();
1275
+ const result = this.expandPasteMarkers(this.state.lines.join("\n")).trim();
1276
+
1277
+ this.state = { lines: [""], cursorLine: 0, cursorCol: 0 };
1278
+ this.pastes.clear();
1279
+ this.pasteCounter = 0;
1280
+ this.exitHistoryBrowsing();
1281
+ this.scrollOffset = 0;
1282
+ this.undoStack.clear();
1283
+ this.lastAction = null;
1284
+
1285
+ if (this.onChange) this.onChange("");
1286
+ if (this.onSubmit) this.onSubmit(result);
1287
+ }
1288
+
1289
+ private handleBackspace(): void {
1290
+ this.exitHistoryBrowsing();
1291
+ this.lastAction = null;
1292
+
1293
+ if (this.state.cursorCol > 0) {
1294
+ this.pushUndoSnapshot();
1295
+
1296
+ // Delete grapheme before cursor (handles emojis, combining characters, etc.)
1297
+ let line = this.state.lines[this.state.cursorLine] || "";
1298
+ const beforeCursor = line.slice(0, this.state.cursorCol);
1299
+
1300
+ // Find the last grapheme in the text before cursor
1301
+ const graphemes = [...this.segment(beforeCursor, "grapheme")];
1302
+ const lastGrapheme = graphemes[graphemes.length - 1];
1303
+ const graphemeLength = lastGrapheme ? lastGrapheme.segment.length : 1;
1304
+ const isPastedSegmented = PASTE_MARKER_SINGLE.exec(lastGrapheme.segment);
1305
+
1306
+ if (isPastedSegmented) {
1307
+ // This contains the id part e.g 4 from [paste #4 +123 lines]
1308
+ const targetId = Number(isPastedSegmented[1]);
1309
+ this.pastes.delete(targetId);
1310
+ this.pasteCounter--;
1311
+
1312
+ // Shift registry entries down in ascending id order, independent
1313
+ // of marker order in the text ([paste #3] becomes [paste #2] when
1314
+ // [paste #1] is removed).
1315
+ const higherIds = [...this.pastes.keys()].filter((id) => id > targetId).sort((a, b) => a - b);
1316
+ for (const id of higherIds) {
1317
+ this.pastes.set(id - 1, this.pastes.get(id)!);
1318
+ this.pastes.delete(id);
1319
+ }
1320
+
1321
+ // Renumber markers with ids greater than the removed one.
1322
+ this.state.lines = this.state.lines.map((line) =>
1323
+ line.replace(PASTE_MARKER_REGEX, (fullMatch, idGroup, suffixGroup) => {
1324
+ const x = Number(idGroup);
1325
+ if (x <= targetId) return fullMatch;
1326
+ return `[paste #${x - 1}${suffixGroup}]`;
1327
+ }),
1328
+ );
1329
+ }
1330
+
1331
+ line = this.state.lines[this.state.cursorLine] || "";
1332
+
1333
+ const before = line.slice(0, this.state.cursorCol - graphemeLength);
1334
+ const after = line.slice(this.state.cursorCol);
1335
+
1336
+ this.state.lines[this.state.cursorLine] = before + after;
1337
+ this.setCursorCol(this.state.cursorCol - graphemeLength);
1338
+ } else if (this.state.cursorLine > 0) {
1339
+ this.pushUndoSnapshot();
1340
+
1341
+ // Merge with previous line
1342
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1343
+ const previousLine = this.state.lines[this.state.cursorLine - 1] || "";
1344
+
1345
+ this.state.lines[this.state.cursorLine - 1] = previousLine + currentLine;
1346
+ this.state.lines.splice(this.state.cursorLine, 1);
1347
+
1348
+ this.state.cursorLine--;
1349
+ this.setCursorCol(previousLine.length);
1350
+ }
1351
+
1352
+ if (this.onChange) {
1353
+ this.onChange(this.getText());
1354
+ }
1355
+
1356
+ // Update or re-trigger autocomplete after backspace
1357
+ if (this.autocompleteState) {
1358
+ this.updateAutocomplete();
1359
+ } else {
1360
+ // If autocomplete was cancelled (no matches), re-trigger if we're in a completable context
1361
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1362
+ const textBeforeCursor = currentLine.slice(0, this.state.cursorCol);
1363
+ // Slash command context
1364
+ if (this.isInSlashCommandContext(textBeforeCursor)) {
1365
+ this.tryTriggerAutocomplete();
1366
+ }
1367
+ // Symbol-based completion context like @, #, or provider triggers
1368
+ else if (this.autocompleteTriggerPattern.test(textBeforeCursor)) {
1369
+ this.tryTriggerAutocomplete();
1370
+ }
1371
+ }
1372
+ }
1373
+
1374
+ /**
1375
+ * Set cursor column and clear preferredVisualCol.
1376
+ * Use this for all non-vertical cursor movements to reset sticky column behavior.
1377
+ */
1378
+ private setCursorCol(col: number): void {
1379
+ this.state.cursorCol = col;
1380
+ this.preferredVisualCol = null;
1381
+ this.snappedFromCursorCol = null;
1382
+ }
1383
+
1384
+ /**
1385
+ * Move cursor to a target visual line, applying sticky column logic.
1386
+ * Shared by moveCursor() and pageScroll().
1387
+ */
1388
+ private moveToVisualLine(
1389
+ visualLines: Array<{ logicalLine: number; startCol: number; length: number }>,
1390
+ currentVisualLine: number,
1391
+ targetVisualLine: number,
1392
+ ): void {
1393
+ const currentVL = visualLines[currentVisualLine];
1394
+ const targetVL = visualLines[targetVisualLine];
1395
+ if (!(currentVL && targetVL)) return;
1396
+
1397
+ // When the cursor was snapped to a segment start, resolve the pre-snap
1398
+ // position against the VL it belongs to. This gives the correct visual
1399
+ // column even after a resize reshuffles VLs.
1400
+ let currentVisualCol: number;
1401
+ if (this.snappedFromCursorCol !== null) {
1402
+ const vlIndex = this.findVisualLineAt(visualLines, currentVL.logicalLine, this.snappedFromCursorCol);
1403
+ currentVisualCol = this.snappedFromCursorCol - visualLines[vlIndex].startCol;
1404
+ } else {
1405
+ currentVisualCol = this.state.cursorCol - currentVL.startCol;
1406
+ }
1407
+
1408
+ // For non-last segments, clamp to length-1 to stay within the segment
1409
+ const isLastSourceSegment =
1410
+ currentVisualLine === visualLines.length - 1 ||
1411
+ visualLines[currentVisualLine + 1]?.logicalLine !== currentVL.logicalLine;
1412
+ const sourceMaxVisualCol = isLastSourceSegment ? currentVL.length : Math.max(0, currentVL.length - 1);
1413
+
1414
+ const isLastTargetSegment =
1415
+ targetVisualLine === visualLines.length - 1 ||
1416
+ visualLines[targetVisualLine + 1]?.logicalLine !== targetVL.logicalLine;
1417
+ const targetMaxVisualCol = isLastTargetSegment ? targetVL.length : Math.max(0, targetVL.length - 1);
1418
+
1419
+ const moveToVisualCol = this.computeVerticalMoveColumn(currentVisualCol, sourceMaxVisualCol, targetMaxVisualCol);
1420
+
1421
+ // Set cursor position
1422
+ this.state.cursorLine = targetVL.logicalLine;
1423
+ const targetCol = targetVL.startCol + moveToVisualCol;
1424
+ const logicalLine = this.state.lines[targetVL.logicalLine] || "";
1425
+ this.state.cursorCol = Math.min(targetCol, logicalLine.length);
1426
+
1427
+ // Snap cursor to atomic segment boundary (e.g. paste markers)
1428
+ // so the cursor never lands in the middle of a multi-grapheme unit.
1429
+ // Single-grapheme segments don't need snapping.
1430
+ const segments = [...this.segment(logicalLine, "grapheme")];
1431
+ for (const seg of segments) {
1432
+ if (seg.index > this.state.cursorCol) break;
1433
+ if (seg.segment.length <= 1) continue;
1434
+ if (this.state.cursorCol < seg.index + seg.segment.length) {
1435
+ const isContinuation = seg.index < targetVL.startCol;
1436
+ const isMovingDown = targetVisualLine > currentVisualLine;
1437
+
1438
+ if (isContinuation && isMovingDown) {
1439
+ // The segment started on a previous visual line, and we
1440
+ // already visited it on the way down. Skip all remaining
1441
+ // continuation VLs and land on the first VL past it.
1442
+ const segEnd = seg.index + seg.segment.length;
1443
+ let next = targetVisualLine + 1;
1444
+ while (
1445
+ next < visualLines.length &&
1446
+ visualLines[next].logicalLine === targetVL.logicalLine &&
1447
+ visualLines[next].startCol < segEnd
1448
+ ) {
1449
+ next++;
1450
+ }
1451
+ if (next < visualLines.length) {
1452
+ this.moveToVisualLine(visualLines, currentVisualLine, next);
1453
+ return;
1454
+ }
1455
+ }
1456
+
1457
+ // Snap to the start of the segment so it gets highlighted.
1458
+ // Store the pre-snap position so the next vertical move can
1459
+ // resolve it to the correct visual column.
1460
+ this.snappedFromCursorCol = this.state.cursorCol;
1461
+ this.state.cursorCol = seg.index;
1462
+ return;
1463
+ }
1464
+ }
1465
+
1466
+ // No snap occurred – we moved out of the atomic segment.
1467
+ this.snappedFromCursorCol = null;
1468
+ }
1469
+
1470
+ /**
1471
+ * Compute the target visual column for vertical cursor movement.
1472
+ * Implements the sticky column decision table:
1473
+ *
1474
+ * | P | S | T | U | Scenario | Set Preferred | Move To |
1475
+ * |---|---|---|---| ---------------------------------------------------- |---------------|-------------|
1476
+ * | 0 | * | 0 | - | Start nav, target fits | null | current |
1477
+ * | 0 | * | 1 | - | Start nav, target shorter | current | target end |
1478
+ * | 1 | 0 | 0 | 0 | Clamped, target fits preferred | null | preferred |
1479
+ * | 1 | 0 | 0 | 1 | Clamped, target longer but still can't fit preferred | keep | target end |
1480
+ * | 1 | 0 | 1 | - | Clamped, target even shorter | keep | target end |
1481
+ * | 1 | 1 | 0 | - | Rewrapped, target fits current | null | current |
1482
+ * | 1 | 1 | 1 | - | Rewrapped, target shorter than current | current | target end |
1483
+ *
1484
+ * Where:
1485
+ * - P = preferred col is set
1486
+ * - S = cursor in middle of source line (not clamped to end)
1487
+ * - T = target line shorter than current visual col
1488
+ * - U = target line shorter than preferred col
1489
+ */
1490
+ private computeVerticalMoveColumn(
1491
+ currentVisualCol: number,
1492
+ sourceMaxVisualCol: number,
1493
+ targetMaxVisualCol: number,
1494
+ ): number {
1495
+ const hasPreferred = this.preferredVisualCol !== null; // P
1496
+ const cursorInMiddle = currentVisualCol < sourceMaxVisualCol; // S
1497
+ const targetTooShort = targetMaxVisualCol < currentVisualCol; // T
1498
+
1499
+ if (!hasPreferred || cursorInMiddle) {
1500
+ if (targetTooShort) {
1501
+ // Cases 2 and 7
1502
+ this.preferredVisualCol = currentVisualCol;
1503
+ return targetMaxVisualCol;
1504
+ }
1505
+
1506
+ // Cases 1 and 6
1507
+ this.preferredVisualCol = null;
1508
+ return currentVisualCol;
1509
+ }
1510
+
1511
+ const targetCantFitPreferred = targetMaxVisualCol < this.preferredVisualCol!; // U
1512
+ if (targetTooShort || targetCantFitPreferred) {
1513
+ // Cases 4 and 5
1514
+ return targetMaxVisualCol;
1515
+ }
1516
+
1517
+ // Case 3
1518
+ const result = this.preferredVisualCol!;
1519
+ this.preferredVisualCol = null;
1520
+ return result;
1521
+ }
1522
+
1523
+ private moveToLineStart(): void {
1524
+ this.lastAction = null;
1525
+ this.setCursorCol(0);
1526
+ }
1527
+
1528
+ private moveToLineEnd(): void {
1529
+ this.lastAction = null;
1530
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1531
+ this.setCursorCol(currentLine.length);
1532
+ }
1533
+
1534
+ private deleteToStartOfLine(): void {
1535
+ this.exitHistoryBrowsing();
1536
+
1537
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1538
+
1539
+ if (this.state.cursorCol > 0) {
1540
+ this.pushUndoSnapshot();
1541
+
1542
+ // Calculate text to be deleted and save to kill ring (backward deletion = prepend)
1543
+ const deletedText = currentLine.slice(0, this.state.cursorCol);
1544
+ this.killRing.push(deletedText, { prepend: true, accumulate: this.lastAction === "kill" });
1545
+ this.lastAction = "kill";
1546
+
1547
+ // Delete from start of line up to cursor
1548
+ this.state.lines[this.state.cursorLine] = currentLine.slice(this.state.cursorCol);
1549
+ this.setCursorCol(0);
1550
+ } else if (this.state.cursorLine > 0) {
1551
+ this.pushUndoSnapshot();
1552
+
1553
+ // At start of line - merge with previous line, treating newline as deleted text
1554
+ this.killRing.push("\n", { prepend: true, accumulate: this.lastAction === "kill" });
1555
+ this.lastAction = "kill";
1556
+
1557
+ const previousLine = this.state.lines[this.state.cursorLine - 1] || "";
1558
+ this.state.lines[this.state.cursorLine - 1] = previousLine + currentLine;
1559
+ this.state.lines.splice(this.state.cursorLine, 1);
1560
+ this.state.cursorLine--;
1561
+ this.setCursorCol(previousLine.length);
1562
+ }
1563
+
1564
+ if (this.onChange) {
1565
+ this.onChange(this.getText());
1566
+ }
1567
+ }
1568
+
1569
+ private deleteToEndOfLine(): void {
1570
+ this.exitHistoryBrowsing();
1571
+
1572
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1573
+
1574
+ if (this.state.cursorCol < currentLine.length) {
1575
+ this.pushUndoSnapshot();
1576
+
1577
+ // Calculate text to be deleted and save to kill ring (forward deletion = append)
1578
+ const deletedText = currentLine.slice(this.state.cursorCol);
1579
+ this.killRing.push(deletedText, { prepend: false, accumulate: this.lastAction === "kill" });
1580
+ this.lastAction = "kill";
1581
+
1582
+ // Delete from cursor to end of line
1583
+ this.state.lines[this.state.cursorLine] = currentLine.slice(0, this.state.cursorCol);
1584
+ } else if (this.state.cursorLine < this.state.lines.length - 1) {
1585
+ this.pushUndoSnapshot();
1586
+
1587
+ // At end of line - merge with next line, treating newline as deleted text
1588
+ this.killRing.push("\n", { prepend: false, accumulate: this.lastAction === "kill" });
1589
+ this.lastAction = "kill";
1590
+
1591
+ const nextLine = this.state.lines[this.state.cursorLine + 1] || "";
1592
+ this.state.lines[this.state.cursorLine] = currentLine + nextLine;
1593
+ this.state.lines.splice(this.state.cursorLine + 1, 1);
1594
+ }
1595
+
1596
+ if (this.onChange) {
1597
+ this.onChange(this.getText());
1598
+ }
1599
+ }
1600
+
1601
+ private deleteWordBackwards(): void {
1602
+ this.exitHistoryBrowsing();
1603
+
1604
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1605
+
1606
+ // If at start of line, behave like backspace at column 0 (merge with previous line)
1607
+ if (this.state.cursorCol === 0) {
1608
+ if (this.state.cursorLine > 0) {
1609
+ this.pushUndoSnapshot();
1610
+
1611
+ // Treat newline as deleted text (backward deletion = prepend)
1612
+ this.killRing.push("\n", { prepend: true, accumulate: this.lastAction === "kill" });
1613
+ this.lastAction = "kill";
1614
+
1615
+ const previousLine = this.state.lines[this.state.cursorLine - 1] || "";
1616
+ this.state.lines[this.state.cursorLine - 1] = previousLine + currentLine;
1617
+ this.state.lines.splice(this.state.cursorLine, 1);
1618
+ this.state.cursorLine--;
1619
+ this.setCursorCol(previousLine.length);
1620
+ }
1621
+ } else {
1622
+ this.pushUndoSnapshot();
1623
+
1624
+ // Save lastAction before cursor movement (moveWordBackwards resets it)
1625
+ const wasKill = this.lastAction === "kill";
1626
+
1627
+ const oldCursorCol = this.state.cursorCol;
1628
+ this.moveWordBackwards();
1629
+ const deleteFrom = this.state.cursorCol;
1630
+ this.setCursorCol(oldCursorCol);
1631
+
1632
+ const deletedText = currentLine.slice(deleteFrom, this.state.cursorCol);
1633
+ this.killRing.push(deletedText, { prepend: true, accumulate: wasKill });
1634
+ this.lastAction = "kill";
1635
+
1636
+ this.state.lines[this.state.cursorLine] =
1637
+ currentLine.slice(0, deleteFrom) + currentLine.slice(this.state.cursorCol);
1638
+ this.setCursorCol(deleteFrom);
1639
+ }
1640
+
1641
+ if (this.onChange) {
1642
+ this.onChange(this.getText());
1643
+ }
1644
+ }
1645
+
1646
+ private deleteWordForward(): void {
1647
+ this.exitHistoryBrowsing();
1648
+
1649
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1650
+
1651
+ // If at end of line, merge with next line (delete the newline)
1652
+ if (this.state.cursorCol >= currentLine.length) {
1653
+ if (this.state.cursorLine < this.state.lines.length - 1) {
1654
+ this.pushUndoSnapshot();
1655
+
1656
+ // Treat newline as deleted text (forward deletion = append)
1657
+ this.killRing.push("\n", { prepend: false, accumulate: this.lastAction === "kill" });
1658
+ this.lastAction = "kill";
1659
+
1660
+ const nextLine = this.state.lines[this.state.cursorLine + 1] || "";
1661
+ this.state.lines[this.state.cursorLine] = currentLine + nextLine;
1662
+ this.state.lines.splice(this.state.cursorLine + 1, 1);
1663
+ }
1664
+ } else {
1665
+ this.pushUndoSnapshot();
1666
+
1667
+ // Save lastAction before cursor movement (moveWordForwards resets it)
1668
+ const wasKill = this.lastAction === "kill";
1669
+
1670
+ const oldCursorCol = this.state.cursorCol;
1671
+ this.moveWordForwards();
1672
+ const deleteTo = this.state.cursorCol;
1673
+ this.setCursorCol(oldCursorCol);
1674
+
1675
+ const deletedText = currentLine.slice(this.state.cursorCol, deleteTo);
1676
+ this.killRing.push(deletedText, { prepend: false, accumulate: wasKill });
1677
+ this.lastAction = "kill";
1678
+
1679
+ this.state.lines[this.state.cursorLine] =
1680
+ currentLine.slice(0, this.state.cursorCol) + currentLine.slice(deleteTo);
1681
+ }
1682
+
1683
+ if (this.onChange) {
1684
+ this.onChange(this.getText());
1685
+ }
1686
+ }
1687
+
1688
+ private handleForwardDelete(): void {
1689
+ this.exitHistoryBrowsing();
1690
+ this.lastAction = null;
1691
+
1692
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1693
+
1694
+ if (this.state.cursorCol < currentLine.length) {
1695
+ this.pushUndoSnapshot();
1696
+
1697
+ // Delete grapheme at cursor position (handles emojis, combining characters, etc.)
1698
+ const afterCursor = currentLine.slice(this.state.cursorCol);
1699
+
1700
+ // Find the first grapheme at cursor
1701
+ const graphemes = [...this.segment(afterCursor, "grapheme")];
1702
+ const firstGrapheme = graphemes[0];
1703
+ const graphemeLength = firstGrapheme ? firstGrapheme.segment.length : 1;
1704
+
1705
+ const before = currentLine.slice(0, this.state.cursorCol);
1706
+ const after = currentLine.slice(this.state.cursorCol + graphemeLength);
1707
+ this.state.lines[this.state.cursorLine] = before + after;
1708
+ } else if (this.state.cursorLine < this.state.lines.length - 1) {
1709
+ this.pushUndoSnapshot();
1710
+
1711
+ // At end of line - merge with next line
1712
+ const nextLine = this.state.lines[this.state.cursorLine + 1] || "";
1713
+ this.state.lines[this.state.cursorLine] = currentLine + nextLine;
1714
+ this.state.lines.splice(this.state.cursorLine + 1, 1);
1715
+ }
1716
+
1717
+ if (this.onChange) {
1718
+ this.onChange(this.getText());
1719
+ }
1720
+
1721
+ // Update or re-trigger autocomplete after forward delete
1722
+ if (this.autocompleteState) {
1723
+ this.updateAutocomplete();
1724
+ } else {
1725
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1726
+ const textBeforeCursor = currentLine.slice(0, this.state.cursorCol);
1727
+ // Slash command context
1728
+ if (this.isInSlashCommandContext(textBeforeCursor)) {
1729
+ this.tryTriggerAutocomplete();
1730
+ }
1731
+ // Symbol-based completion context like @, #, or provider triggers
1732
+ else if (this.autocompleteTriggerPattern.test(textBeforeCursor)) {
1733
+ this.tryTriggerAutocomplete();
1734
+ }
1735
+ }
1736
+ }
1737
+
1738
+ /**
1739
+ * Build a mapping from visual lines to logical positions.
1740
+ * Returns an array where each element represents a visual line with:
1741
+ * - logicalLine: index into this.state.lines
1742
+ * - startCol: starting column in the logical line
1743
+ * - length: length of this visual line segment
1744
+ */
1745
+ private buildVisualLineMap(width: number): Array<{ logicalLine: number; startCol: number; length: number }> {
1746
+ const visualLines: Array<{ logicalLine: number; startCol: number; length: number }> = [];
1747
+
1748
+ for (let i = 0; i < this.state.lines.length; i++) {
1749
+ const line = this.state.lines[i] || "";
1750
+ const lineVisWidth = visibleWidth(line);
1751
+ if (line.length === 0) {
1752
+ // Empty line still takes one visual line
1753
+ visualLines.push({ logicalLine: i, startCol: 0, length: 0 });
1754
+ } else if (lineVisWidth <= width) {
1755
+ visualLines.push({ logicalLine: i, startCol: 0, length: line.length });
1756
+ } else {
1757
+ // Line needs wrapping - use word-aware wrapping
1758
+ const chunks = wordWrapLine(line, width, [...this.segment(line, "grapheme")]);
1759
+ for (const chunk of chunks) {
1760
+ visualLines.push({
1761
+ logicalLine: i,
1762
+ startCol: chunk.startIndex,
1763
+ length: chunk.endIndex - chunk.startIndex,
1764
+ });
1765
+ }
1766
+ }
1767
+ }
1768
+
1769
+ return visualLines;
1770
+ }
1771
+
1772
+ /**
1773
+ * Find the visual line index that contains the given logical position.
1774
+ */
1775
+ private findVisualLineAt(
1776
+ visualLines: Array<{ logicalLine: number; startCol: number; length: number }>,
1777
+ line: number,
1778
+ col: number,
1779
+ ): number {
1780
+ for (let i = 0; i < visualLines.length; i++) {
1781
+ const vl = visualLines[i];
1782
+ if (!vl || vl.logicalLine !== line) continue;
1783
+ const offset = col - vl.startCol;
1784
+ // Cursor is in this segment if it's within range. For the last
1785
+ // segment of a logical line, cursor can be at length (end position)
1786
+ const isLastSegmentOfLine = i === visualLines.length - 1 || visualLines[i + 1]?.logicalLine !== vl.logicalLine;
1787
+ if (offset >= 0 && (offset < vl.length || (isLastSegmentOfLine && offset === vl.length))) {
1788
+ return i;
1789
+ }
1790
+ }
1791
+ return visualLines.length - 1;
1792
+ }
1793
+
1794
+ /**
1795
+ * Find the visual line index for the current cursor position.
1796
+ */
1797
+ private findCurrentVisualLine(
1798
+ visualLines: Array<{ logicalLine: number; startCol: number; length: number }>,
1799
+ ): number {
1800
+ return this.findVisualLineAt(visualLines, this.state.cursorLine, this.state.cursorCol);
1801
+ }
1802
+
1803
+ private moveCursor(deltaLine: number, deltaCol: number): void {
1804
+ this.lastAction = null;
1805
+ const visualLines = this.buildVisualLineMap(this.lastWidth);
1806
+ const currentVisualLine = this.findCurrentVisualLine(visualLines);
1807
+
1808
+ if (deltaLine !== 0) {
1809
+ const targetVisualLine = currentVisualLine + deltaLine;
1810
+
1811
+ if (targetVisualLine >= 0 && targetVisualLine < visualLines.length) {
1812
+ this.moveToVisualLine(visualLines, currentVisualLine, targetVisualLine);
1813
+ }
1814
+ }
1815
+
1816
+ if (deltaCol !== 0) {
1817
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1818
+
1819
+ if (deltaCol > 0) {
1820
+ // Moving right - move by one grapheme (handles emojis, combining characters, etc.)
1821
+ if (this.state.cursorCol < currentLine.length) {
1822
+ const afterCursor = currentLine.slice(this.state.cursorCol);
1823
+ const graphemes = [...this.segment(afterCursor, "grapheme")];
1824
+ const firstGrapheme = graphemes[0];
1825
+ this.setCursorCol(this.state.cursorCol + (firstGrapheme ? firstGrapheme.segment.length : 1));
1826
+ } else if (this.state.cursorLine < this.state.lines.length - 1) {
1827
+ // Wrap to start of next logical line
1828
+ this.state.cursorLine++;
1829
+ this.setCursorCol(0);
1830
+ } else {
1831
+ // At end of last line - can't move, but set preferredVisualCol for up/down navigation
1832
+ const currentVL = visualLines[currentVisualLine];
1833
+ if (currentVL) {
1834
+ this.preferredVisualCol = this.state.cursorCol - currentVL.startCol;
1835
+ }
1836
+ }
1837
+ } else {
1838
+ // Moving left - move by one grapheme (handles emojis, combining characters, etc.)
1839
+ if (this.state.cursorCol > 0) {
1840
+ const beforeCursor = currentLine.slice(0, this.state.cursorCol);
1841
+ const graphemes = [...this.segment(beforeCursor, "grapheme")];
1842
+ const lastGrapheme = graphemes[graphemes.length - 1];
1843
+ this.setCursorCol(this.state.cursorCol - (lastGrapheme ? lastGrapheme.segment.length : 1));
1844
+ } else if (this.state.cursorLine > 0) {
1845
+ // Wrap to end of previous logical line
1846
+ this.state.cursorLine--;
1847
+ const prevLine = this.state.lines[this.state.cursorLine] || "";
1848
+ this.setCursorCol(prevLine.length);
1849
+ }
1850
+ }
1851
+ }
1852
+
1853
+ // Keep an open autocomplete picker in sync with the new cursor
1854
+ // position: cursor movement changes the text before the cursor, so a
1855
+ // picker computed for the old position is stale. Re-query so it
1856
+ // refreshes — or closes when the new position yields no suggestions —
1857
+ // mirroring insertCharacter()/handleBackspace(). Without this, arrowing
1858
+ // left from `/cmd ` back into the command name leaves the argument
1859
+ // picker showing against a `/cmd` prefix (and a Tab there would
1860
+ // concatenate the stale suggestion onto the partial command name).
1861
+ if (this.autocompleteState) {
1862
+ this.updateAutocomplete();
1863
+ }
1864
+ }
1865
+
1866
+ /**
1867
+ * Scroll by a page (direction: -1 for up, 1 for down).
1868
+ * Moves cursor by the page size while keeping it in bounds.
1869
+ */
1870
+ private pageScroll(direction: -1 | 1): void {
1871
+ this.lastAction = null;
1872
+ const terminalRows = this.tui.terminal.rows;
1873
+ const pageSize = Math.max(5, Math.floor(terminalRows * 0.3));
1874
+
1875
+ const visualLines = this.buildVisualLineMap(this.lastWidth);
1876
+ const currentVisualLine = this.findCurrentVisualLine(visualLines);
1877
+ const targetVisualLine = Math.max(0, Math.min(visualLines.length - 1, currentVisualLine + direction * pageSize));
1878
+
1879
+ this.moveToVisualLine(visualLines, currentVisualLine, targetVisualLine);
1880
+ }
1881
+
1882
+ private moveWordBackwards(): void {
1883
+ this.lastAction = null;
1884
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1885
+
1886
+ // If at start of line, move to end of previous line
1887
+ if (this.state.cursorCol === 0) {
1888
+ if (this.state.cursorLine > 0) {
1889
+ this.state.cursorLine--;
1890
+ const prevLine = this.state.lines[this.state.cursorLine] || "";
1891
+ this.setCursorCol(prevLine.length);
1892
+ }
1893
+ return;
1894
+ }
1895
+
1896
+ this.setCursorCol(
1897
+ findWordBackward(currentLine, this.state.cursorCol, {
1898
+ segment: (text) => this.segment(text, "word"),
1899
+ isAtomicSegment: isPasteMarker,
1900
+ }),
1901
+ );
1902
+ }
1903
+
1904
+ /**
1905
+ * Yank (paste) the most recent kill ring entry at cursor position.
1906
+ */
1907
+ private yank(): void {
1908
+ if (this.killRing.length === 0) return;
1909
+
1910
+ this.pushUndoSnapshot();
1911
+
1912
+ const text = this.killRing.peek()!;
1913
+ this.insertYankedText(text);
1914
+
1915
+ this.lastAction = "yank";
1916
+ }
1917
+
1918
+ /**
1919
+ * Cycle through kill ring (only works immediately after yank or yank-pop).
1920
+ * Replaces the last yanked text with the previous entry in the ring.
1921
+ */
1922
+ private yankPop(): void {
1923
+ // Only works if we just yanked and have more than one entry
1924
+ if (this.lastAction !== "yank" || this.killRing.length <= 1) return;
1925
+
1926
+ this.pushUndoSnapshot();
1927
+
1928
+ // Delete the previously yanked text (still at end of ring before rotation)
1929
+ this.deleteYankedText();
1930
+
1931
+ // Rotate the ring: move end to front
1932
+ this.killRing.rotate();
1933
+
1934
+ // Insert the new most recent entry (now at end after rotation)
1935
+ const text = this.killRing.peek()!;
1936
+ this.insertYankedText(text);
1937
+
1938
+ this.lastAction = "yank";
1939
+ }
1940
+
1941
+ /**
1942
+ * Insert text at cursor position (used by yank operations).
1943
+ */
1944
+ private insertYankedText(text: string): void {
1945
+ this.exitHistoryBrowsing();
1946
+ const lines = text.split("\n");
1947
+
1948
+ if (lines.length === 1) {
1949
+ // Single line - insert at cursor
1950
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1951
+ const before = currentLine.slice(0, this.state.cursorCol);
1952
+ const after = currentLine.slice(this.state.cursorCol);
1953
+ this.state.lines[this.state.cursorLine] = before + text + after;
1954
+ this.setCursorCol(this.state.cursorCol + text.length);
1955
+ } else {
1956
+ // Multi-line insert
1957
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1958
+ const before = currentLine.slice(0, this.state.cursorCol);
1959
+ const after = currentLine.slice(this.state.cursorCol);
1960
+
1961
+ // First line merges with text before cursor
1962
+ this.state.lines[this.state.cursorLine] = before + (lines[0] || "");
1963
+
1964
+ // Insert middle lines
1965
+ for (let i = 1; i < lines.length - 1; i++) {
1966
+ this.state.lines.splice(this.state.cursorLine + i, 0, lines[i] || "");
1967
+ }
1968
+
1969
+ // Last line merges with text after cursor
1970
+ const lastLineIndex = this.state.cursorLine + lines.length - 1;
1971
+ this.state.lines.splice(lastLineIndex, 0, (lines[lines.length - 1] || "") + after);
1972
+
1973
+ // Update cursor position
1974
+ this.state.cursorLine = lastLineIndex;
1975
+ this.setCursorCol((lines[lines.length - 1] || "").length);
1976
+ }
1977
+
1978
+ if (this.onChange) {
1979
+ this.onChange(this.getText());
1980
+ }
1981
+ }
1982
+
1983
+ /**
1984
+ * Delete the previously yanked text (used by yank-pop).
1985
+ * The yanked text is derived from killRing[end] since it hasn't been rotated yet.
1986
+ */
1987
+ private deleteYankedText(): void {
1988
+ const yankedText = this.killRing.peek();
1989
+ if (!yankedText) return;
1990
+
1991
+ const yankLines = yankedText.split("\n");
1992
+
1993
+ if (yankLines.length === 1) {
1994
+ // Single line - delete backward from cursor
1995
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1996
+ const deleteLen = yankedText.length;
1997
+ const before = currentLine.slice(0, this.state.cursorCol - deleteLen);
1998
+ const after = currentLine.slice(this.state.cursorCol);
1999
+ this.state.lines[this.state.cursorLine] = before + after;
2000
+ this.setCursorCol(this.state.cursorCol - deleteLen);
2001
+ } else {
2002
+ // Multi-line delete - cursor is at end of last yanked line
2003
+ const startLine = this.state.cursorLine - (yankLines.length - 1);
2004
+ const startCol = (this.state.lines[startLine] || "").length - (yankLines[0] || "").length;
2005
+
2006
+ // Get text after cursor on current line
2007
+ const afterCursor = (this.state.lines[this.state.cursorLine] || "").slice(this.state.cursorCol);
2008
+
2009
+ // Get text before yank start position
2010
+ const beforeYank = (this.state.lines[startLine] || "").slice(0, startCol);
2011
+
2012
+ // Remove all lines from startLine to cursorLine and replace with merged line
2013
+ this.state.lines.splice(startLine, yankLines.length, beforeYank + afterCursor);
2014
+
2015
+ // Update cursor
2016
+ this.state.cursorLine = startLine;
2017
+ this.setCursorCol(startCol);
2018
+ }
2019
+
2020
+ if (this.onChange) {
2021
+ this.onChange(this.getText());
2022
+ }
2023
+ }
2024
+
2025
+ private pushUndoSnapshot(): void {
2026
+ this.undoStack.push({ state: this.state, pastes: this.pastes, pasteCounter: this.pasteCounter });
2027
+ }
2028
+
2029
+ private undo(): void {
2030
+ this.exitHistoryBrowsing();
2031
+ const snapshot = this.undoStack.pop();
2032
+ if (!snapshot) return;
2033
+ Object.assign(this.state, snapshot.state);
2034
+ this.pastes = snapshot.pastes;
2035
+ this.pasteCounter = snapshot.pasteCounter;
2036
+ this.lastAction = null;
2037
+ this.preferredVisualCol = null;
2038
+ if (this.onChange) {
2039
+ this.onChange(this.getText());
2040
+ }
2041
+ }
2042
+
2043
+ /**
2044
+ * Jump to the first occurrence of a character in the specified direction.
2045
+ * Multi-line search. Case-sensitive. Skips the current cursor position.
2046
+ */
2047
+ private jumpToChar(char: string, direction: "forward" | "backward"): void {
2048
+ this.lastAction = null;
2049
+ const isForward = direction === "forward";
2050
+ const lines = this.state.lines;
2051
+
2052
+ const end = isForward ? lines.length : -1;
2053
+ const step = isForward ? 1 : -1;
2054
+
2055
+ for (let lineIdx = this.state.cursorLine; lineIdx !== end; lineIdx += step) {
2056
+ const line = lines[lineIdx] || "";
2057
+ const isCurrentLine = lineIdx === this.state.cursorLine;
2058
+
2059
+ // Current line: start after/before cursor; other lines: search full line
2060
+ const searchFrom = isCurrentLine
2061
+ ? isForward
2062
+ ? this.state.cursorCol + 1
2063
+ : this.state.cursorCol - 1
2064
+ : undefined;
2065
+
2066
+ const idx = isForward ? line.indexOf(char, searchFrom) : line.lastIndexOf(char, searchFrom);
2067
+
2068
+ if (idx !== -1) {
2069
+ this.state.cursorLine = lineIdx;
2070
+ this.setCursorCol(idx);
2071
+ return;
2072
+ }
2073
+ }
2074
+ // No match found - cursor stays in place
2075
+ }
2076
+
2077
+ private moveWordForwards(): void {
2078
+ this.lastAction = null;
2079
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
2080
+
2081
+ // If at end of line, move to start of next line
2082
+ if (this.state.cursorCol >= currentLine.length) {
2083
+ if (this.state.cursorLine < this.state.lines.length - 1) {
2084
+ this.state.cursorLine++;
2085
+ this.setCursorCol(0);
2086
+ }
2087
+ return;
2088
+ }
2089
+
2090
+ this.setCursorCol(
2091
+ findWordForward(currentLine, this.state.cursorCol, {
2092
+ segment: (text) => this.segment(text, "word"),
2093
+ isAtomicSegment: isPasteMarker,
2094
+ }),
2095
+ );
2096
+ }
2097
+
2098
+ // Slash menu only allowed on the first line of the editor
2099
+ private isSlashMenuAllowed(): boolean {
2100
+ return this.state.cursorLine === 0;
2101
+ }
2102
+
2103
+ // Helper method to check if cursor is at start of message (for slash command detection)
2104
+ private isAtStartOfMessage(): boolean {
2105
+ if (!this.isSlashMenuAllowed()) return false;
2106
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
2107
+ const beforeCursor = currentLine.slice(0, this.state.cursorCol);
2108
+ return beforeCursor.trim() === "" || beforeCursor.trim() === "/";
2109
+ }
2110
+
2111
+ private isInSlashCommandContext(textBeforeCursor: string): boolean {
2112
+ return this.isSlashMenuAllowed() && textBeforeCursor.trimStart().startsWith("/");
2113
+ }
2114
+
2115
+ // Autocomplete methods
2116
+ /**
2117
+ * Find the best autocomplete item index for the given prefix.
2118
+ * Returns -1 if no match is found.
2119
+ *
2120
+ * Match priority:
2121
+ * 1. Exact match (prefix === item.value) -> always selected
2122
+ * 2. Prefix match -> first item whose value starts with prefix
2123
+ * 3. No match -> -1 (keep default highlight)
2124
+ *
2125
+ * Matching is case-sensitive and checks item.value only.
2126
+ */
2127
+ private getBestAutocompleteMatchIndex(items: Array<{ value: string; label: string }>, prefix: string): number {
2128
+ if (!prefix) return -1;
2129
+
2130
+ let firstPrefixIndex = -1;
2131
+
2132
+ for (let i = 0; i < items.length; i++) {
2133
+ const value = items[i]!.value;
2134
+ if (value === prefix) {
2135
+ return i; // Exact match always wins
2136
+ }
2137
+ if (firstPrefixIndex === -1 && value.startsWith(prefix)) {
2138
+ firstPrefixIndex = i;
2139
+ }
2140
+ }
2141
+
2142
+ return firstPrefixIndex;
2143
+ }
2144
+
2145
+ private createAutocompleteList(
2146
+ prefix: string,
2147
+ items: Array<{ value: string; label: string; description?: string }>,
2148
+ ): SelectList {
2149
+ const layout = prefix.startsWith("/") ? SLASH_COMMAND_SELECT_LIST_LAYOUT : undefined;
2150
+ return new SelectList(items, this.autocompleteMaxVisible, this.theme.selectList, layout);
2151
+ }
2152
+
2153
+ private tryTriggerAutocomplete(explicitTab: boolean = false): void {
2154
+ this.requestAutocomplete({ force: false, explicitTab });
2155
+ }
2156
+
2157
+ private handleTabCompletion(): void {
2158
+ if (!this.autocompleteProvider) return;
2159
+
2160
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
2161
+ const beforeCursor = currentLine.slice(0, this.state.cursorCol);
2162
+
2163
+ if (this.isInSlashCommandContext(beforeCursor) && !beforeCursor.trimStart().includes(" ")) {
2164
+ this.handleSlashCommandCompletion();
2165
+ } else {
2166
+ this.forceFileAutocomplete(true);
2167
+ }
2168
+ }
2169
+
2170
+ private handleSlashCommandCompletion(): void {
2171
+ this.requestAutocomplete({ force: false, explicitTab: true });
2172
+ }
2173
+
2174
+ private forceFileAutocomplete(explicitTab: boolean = false): void {
2175
+ this.requestAutocomplete({ force: true, explicitTab });
2176
+ }
2177
+
2178
+ private requestAutocomplete(options: { force: boolean; explicitTab: boolean }): void {
2179
+ if (!this.autocompleteProvider) return;
2180
+
2181
+ if (options.force) {
2182
+ const shouldTrigger =
2183
+ !this.autocompleteProvider.shouldTriggerFileCompletion ||
2184
+ this.autocompleteProvider.shouldTriggerFileCompletion(
2185
+ this.state.lines,
2186
+ this.state.cursorLine,
2187
+ this.state.cursorCol,
2188
+ );
2189
+ if (!shouldTrigger) {
2190
+ return;
2191
+ }
2192
+ }
2193
+
2194
+ this.cancelAutocompleteRequest();
2195
+ const startToken = ++this.autocompleteStartToken;
2196
+
2197
+ const debounceMs = this.getAutocompleteDebounceMs(options);
2198
+ if (debounceMs > 0) {
2199
+ this.autocompleteDebounceTimer = setTimeout(() => {
2200
+ this.autocompleteDebounceTimer = undefined;
2201
+ void this.startAutocompleteRequest(startToken, options);
2202
+ }, debounceMs);
2203
+ return;
2204
+ }
2205
+
2206
+ void this.startAutocompleteRequest(startToken, options);
2207
+ }
2208
+
2209
+ private async startAutocompleteRequest(
2210
+ startToken: number,
2211
+ options: { force: boolean; explicitTab: boolean },
2212
+ ): Promise<void> {
2213
+ const previousTask = this.autocompleteRequestTask;
2214
+ this.autocompleteRequestTask = (async () => {
2215
+ await previousTask;
2216
+ if (startToken !== this.autocompleteStartToken || !this.autocompleteProvider) {
2217
+ return;
2218
+ }
2219
+
2220
+ const controller = new AbortController();
2221
+ this.autocompleteAbort = controller;
2222
+ const requestId = ++this.autocompleteRequestId;
2223
+ const snapshotText = this.getText();
2224
+ const snapshotLine = this.state.cursorLine;
2225
+ const snapshotCol = this.state.cursorCol;
2226
+
2227
+ await this.runAutocompleteRequest(requestId, controller, snapshotText, snapshotLine, snapshotCol, options);
2228
+ })();
2229
+ await this.autocompleteRequestTask;
2230
+ }
2231
+
2232
+ private setAutocompleteTriggerCharacters(triggerCharacters: string[]): void {
2233
+ const next = [...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS];
2234
+ for (const character of triggerCharacters) {
2235
+ if (character.length !== 1 || character === "/" || isWhitespaceChar(character) || next.includes(character)) {
2236
+ continue;
2237
+ }
2238
+ next.push(character);
2239
+ }
2240
+ this.autocompleteTriggerCharacters = next;
2241
+ this.autocompleteTriggerPattern = buildTriggerPattern(next);
2242
+ this.autocompleteDebouncePattern = buildDebouncePattern(next);
2243
+ }
2244
+
2245
+ private getAutocompleteDebounceMs(options: { force: boolean; explicitTab: boolean }): number {
2246
+ if (options.explicitTab || options.force) {
2247
+ return 0;
2248
+ }
2249
+
2250
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
2251
+ const textBeforeCursor = currentLine.slice(0, this.state.cursorCol);
2252
+ return this.autocompleteDebouncePattern.test(textBeforeCursor) ? ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS : 0;
2253
+ }
2254
+
2255
+ private async runAutocompleteRequest(
2256
+ requestId: number,
2257
+ controller: AbortController,
2258
+ snapshotText: string,
2259
+ snapshotLine: number,
2260
+ snapshotCol: number,
2261
+ options: { force: boolean; explicitTab: boolean },
2262
+ ): Promise<void> {
2263
+ if (!this.autocompleteProvider) return;
2264
+
2265
+ const suggestions = await this.autocompleteProvider.getSuggestions(
2266
+ this.state.lines,
2267
+ this.state.cursorLine,
2268
+ this.state.cursorCol,
2269
+ { signal: controller.signal, force: options.force },
2270
+ );
2271
+
2272
+ if (!this.isAutocompleteRequestCurrent(requestId, controller, snapshotText, snapshotLine, snapshotCol)) {
2273
+ return;
2274
+ }
2275
+
2276
+ this.autocompleteAbort = undefined;
2277
+
2278
+ if (!suggestions || !Array.isArray(suggestions.items) || suggestions.items.length === 0) {
2279
+ this.cancelAutocomplete();
2280
+ this.tui.requestRender();
2281
+ return;
2282
+ }
2283
+
2284
+ if (options.force && options.explicitTab && suggestions.items.length === 1) {
2285
+ const item = suggestions.items[0]!;
2286
+ this.pushUndoSnapshot();
2287
+ this.lastAction = null;
2288
+ const result = this.autocompleteProvider.applyCompletion(
2289
+ this.state.lines,
2290
+ this.state.cursorLine,
2291
+ this.state.cursorCol,
2292
+ item,
2293
+ suggestions.prefix,
2294
+ );
2295
+ this.state.lines = result.lines;
2296
+ this.state.cursorLine = result.cursorLine;
2297
+ this.setCursorCol(result.cursorCol);
2298
+ if (this.onChange) this.onChange(this.getText());
2299
+ this.tui.requestRender();
2300
+ return;
2301
+ }
2302
+
2303
+ this.applyAutocompleteSuggestions(suggestions, options.force ? "force" : "regular");
2304
+ this.tui.requestRender();
2305
+ }
2306
+
2307
+ private isAutocompleteRequestCurrent(
2308
+ requestId: number,
2309
+ controller: AbortController,
2310
+ snapshotText: string,
2311
+ snapshotLine: number,
2312
+ snapshotCol: number,
2313
+ ): boolean {
2314
+ return (
2315
+ !controller.signal.aborted &&
2316
+ requestId === this.autocompleteRequestId &&
2317
+ this.getText() === snapshotText &&
2318
+ this.state.cursorLine === snapshotLine &&
2319
+ this.state.cursorCol === snapshotCol
2320
+ );
2321
+ }
2322
+
2323
+ private applyAutocompleteSuggestions(suggestions: AutocompleteSuggestions, state: "regular" | "force"): void {
2324
+ this.autocompletePrefix = suggestions.prefix;
2325
+ this.autocompleteList = this.createAutocompleteList(suggestions.prefix, suggestions.items);
2326
+
2327
+ const bestMatchIndex = this.getBestAutocompleteMatchIndex(suggestions.items, suggestions.prefix);
2328
+ if (bestMatchIndex >= 0) {
2329
+ this.autocompleteList.setSelectedIndex(bestMatchIndex);
2330
+ }
2331
+
2332
+ this.autocompleteState = state;
2333
+ }
2334
+
2335
+ private cancelAutocompleteRequest(): void {
2336
+ this.autocompleteStartToken += 1;
2337
+ if (this.autocompleteDebounceTimer) {
2338
+ clearTimeout(this.autocompleteDebounceTimer);
2339
+ this.autocompleteDebounceTimer = undefined;
2340
+ }
2341
+ this.autocompleteAbort?.abort();
2342
+ this.autocompleteAbort = undefined;
2343
+ }
2344
+
2345
+ private clearAutocompleteUi(): void {
2346
+ this.autocompleteState = null;
2347
+ this.autocompleteList = undefined;
2348
+ this.autocompletePrefix = "";
2349
+ }
2350
+
2351
+ private cancelAutocomplete(): void {
2352
+ this.cancelAutocompleteRequest();
2353
+ this.clearAutocompleteUi();
2354
+ }
2355
+
2356
+ public isShowingAutocomplete(): boolean {
2357
+ return this.autocompleteState !== null;
2358
+ }
2359
+
2360
+ private updateAutocomplete(): void {
2361
+ if (!this.autocompleteState || !this.autocompleteProvider) return;
2362
+ this.requestAutocomplete({ force: this.autocompleteState === "force", explicitTab: false });
2363
+ }
2364
+ }