@fractaal/pi-tui 0.85.4 → 0.86.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/README.md +175 -19
  2. package/dist/alt-screen-search.d.ts +46 -0
  3. package/dist/alt-screen-search.d.ts.map +1 -0
  4. package/dist/alt-screen-search.js +282 -0
  5. package/dist/alt-screen-search.js.map +1 -0
  6. package/dist/autocomplete.d.ts +2 -1
  7. package/dist/autocomplete.d.ts.map +1 -1
  8. package/dist/autocomplete.js +85 -24
  9. package/dist/autocomplete.js.map +1 -1
  10. package/dist/colors.d.ts +73 -0
  11. package/dist/colors.d.ts.map +1 -0
  12. package/dist/colors.js +273 -0
  13. package/dist/colors.js.map +1 -0
  14. package/dist/components/alt-screen-flash.d.ts +13 -0
  15. package/dist/components/alt-screen-flash.d.ts.map +1 -0
  16. package/dist/components/alt-screen-flash.js +37 -0
  17. package/dist/components/alt-screen-flash.js.map +1 -0
  18. package/dist/components/box.d.ts +3 -1
  19. package/dist/components/box.d.ts.map +1 -1
  20. package/dist/components/box.js +38 -8
  21. package/dist/components/box.js.map +1 -1
  22. package/dist/components/cancellable-loader.d.ts.map +1 -1
  23. package/dist/components/cancellable-loader.js.map +1 -1
  24. package/dist/components/editor.d.ts +6 -1
  25. package/dist/components/editor.d.ts.map +1 -1
  26. package/dist/components/editor.js +118 -24
  27. package/dist/components/editor.js.map +1 -1
  28. package/dist/components/h-stack.d.ts +7 -0
  29. package/dist/components/h-stack.d.ts.map +1 -0
  30. package/dist/components/h-stack.js +43 -0
  31. package/dist/components/h-stack.js.map +1 -0
  32. package/dist/components/image.d.ts +12 -0
  33. package/dist/components/image.d.ts.map +1 -1
  34. package/dist/components/image.js +36 -3
  35. package/dist/components/image.js.map +1 -1
  36. package/dist/components/input.d.ts +12 -1
  37. package/dist/components/input.d.ts.map +1 -1
  38. package/dist/components/input.js +44 -5
  39. package/dist/components/input.js.map +1 -1
  40. package/dist/components/loader.d.ts +2 -0
  41. package/dist/components/loader.d.ts.map +1 -1
  42. package/dist/components/loader.js +10 -3
  43. package/dist/components/loader.js.map +1 -1
  44. package/dist/components/markdown.d.ts +5 -0
  45. package/dist/components/markdown.d.ts.map +1 -1
  46. package/dist/components/markdown.js +150 -9
  47. package/dist/components/markdown.js.map +1 -1
  48. package/dist/components/mouse-region.d.ts +12 -0
  49. package/dist/components/mouse-region.d.ts.map +1 -0
  50. package/dist/components/mouse-region.js +21 -0
  51. package/dist/components/mouse-region.js.map +1 -0
  52. package/dist/components/scroll-view.d.ts +59 -0
  53. package/dist/components/scroll-view.d.ts.map +1 -0
  54. package/dist/components/scroll-view.js +195 -0
  55. package/dist/components/scroll-view.js.map +1 -0
  56. package/dist/components/select-list.d.ts +4 -1
  57. package/dist/components/select-list.d.ts.map +1 -1
  58. package/dist/components/select-list.js +49 -2
  59. package/dist/components/select-list.js.map +1 -1
  60. package/dist/components/settings-list.d.ts +13 -3
  61. package/dist/components/settings-list.d.ts.map +1 -1
  62. package/dist/components/settings-list.js +82 -15
  63. package/dist/components/settings-list.js.map +1 -1
  64. package/dist/components/spacer.d.ts.map +1 -1
  65. package/dist/components/spacer.js.map +1 -1
  66. package/dist/components/stack.d.ts +32 -0
  67. package/dist/components/stack.d.ts.map +1 -0
  68. package/dist/components/stack.js +111 -0
  69. package/dist/components/stack.js.map +1 -0
  70. package/dist/components/text.d.ts.map +1 -1
  71. package/dist/components/text.js +7 -5
  72. package/dist/components/text.js.map +1 -1
  73. package/dist/components/truncated-text.d.ts.map +1 -1
  74. package/dist/components/truncated-text.js.map +1 -1
  75. package/dist/components/v-stack.d.ts +8 -0
  76. package/dist/components/v-stack.d.ts.map +1 -0
  77. package/dist/components/v-stack.js +26 -0
  78. package/dist/components/v-stack.js.map +1 -0
  79. package/dist/editor-component.d.ts.map +1 -1
  80. package/dist/fuzzy.d.ts.map +1 -1
  81. package/dist/fuzzy.js +23 -22
  82. package/dist/fuzzy.js.map +1 -1
  83. package/dist/index.d.ts +18 -6
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +20 -6
  86. package/dist/index.js.map +1 -1
  87. package/dist/keybindings.d.ts +82 -2
  88. package/dist/keybindings.d.ts.map +1 -1
  89. package/dist/keybindings.js +61 -2
  90. package/dist/keybindings.js.map +1 -1
  91. package/dist/keys.d.ts.map +1 -1
  92. package/dist/keys.js.map +1 -1
  93. package/dist/kill-ring.d.ts.map +1 -1
  94. package/dist/kill-ring.js.map +1 -1
  95. package/dist/latex.d.ts +10 -0
  96. package/dist/latex.d.ts.map +1 -0
  97. package/dist/latex.js +1378 -0
  98. package/dist/latex.js.map +1 -0
  99. package/dist/layout-node.d.ts +40 -0
  100. package/dist/layout-node.d.ts.map +1 -0
  101. package/dist/layout-node.js +6 -0
  102. package/dist/layout-node.js.map +1 -0
  103. package/dist/layout.d.ts +42 -0
  104. package/dist/layout.d.ts.map +1 -0
  105. package/dist/layout.js +344 -0
  106. package/dist/layout.js.map +1 -0
  107. package/dist/native-modifiers.d.ts +2 -1
  108. package/dist/native-modifiers.d.ts.map +1 -1
  109. package/dist/native-modifiers.js +3 -43
  110. package/dist/native-modifiers.js.map +1 -1
  111. package/dist/native-module-path.d.ts +7 -0
  112. package/dist/native-module-path.d.ts.map +1 -0
  113. package/dist/native-module-path.js +19 -0
  114. package/dist/native-module-path.js.map +1 -0
  115. package/dist/native-platform.d.ts +20 -0
  116. package/dist/native-platform.d.ts.map +1 -0
  117. package/dist/native-platform.js +42 -0
  118. package/dist/native-platform.js.map +1 -0
  119. package/dist/oklab.d.ts +43 -0
  120. package/dist/oklab.d.ts.map +1 -0
  121. package/dist/oklab.js +210 -0
  122. package/dist/oklab.js.map +1 -0
  123. package/dist/stdin-buffer.d.ts +8 -2
  124. package/dist/stdin-buffer.d.ts.map +1 -1
  125. package/dist/stdin-buffer.js +7 -2
  126. package/dist/stdin-buffer.js.map +1 -1
  127. package/dist/terminal-colors.d.ts +19 -2
  128. package/dist/terminal-colors.d.ts.map +1 -1
  129. package/dist/terminal-colors.js +13 -8
  130. package/dist/terminal-colors.js.map +1 -1
  131. package/dist/terminal-image.d.ts +29 -1
  132. package/dist/terminal-image.d.ts.map +1 -1
  133. package/dist/terminal-image.js +223 -18
  134. package/dist/terminal-image.js.map +1 -1
  135. package/dist/terminal.d.ts +16 -0
  136. package/dist/terminal.d.ts.map +1 -1
  137. package/dist/terminal.js +62 -46
  138. package/dist/terminal.js.map +1 -1
  139. package/dist/tui-alt-screen.d.ts +166 -0
  140. package/dist/tui-alt-screen.d.ts.map +1 -0
  141. package/dist/tui-alt-screen.js +1546 -0
  142. package/dist/tui-alt-screen.js.map +1 -0
  143. package/dist/tui-main-screen.d.ts +39 -0
  144. package/dist/tui-main-screen.d.ts.map +1 -0
  145. package/dist/tui-main-screen.js +594 -0
  146. package/dist/tui-main-screen.js.map +1 -0
  147. package/dist/tui.d.ts +178 -60
  148. package/dist/tui.d.ts.map +1 -1
  149. package/dist/tui.js +303 -641
  150. package/dist/tui.js.map +1 -1
  151. package/dist/undo-stack.d.ts.map +1 -1
  152. package/dist/undo-stack.js.map +1 -1
  153. package/dist/utils.d.ts +22 -0
  154. package/dist/utils.d.ts.map +1 -1
  155. package/dist/utils.js +245 -63
  156. package/dist/utils.js.map +1 -1
  157. package/dist/wheel-scroll.d.ts +23 -0
  158. package/dist/wheel-scroll.d.ts.map +1 -0
  159. package/dist/wheel-scroll.js +73 -0
  160. package/dist/wheel-scroll.js.map +1 -0
  161. package/dist/word-navigation.d.ts.map +1 -1
  162. package/dist/word-navigation.js.map +1 -1
  163. package/native/clipboard.h +208 -0
  164. package/native/darwin/README.md +22 -0
  165. package/native/darwin/build.sh +69 -0
  166. package/native/darwin/prebuilds/darwin-arm64/{darwin-modifiers.node → darwin-platform.node} +0 -0
  167. package/native/darwin/prebuilds/darwin-x64/darwin-platform.node +0 -0
  168. package/native/darwin/src/darwin-platform.m +132 -0
  169. package/native/linux/README.md +23 -0
  170. package/native/linux/build.sh +65 -0
  171. package/native/linux/prebuilds/linux-arm64/linux-platform-x11.node +0 -0
  172. package/native/linux/prebuilds/linux-x64/linux-platform-x11.node +0 -0
  173. package/native/linux/src/clipboard-worker.h +70 -0
  174. package/native/linux/src/linux-platform-x11.c +274 -0
  175. package/native/napi.h +91 -0
  176. package/native/win32/README.md +31 -0
  177. package/native/win32/build.mjs +232 -0
  178. package/native/win32/prebuilds/win32-arm64/win32-platform.node +0 -0
  179. package/native/win32/prebuilds/win32-x64/win32-platform.node +0 -0
  180. package/native/win32/src/win32-platform.c +241 -0
  181. package/package.json +19 -4
  182. package/native/darwin/prebuilds/darwin-x64/darwin-modifiers.node +0 -0
  183. package/native/win32/prebuilds/win32-arm64/win32-console-mode.node +0 -0
  184. package/native/win32/prebuilds/win32-x64/win32-console-mode.node +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAMA;;GAEG;AACH,wBAAgB,oBAAoB,IAAI,IAAI,CAAC,SAAS,CAErD;AAED;;GAEG;AACH,wBAAgB,gBAAgB,IAAI,IAAI,CAAC,SAAS,CAEjD;AA6BD,eAAO,MAAM,aAAa,QAC2H,CAAC;AAoKtJ;;GAEG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAuDhD;AAaD,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAsB3D;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAsCjG;AAmWD;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAuBtE;AAmFD,eAAO,MAAM,iBAAiB,QAAyC,CAAC;AAExE;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEtD;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEvD;AAuED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,GAAG,MAAM,CASzG;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,CAC9B,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,MAAM,EAChB,QAAQ,GAAE,MAAc,EACxB,GAAG,GAAE,OAAe,GAClB,MAAM,CAmIR;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,UAAQ,GAAG,MAAM,CAEpG;AAED,kFAAkF;AAClF,wBAAgB,cAAc,CAC7B,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,EACd,MAAM,UAAQ,GACZ;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAwCjC;AAKD;;;;GAIG;AACH,wBAAgB,eAAe,CAC9B,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,MAAM,EAClB,QAAQ,EAAE,MAAM,EAChB,WAAW,UAAQ,GACjB;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAiE5E","sourcesContent":["import { eastAsianWidth } from \"get-east-asian-width\";\n\n// segmenters (shared instance)\nconst graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\nconst wordSegmenter = new Intl.Segmenter(undefined, { granularity: \"word\" });\n\n/**\n * Get the shared grapheme segmenter instance.\n */\nexport function getGraphemeSegmenter(): Intl.Segmenter {\n\treturn graphemeSegmenter;\n}\n\n/**\n * Get the shared word segmenter instance.\n */\nexport function getWordSegmenter(): Intl.Segmenter {\n\treturn wordSegmenter;\n}\n\n/**\n * Check if a grapheme cluster (after segmentation) could possibly be an RGI emoji.\n * This is a fast heuristic to avoid the expensive rgiEmojiRegex test.\n * The tested Unicode blocks are deliberately broad to account for future\n * Unicode additions.\n */\nfunction couldBeEmoji(segment: string): boolean {\n\tconst cp = segment.codePointAt(0)!;\n\treturn (\n\t\t(cp >= 0x1f000 && cp <= 0x1fbff) || // Emoji and Pictograph\n\t\t(cp >= 0x2300 && cp <= 0x23ff) || // Misc technical\n\t\t(cp >= 0x2600 && cp <= 0x27bf) || // Misc symbols, dingbats\n\t\t(cp >= 0x2b50 && cp <= 0x2b55) || // Specific stars/circles\n\t\tsegment.includes(\"\\uFE0F\") || // Contains VS16 (emoji presentation selector)\n\t\tsegment.length > 2 // Multi-codepoint sequences (ZWJ, skin tones, etc.)\n\t);\n}\n\n// Regexes for character classification (same as string-width library)\nconst zeroWidthRegex = /^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$/v;\nconst leadingNonPrintingRegex = /^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+/v;\nconst rgiEmojiRegex = /^\\p{RGI_Emoji}$/v;\n\n// Cache for non-ASCII strings\nconst WIDTH_CACHE_SIZE = 512;\nconst widthCache = new Map<string, number>();\n\nexport const cjkBreakRegex =\n\t/[\\p{Script_Extensions=Han}\\p{Script_Extensions=Hiragana}\\p{Script_Extensions=Katakana}\\p{Script_Extensions=Hangul}\\p{Script_Extensions=Bopomofo}]/u;\n\nfunction isPrintableAscii(str: string): boolean {\n\tfor (let i = 0; i < str.length; i++) {\n\t\tconst code = str.charCodeAt(i);\n\t\tif (code < 0x20 || code > 0x7e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction truncateFragmentToWidth(text: string, maxWidth: number): { text: string; width: number } {\n\tif (maxWidth <= 0 || text.length === 0) {\n\t\treturn { text: \"\", width: 0 };\n\t}\n\n\tif (isPrintableAscii(text)) {\n\t\tconst clipped = text.slice(0, maxWidth);\n\t\treturn { text: clipped, width: clipped.length };\n\t}\n\n\tconst hasAnsi = text.includes(\"\\x1b\");\n\tconst hasTabs = text.includes(\"\\t\");\n\tif (!hasAnsi && !hasTabs) {\n\t\tlet result = \"\";\n\t\tlet width = 0;\n\t\tfor (const { segment } of graphemeSegmenter.segment(text)) {\n\t\t\tconst w = graphemeWidth(segment);\n\t\t\tif (width + w > maxWidth) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresult += segment;\n\t\t\twidth += w;\n\t\t}\n\t\treturn { text: result, width };\n\t}\n\n\tlet result = \"\";\n\tlet width = 0;\n\tlet i = 0;\n\tlet pendingAnsi = \"\";\n\n\twhile (i < text.length) {\n\t\tconst ansi = extractAnsiCode(text, i);\n\t\tif (ansi) {\n\t\t\tpendingAnsi += ansi.code;\n\t\t\ti += ansi.length;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (text[i] === \"\\t\") {\n\t\t\tif (width + 3 > maxWidth) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (pendingAnsi) {\n\t\t\t\tresult += pendingAnsi;\n\t\t\t\tpendingAnsi = \"\";\n\t\t\t}\n\t\t\tresult += \"\\t\";\n\t\t\twidth += 3;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet end = i;\n\t\twhile (end < text.length && text[end] !== \"\\t\") {\n\t\t\tconst nextAnsi = extractAnsiCode(text, end);\n\t\t\tif (nextAnsi) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tend++;\n\t\t}\n\n\t\tfor (const { segment } of graphemeSegmenter.segment(text.slice(i, end))) {\n\t\t\tconst w = graphemeWidth(segment);\n\t\t\tif (width + w > maxWidth) {\n\t\t\t\treturn { text: result, width };\n\t\t\t}\n\t\t\tif (pendingAnsi) {\n\t\t\t\tresult += pendingAnsi;\n\t\t\t\tpendingAnsi = \"\";\n\t\t\t}\n\t\t\tresult += segment;\n\t\t\twidth += w;\n\t\t}\n\t\ti = end;\n\t}\n\n\treturn { text: result, width };\n}\n\nfunction finalizeTruncatedResult(\n\tprefix: string,\n\tprefixWidth: number,\n\tellipsis: string,\n\tellipsisWidth: number,\n\tmaxWidth: number,\n\tpad: boolean,\n): string {\n\tconst reset = \"\\x1b[0m\";\n\tconst visibleWidth = prefixWidth + ellipsisWidth;\n\tlet result: string;\n\n\tif (ellipsis.length > 0) {\n\t\tresult = `${prefix}${reset}${ellipsis}${reset}`;\n\t} else {\n\t\tresult = `${prefix}${reset}`;\n\t}\n\n\treturn pad ? result + \" \".repeat(Math.max(0, maxWidth - visibleWidth)) : result;\n}\n\n/**\n * Calculate the terminal width of a single grapheme cluster.\n * Based on code from the string-width library, but includes a possible-emoji\n * check to avoid running the RGI_Emoji regex unnecessarily.\n */\nfunction graphemeWidth(segment: string): number {\n\tif (segment === \"\\t\") {\n\t\treturn 3;\n\t}\n\n\t// Zero-width clusters\n\tif (zeroWidthRegex.test(segment)) {\n\t\treturn 0;\n\t}\n\n\t// Emoji check with pre-filter\n\tif (couldBeEmoji(segment) && rgiEmojiRegex.test(segment)) {\n\t\treturn 2;\n\t}\n\n\t// Get base visible codepoint\n\tconst base = segment.replace(leadingNonPrintingRegex, \"\");\n\tconst cp = base.codePointAt(0);\n\tif (cp === undefined) {\n\t\treturn 0;\n\t}\n\n\t// Regional indicator symbols (U+1F1E6..U+1F1FF) are often rendered as\n\t// full-width emoji in terminals, even when isolated during streaming.\n\t// Keep width conservative (2) to avoid terminal auto-wrap drift artifacts.\n\tif (cp >= 0x1f1e6 && cp <= 0x1f1ff) {\n\t\treturn 2;\n\t}\n\n\tlet width = eastAsianWidth(cp);\n\n\t// Trailing halfwidth/fullwidth forms and AM vowels that segment with a base.\n\tif (segment.length > 1) {\n\t\tfor (const char of segment.slice(1)) {\n\t\t\tconst c = char.codePointAt(0)!;\n\t\t\tif (c >= 0xff00 && c <= 0xffef) {\n\t\t\t\twidth += eastAsianWidth(c);\n\t\t\t} else if (c === 0x0e33 || c === 0x0eb3) {\n\t\t\t\twidth += 1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn width;\n}\n\n/**\n * Calculate the visible width of a string in terminal columns.\n */\nexport function visibleWidth(str: string): number {\n\tif (str.length === 0) {\n\t\treturn 0;\n\t}\n\n\t// Fast path: pure ASCII printable\n\tif (isPrintableAscii(str)) {\n\t\treturn str.length;\n\t}\n\n\t// Check cache\n\tconst cached = widthCache.get(str);\n\tif (cached !== undefined) {\n\t\treturn cached;\n\t}\n\n\t// Normalize: tabs to 3 spaces, strip ANSI escape codes\n\tlet clean = str;\n\tif (str.includes(\"\\t\")) {\n\t\tclean = clean.replace(/\\t/g, \" \");\n\t}\n\tif (clean.includes(\"\\x1b\")) {\n\t\t// Strip supported ANSI/OSC/APC escape sequences in one pass.\n\t\t// This covers CSI styling/cursor codes, OSC hyperlinks and prompt markers,\n\t\t// and APC sequences like CURSOR_MARKER.\n\t\tlet stripped = \"\";\n\t\tlet i = 0;\n\t\twhile (i < clean.length) {\n\t\t\tconst ansi = extractAnsiCode(clean, i);\n\t\t\tif (ansi) {\n\t\t\t\ti += ansi.length;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tstripped += clean[i];\n\t\t\ti++;\n\t\t}\n\t\tclean = stripped;\n\t}\n\n\t// Calculate width\n\tlet width = 0;\n\tfor (const { segment } of graphemeSegmenter.segment(clean)) {\n\t\twidth += graphemeWidth(segment);\n\t}\n\n\t// Cache result\n\tif (widthCache.size >= WIDTH_CACHE_SIZE) {\n\t\tconst firstKey = widthCache.keys().next().value;\n\t\tif (firstKey !== undefined) {\n\t\t\twidthCache.delete(firstKey);\n\t\t}\n\t}\n\twidthCache.set(str, width);\n\n\treturn width;\n}\n\n/**\n * Normalize text for terminal output without changing logical editor content.\n * Some terminals render precomposed Thai/Lao AM vowels inconsistently during\n * differential repaint. Their compatibility decompositions have the same cell\n * width but avoid stale-cell artifacts in terminal renderers. Visible tabs are\n * expanded to the fixed width used by layout so terminal tab stops cannot wrap\n * a logical line, while tabs inside terminal string sequences stay untouched.\n */\nconst THAI_LAO_AM_REGEX = /[\\u0e33\\u0eb3]/;\nconst THAI_LAO_AM_GLOBAL_REGEX = /[\\u0e33\\u0eb3]/g;\n\nexport function normalizeTerminalOutput(str: string): string {\n\tlet normalized = str;\n\tif (THAI_LAO_AM_REGEX.test(normalized)) {\n\t\tnormalized = normalized.replace(THAI_LAO_AM_GLOBAL_REGEX, (char) =>\n\t\t\tchar === \"\\u0e33\" ? \"\\u0e4d\\u0e32\" : \"\\u0ecd\\u0eb2\",\n\t\t);\n\t}\n\tif (!normalized.includes(\"\\t\")) return normalized;\n\n\tlet result = \"\";\n\tlet i = 0;\n\twhile (i < normalized.length) {\n\t\tconst ansi = extractAnsiCode(normalized, i);\n\t\tif (ansi) {\n\t\t\tresult += ansi.code;\n\t\t\ti += ansi.length;\n\t\t\tcontinue;\n\t\t}\n\t\tresult += normalized[i] === \"\\t\" ? \" \" : normalized[i];\n\t\ti++;\n\t}\n\treturn result;\n}\n\n/**\n * Extract ANSI escape sequences from a string at the given position.\n */\nexport function extractAnsiCode(str: string, pos: number): { code: string; length: number } | null {\n\tif (pos >= str.length || str[pos] !== \"\\x1b\") return null;\n\n\tconst next = str[pos + 1];\n\n\t// CSI sequence: ESC [ ... m/G/K/H/J\n\tif (next === \"[\") {\n\t\tlet j = pos + 2;\n\t\twhile (j < str.length && !/[mGKHJ]/.test(str[j]!)) j++;\n\t\tif (j < str.length) return { code: str.substring(pos, j + 1), length: j + 1 - pos };\n\t\treturn null;\n\t}\n\n\t// OSC sequence: ESC ] ... BEL or ESC ] ... ST (ESC \\)\n\t// Used for hyperlinks (OSC 8), window titles, etc.\n\tif (next === \"]\") {\n\t\tlet j = pos + 2;\n\t\twhile (j < str.length) {\n\t\t\tif (str[j] === \"\\x07\") return { code: str.substring(pos, j + 1), length: j + 1 - pos };\n\t\t\tif (str[j] === \"\\x1b\" && str[j + 1] === \"\\\\\") return { code: str.substring(pos, j + 2), length: j + 2 - pos };\n\t\t\tj++;\n\t\t}\n\t\treturn null;\n\t}\n\n\t// APC sequence: ESC _ ... BEL or ESC _ ... ST (ESC \\)\n\t// Used for cursor marker and application-specific commands\n\tif (next === \"_\") {\n\t\tlet j = pos + 2;\n\t\twhile (j < str.length) {\n\t\t\tif (str[j] === \"\\x07\") return { code: str.substring(pos, j + 1), length: j + 1 - pos };\n\t\t\tif (str[j] === \"\\x1b\" && str[j + 1] === \"\\\\\") return { code: str.substring(pos, j + 2), length: j + 2 - pos };\n\t\t\tj++;\n\t\t}\n\t\treturn null;\n\t}\n\n\treturn null;\n}\n\ntype Osc8Terminator = \"\\x07\" | \"\\x1b\\\\\";\n\ninterface ActiveHyperlink {\n\tparams: string;\n\turl: string;\n\tterminator: Osc8Terminator;\n}\n\nfunction parseOsc8Hyperlink(ansiCode: string): ActiveHyperlink | null | undefined {\n\tif (!ansiCode.startsWith(\"\\x1b]8;\")) {\n\t\treturn undefined;\n\t}\n\n\tconst terminator: Osc8Terminator = ansiCode.endsWith(\"\\x07\") ? \"\\x07\" : \"\\x1b\\\\\";\n\tconst body = ansiCode.slice(4, terminator === \"\\x07\" ? -1 : -2);\n\tconst separatorIndex = body.indexOf(\";\");\n\tif (separatorIndex === -1) {\n\t\treturn undefined;\n\t}\n\n\tconst params = body.slice(0, separatorIndex);\n\tconst url = body.slice(separatorIndex + 1);\n\tif (!url) {\n\t\treturn null;\n\t}\n\treturn { params, url, terminator };\n}\n\nfunction formatOsc8Hyperlink(hyperlink: ActiveHyperlink): string {\n\treturn `\\x1b]8;${hyperlink.params};${hyperlink.url}${hyperlink.terminator}`;\n}\n\nfunction formatOsc8Close(terminator: Osc8Terminator): string {\n\treturn `\\x1b]8;;${terminator}`;\n}\n\n/**\n * Track active ANSI SGR codes to preserve styling across line breaks.\n */\nclass AnsiCodeTracker {\n\t// Track individual attributes separately so we can reset them specifically\n\tprivate bold = false;\n\tprivate dim = false;\n\tprivate italic = false;\n\tprivate underline = false;\n\tprivate blink = false;\n\tprivate inverse = false;\n\tprivate hidden = false;\n\tprivate strikethrough = false;\n\tprivate fgColor: string | null = null; // Stores the full code like \"31\" or \"38;5;240\"\n\tprivate bgColor: string | null = null; // Stores the full code like \"41\" or \"48;5;240\"\n\tprivate activeHyperlink: ActiveHyperlink | null = null;\n\n\tprocess(ansiCode: string): void {\n\t\t// OSC 8 hyperlink: \\x1b]8;;<url>\\x1b\\\\ (open) or \\x1b]8;;\\x1b\\\\ (close).\n\t\t// Preserve the original terminator because some terminals only make BEL-terminated\n\t\t// links clickable. OAuth login URLs use BEL, so reopening wrapped lines with ST\n\t\t// made only the first physical line clickable in those terminals.\n\t\tconst hyperlink = parseOsc8Hyperlink(ansiCode);\n\t\tif (hyperlink !== undefined) {\n\t\t\tthis.activeHyperlink = hyperlink;\n\t\t\treturn;\n\t\t}\n\n\t\tif (!ansiCode.endsWith(\"m\")) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Extract the parameters between \\x1b[ and m\n\t\tconst match = ansiCode.match(/\\x1b\\[([\\d;]*)m/);\n\t\tif (!match) return;\n\n\t\tconst params = match[1];\n\t\tif (params === \"\" || params === \"0\") {\n\t\t\t// Full reset\n\t\t\tthis.reset();\n\t\t\treturn;\n\t\t}\n\n\t\t// Parse parameters (can be semicolon-separated)\n\t\tconst parts = params.split(\";\");\n\t\tlet i = 0;\n\t\twhile (i < parts.length) {\n\t\t\tconst code = Number.parseInt(parts[i], 10);\n\n\t\t\t// Handle 256-color and RGB codes which consume multiple parameters\n\t\t\tif (code === 38 || code === 48) {\n\t\t\t\t// 38;5;N (256 color fg) or 38;2;R;G;B (RGB fg)\n\t\t\t\t// 48;5;N (256 color bg) or 48;2;R;G;B (RGB bg)\n\t\t\t\tif (parts[i + 1] === \"5\" && parts[i + 2] !== undefined) {\n\t\t\t\t\t// 256 color: 38;5;N or 48;5;N\n\t\t\t\t\tconst colorCode = `${parts[i]};${parts[i + 1]};${parts[i + 2]}`;\n\t\t\t\t\tif (code === 38) {\n\t\t\t\t\t\tthis.fgColor = colorCode;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.bgColor = colorCode;\n\t\t\t\t\t}\n\t\t\t\t\ti += 3;\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (parts[i + 1] === \"2\" && parts[i + 4] !== undefined) {\n\t\t\t\t\t// RGB color: 38;2;R;G;B or 48;2;R;G;B\n\t\t\t\t\tconst colorCode = `${parts[i]};${parts[i + 1]};${parts[i + 2]};${parts[i + 3]};${parts[i + 4]}`;\n\t\t\t\t\tif (code === 38) {\n\t\t\t\t\t\tthis.fgColor = colorCode;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.bgColor = colorCode;\n\t\t\t\t\t}\n\t\t\t\t\ti += 5;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Standard SGR codes\n\t\t\tswitch (code) {\n\t\t\t\tcase 0:\n\t\t\t\t\tthis.reset();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tthis.bold = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tthis.dim = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tthis.italic = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\t\tthis.underline = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 5:\n\t\t\t\t\tthis.blink = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 7:\n\t\t\t\t\tthis.inverse = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 8:\n\t\t\t\t\tthis.hidden = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 9:\n\t\t\t\t\tthis.strikethrough = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 21:\n\t\t\t\t\tthis.bold = false;\n\t\t\t\t\tbreak; // Some terminals\n\t\t\t\tcase 22:\n\t\t\t\t\tthis.bold = false;\n\t\t\t\t\tthis.dim = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 23:\n\t\t\t\t\tthis.italic = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 24:\n\t\t\t\t\tthis.underline = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 25:\n\t\t\t\t\tthis.blink = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 27:\n\t\t\t\t\tthis.inverse = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 28:\n\t\t\t\t\tthis.hidden = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 29:\n\t\t\t\t\tthis.strikethrough = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 39:\n\t\t\t\t\tthis.fgColor = null;\n\t\t\t\t\tbreak; // Default fg\n\t\t\t\tcase 49:\n\t\t\t\t\tthis.bgColor = null;\n\t\t\t\t\tbreak; // Default bg\n\t\t\t\tdefault:\n\t\t\t\t\t// Standard foreground colors 30-37, 90-97\n\t\t\t\t\tif ((code >= 30 && code <= 37) || (code >= 90 && code <= 97)) {\n\t\t\t\t\t\tthis.fgColor = String(code);\n\t\t\t\t\t}\n\t\t\t\t\t// Standard background colors 40-47, 100-107\n\t\t\t\t\telse if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107)) {\n\t\t\t\t\t\tthis.bgColor = String(code);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\t}\n\n\tprivate reset(): void {\n\t\tthis.bold = false;\n\t\tthis.dim = false;\n\t\tthis.italic = false;\n\t\tthis.underline = false;\n\t\tthis.blink = false;\n\t\tthis.inverse = false;\n\t\tthis.hidden = false;\n\t\tthis.strikethrough = false;\n\t\tthis.fgColor = null;\n\t\tthis.bgColor = null;\n\t\t// SGR reset does not affect OSC 8 hyperlink state\n\t}\n\n\t/** Clear all state for reuse. */\n\tclear(): void {\n\t\tthis.reset();\n\t\tthis.activeHyperlink = null;\n\t}\n\n\tgetActiveCodes(): string {\n\t\tconst codes: string[] = [];\n\t\tif (this.bold) codes.push(\"1\");\n\t\tif (this.dim) codes.push(\"2\");\n\t\tif (this.italic) codes.push(\"3\");\n\t\tif (this.underline) codes.push(\"4\");\n\t\tif (this.blink) codes.push(\"5\");\n\t\tif (this.inverse) codes.push(\"7\");\n\t\tif (this.hidden) codes.push(\"8\");\n\t\tif (this.strikethrough) codes.push(\"9\");\n\t\tif (this.fgColor) codes.push(this.fgColor);\n\t\tif (this.bgColor) codes.push(this.bgColor);\n\n\t\tlet result = codes.length > 0 ? `\\x1b[${codes.join(\";\")}m` : \"\";\n\t\tif (this.activeHyperlink) {\n\t\t\tresult += formatOsc8Hyperlink(this.activeHyperlink);\n\t\t}\n\t\treturn result;\n\t}\n\n\thasActiveCodes(): boolean {\n\t\treturn (\n\t\t\tthis.bold ||\n\t\t\tthis.dim ||\n\t\t\tthis.italic ||\n\t\t\tthis.underline ||\n\t\t\tthis.blink ||\n\t\t\tthis.inverse ||\n\t\t\tthis.hidden ||\n\t\t\tthis.strikethrough ||\n\t\t\tthis.fgColor !== null ||\n\t\t\tthis.bgColor !== null ||\n\t\t\tthis.activeHyperlink !== null\n\t\t);\n\t}\n\n\t/**\n\t * Get reset codes for attributes that need to be turned off at line end.\n\t * Underline must be closed to prevent bleeding into padding.\n\t * Active OSC 8 hyperlinks must be closed and re-opened on the next line.\n\t * Returns empty string if no attributes need closing.\n\t */\n\tgetLineEndReset(): string {\n\t\tlet result = \"\";\n\t\tif (this.underline) {\n\t\t\tresult += \"\\x1b[24m\"; // Underline off only\n\t\t}\n\t\tif (this.activeHyperlink) {\n\t\t\tresult += formatOsc8Close(this.activeHyperlink.terminator); // Re-opened at line start via getActiveCodes()\n\t\t}\n\t\treturn result;\n\t}\n}\n\nfunction updateTrackerFromText(text: string, tracker: AnsiCodeTracker): void {\n\tlet i = 0;\n\twhile (i < text.length) {\n\t\tconst ansiResult = extractAnsiCode(text, i);\n\t\tif (ansiResult) {\n\t\t\ttracker.process(ansiResult.code);\n\t\t\ti += ansiResult.length;\n\t\t} else {\n\t\t\ti++;\n\t\t}\n\t}\n}\n\n/**\n * Split text into words while keeping ANSI codes attached.\n */\nfunction splitIntoTokensWithAnsi(text: string): string[] {\n\tconst tokens: string[] = [];\n\tlet current = \"\";\n\tlet pendingAnsi = \"\"; // ANSI codes waiting to be attached to next visible content\n\tlet currentKind: \"space\" | \"word\" | null = null;\n\tlet i = 0;\n\n\tconst flushCurrent = (): void => {\n\t\tif (!current) {\n\t\t\treturn;\n\t\t}\n\t\ttokens.push(current);\n\t\tcurrent = \"\";\n\t\tcurrentKind = null;\n\t};\n\n\twhile (i < text.length) {\n\t\tconst ansiResult = extractAnsiCode(text, i);\n\t\tif (ansiResult) {\n\t\t\t// Hold ANSI codes separately - they'll be attached to the next visible char\n\t\t\tpendingAnsi += ansiResult.code;\n\t\t\ti += ansiResult.length;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet end = i;\n\t\twhile (end < text.length && !extractAnsiCode(text, end)) {\n\t\t\tend++;\n\t\t}\n\n\t\tfor (const { segment } of graphemeSegmenter.segment(text.slice(i, end))) {\n\t\t\tconst segmentIsSpace = segment === \" \";\n\t\t\tif (!segmentIsSpace && cjkBreakRegex.test(segment)) {\n\t\t\t\tflushCurrent();\n\t\t\t\tconst token = pendingAnsi + segment;\n\t\t\t\tpendingAnsi = \"\";\n\t\t\t\ttokens.push(token);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst segmentKind = segmentIsSpace ? \"space\" : \"word\";\n\t\t\tif (current && currentKind !== segmentKind) {\n\t\t\t\tflushCurrent();\n\t\t\t}\n\n\t\t\t// Attach any pending ANSI codes to this visible character\n\t\t\tif (pendingAnsi) {\n\t\t\t\tcurrent += pendingAnsi;\n\t\t\t\tpendingAnsi = \"\";\n\t\t\t}\n\n\t\t\tcurrentKind = segmentKind;\n\t\t\tcurrent += segment;\n\t\t}\n\n\t\ti = end;\n\t}\n\n\t// Handle any remaining pending ANSI codes (attach to last token)\n\tif (pendingAnsi) {\n\t\tif (current) {\n\t\t\tcurrent += pendingAnsi;\n\t\t} else if (tokens.length > 0) {\n\t\t\ttokens[tokens.length - 1] += pendingAnsi;\n\t\t} else {\n\t\t\tcurrent = pendingAnsi;\n\t\t}\n\t}\n\n\tif (current) {\n\t\ttokens.push(current);\n\t}\n\n\treturn tokens;\n}\n\n/**\n * Wrap text with ANSI codes preserved.\n *\n * ONLY does word wrapping - NO padding, NO background colors.\n * Returns lines where each line is <= width visible chars.\n * Active ANSI codes are preserved across line breaks.\n *\n * @param text - Text to wrap (may contain ANSI codes and newlines)\n * @param width - Maximum visible width per line\n * @returns Array of wrapped lines (NOT padded to width)\n */\nexport function wrapTextWithAnsi(text: string, width: number): string[] {\n\tif (!text) {\n\t\treturn [\"\"];\n\t}\n\n\t// Handle newlines by processing each line separately\n\t// Track ANSI state across lines so styles carry over after literal newlines\n\tconst inputLines = text.split(/\\r\\n|\\r|\\n/);\n\tconst result: string[] = [];\n\tconst tracker = new AnsiCodeTracker();\n\n\tfor (const inputLine of inputLines) {\n\t\t// Prepend active ANSI codes from previous lines (except for first line)\n\t\tconst prefix = result.length > 0 ? tracker.getActiveCodes() : \"\";\n\t\tconst wrappedLines = wrapSingleLine(prefix + inputLine, width);\n\t\tfor (const wrappedLine of wrappedLines) {\n\t\t\tresult.push(wrappedLine);\n\t\t}\n\t\t// Update tracker with codes from this line for next iteration\n\t\tupdateTrackerFromText(inputLine, tracker);\n\t}\n\n\treturn result.length > 0 ? result : [\"\"];\n}\n\nfunction wrapSingleLine(line: string, width: number): string[] {\n\tif (!line) {\n\t\treturn [\"\"];\n\t}\n\n\tconst visibleLength = visibleWidth(line);\n\tif (visibleLength <= width) {\n\t\treturn [line];\n\t}\n\n\tconst wrapped: string[] = [];\n\tconst tracker = new AnsiCodeTracker();\n\tconst tokens = splitIntoTokensWithAnsi(line);\n\n\tlet currentLine = \"\";\n\tlet currentVisibleLength = 0;\n\n\tfor (const token of tokens) {\n\t\tconst tokenVisibleLength = visibleWidth(token);\n\t\tconst isWhitespace = token.trim() === \"\";\n\n\t\t// Token itself is too long - break it character by character\n\t\tif (tokenVisibleLength > width && !isWhitespace) {\n\t\t\tif (currentLine) {\n\t\t\t\t// Add specific reset for underline only (preserves background)\n\t\t\t\tconst lineEndReset = tracker.getLineEndReset();\n\t\t\t\tif (lineEndReset) {\n\t\t\t\t\tcurrentLine += lineEndReset;\n\t\t\t\t}\n\t\t\t\twrapped.push(currentLine);\n\t\t\t\tcurrentLine = \"\";\n\t\t\t\tcurrentVisibleLength = 0;\n\t\t\t}\n\n\t\t\t// Break long token - breakLongWord handles its own resets\n\t\t\tconst broken = breakLongWord(token, width, tracker);\n\t\t\tfor (let i = 0; i < broken.length - 1; i++) {\n\t\t\t\twrapped.push(broken[i]!);\n\t\t\t}\n\t\t\tcurrentLine = broken[broken.length - 1];\n\t\t\tcurrentVisibleLength = visibleWidth(currentLine);\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Check if adding this token would exceed width\n\t\tconst totalNeeded = currentVisibleLength + tokenVisibleLength;\n\n\t\tif (totalNeeded > width && currentVisibleLength > 0) {\n\t\t\t// Trim trailing whitespace, then add underline reset (not full reset, to preserve background)\n\t\t\tlet lineToWrap = currentLine.trimEnd();\n\t\t\tconst lineEndReset = tracker.getLineEndReset();\n\t\t\tif (lineEndReset) {\n\t\t\t\tlineToWrap += lineEndReset;\n\t\t\t}\n\t\t\twrapped.push(lineToWrap);\n\t\t\tif (isWhitespace) {\n\t\t\t\t// Don't start new line with whitespace\n\t\t\t\tcurrentLine = tracker.getActiveCodes();\n\t\t\t\tcurrentVisibleLength = 0;\n\t\t\t} else {\n\t\t\t\tcurrentLine = tracker.getActiveCodes() + token;\n\t\t\t\tcurrentVisibleLength = tokenVisibleLength;\n\t\t\t}\n\t\t} else {\n\t\t\t// Add to current line\n\t\t\tcurrentLine += token;\n\t\t\tcurrentVisibleLength += tokenVisibleLength;\n\t\t}\n\n\t\tupdateTrackerFromText(token, tracker);\n\t}\n\n\tif (currentLine) {\n\t\t// No reset at end of final line - let caller handle it\n\t\twrapped.push(currentLine);\n\t}\n\n\t// Trailing whitespace can cause lines to exceed the requested width\n\treturn wrapped.length > 0 ? wrapped.map((line) => line.trimEnd()) : [\"\"];\n}\n\nexport const PUNCTUATION_REGEX = /[(){}[\\]<>.,;:'\"!?+\\-=*/\\\\|&%^$#@~`]/;\n\n/**\n * Check if a character is whitespace.\n */\nexport function isWhitespaceChar(char: string): boolean {\n\treturn /\\s/.test(char);\n}\n\n/**\n * Check if a character is punctuation.\n */\nexport function isPunctuationChar(char: string): boolean {\n\treturn PUNCTUATION_REGEX.test(char);\n}\n\nfunction breakLongWord(word: string, width: number, tracker: AnsiCodeTracker): string[] {\n\tconst lines: string[] = [];\n\tlet currentLine = tracker.getActiveCodes();\n\tlet currentWidth = 0;\n\n\t// First, separate ANSI codes from visible content\n\t// We need to handle ANSI codes specially since they're not graphemes\n\tlet i = 0;\n\tconst segments: Array<{ type: \"ansi\" | \"grapheme\"; value: string }> = [];\n\n\twhile (i < word.length) {\n\t\tconst ansiResult = extractAnsiCode(word, i);\n\t\tif (ansiResult) {\n\t\t\tsegments.push({ type: \"ansi\", value: ansiResult.code });\n\t\t\ti += ansiResult.length;\n\t\t} else {\n\t\t\t// Find the next ANSI code or end of string\n\t\t\tlet end = i;\n\t\t\twhile (end < word.length) {\n\t\t\t\tconst nextAnsi = extractAnsiCode(word, end);\n\t\t\t\tif (nextAnsi) break;\n\t\t\t\tend++;\n\t\t\t}\n\t\t\t// Segment this non-ANSI portion into graphemes\n\t\t\tconst textPortion = word.slice(i, end);\n\t\t\tfor (const seg of graphemeSegmenter.segment(textPortion)) {\n\t\t\t\tsegments.push({ type: \"grapheme\", value: seg.segment });\n\t\t\t}\n\t\t\ti = end;\n\t\t}\n\t}\n\n\t// Now process segments\n\tfor (const seg of segments) {\n\t\tif (seg.type === \"ansi\") {\n\t\t\tcurrentLine += seg.value;\n\t\t\ttracker.process(seg.value);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst grapheme = seg.value;\n\t\t// Skip empty graphemes to avoid issues with string-width calculation\n\t\tif (!grapheme) continue;\n\n\t\tconst graphemeWidth = visibleWidth(grapheme);\n\n\t\tif (currentWidth + graphemeWidth > width) {\n\t\t\t// Add specific reset for underline only (preserves background)\n\t\t\tconst lineEndReset = tracker.getLineEndReset();\n\t\t\tif (lineEndReset) {\n\t\t\t\tcurrentLine += lineEndReset;\n\t\t\t}\n\t\t\tlines.push(currentLine);\n\t\t\tcurrentLine = tracker.getActiveCodes();\n\t\t\tcurrentWidth = 0;\n\t\t}\n\n\t\tcurrentLine += grapheme;\n\t\tcurrentWidth += graphemeWidth;\n\t}\n\n\tif (currentLine) {\n\t\t// No reset at end of final segment - caller handles continuation\n\t\tlines.push(currentLine);\n\t}\n\n\treturn lines.length > 0 ? lines : [\"\"];\n}\n\n/**\n * Apply background color to a line, padding to full width.\n *\n * @param line - Line of text (may contain ANSI codes)\n * @param width - Total width to pad to\n * @param bgFn - Background color function\n * @returns Line with background applied and padded to width\n */\nexport function applyBackgroundToLine(line: string, width: number, bgFn: (text: string) => string): string {\n\t// Calculate padding needed\n\tconst visibleLen = visibleWidth(line);\n\tconst paddingNeeded = Math.max(0, width - visibleLen);\n\tconst padding = \" \".repeat(paddingNeeded);\n\n\t// Apply background to content + padding\n\tconst withPadding = line + padding;\n\treturn bgFn(withPadding);\n}\n\n/**\n * Truncate text to fit within a maximum visible width, adding ellipsis if needed.\n * Optionally pad with spaces to reach exactly maxWidth.\n * Properly handles ANSI escape codes (they don't count toward width).\n *\n * @param text - Text to truncate (may contain ANSI codes)\n * @param maxWidth - Maximum visible width\n * @param ellipsis - Ellipsis string to append when truncating (default: \"...\")\n * @param pad - If true, pad result with spaces to exactly maxWidth (default: false)\n * @returns Truncated text, optionally padded to exactly maxWidth\n */\nexport function truncateToWidth(\n\ttext: string,\n\tmaxWidth: number,\n\tellipsis: string = \"...\",\n\tpad: boolean = false,\n): string {\n\tif (maxWidth <= 0) {\n\t\treturn \"\";\n\t}\n\n\tif (text.length === 0) {\n\t\treturn pad ? \" \".repeat(maxWidth) : \"\";\n\t}\n\n\tconst ellipsisWidth = visibleWidth(ellipsis);\n\tif (ellipsisWidth >= maxWidth) {\n\t\tconst textWidth = visibleWidth(text);\n\t\tif (textWidth <= maxWidth) {\n\t\t\treturn pad ? text + \" \".repeat(maxWidth - textWidth) : text;\n\t\t}\n\n\t\tconst clippedEllipsis = truncateFragmentToWidth(ellipsis, maxWidth);\n\t\tif (clippedEllipsis.width === 0) {\n\t\t\treturn pad ? \" \".repeat(maxWidth) : \"\";\n\t\t}\n\t\treturn finalizeTruncatedResult(\"\", 0, clippedEllipsis.text, clippedEllipsis.width, maxWidth, pad);\n\t}\n\n\tif (isPrintableAscii(text)) {\n\t\tif (text.length <= maxWidth) {\n\t\t\treturn pad ? text + \" \".repeat(maxWidth - text.length) : text;\n\t\t}\n\t\tconst targetWidth = maxWidth - ellipsisWidth;\n\t\treturn finalizeTruncatedResult(text.slice(0, targetWidth), targetWidth, ellipsis, ellipsisWidth, maxWidth, pad);\n\t}\n\n\tconst targetWidth = maxWidth - ellipsisWidth;\n\tlet result = \"\";\n\tlet pendingAnsi = \"\";\n\tlet visibleSoFar = 0;\n\tlet keptWidth = 0;\n\tlet keepContiguousPrefix = true;\n\tlet overflowed = false;\n\tlet exhaustedInput = false;\n\tconst hasAnsi = text.includes(\"\\x1b\");\n\tconst hasTabs = text.includes(\"\\t\");\n\n\tif (!hasAnsi && !hasTabs) {\n\t\tfor (const { segment } of graphemeSegmenter.segment(text)) {\n\t\t\tconst width = graphemeWidth(segment);\n\t\t\tif (keepContiguousPrefix && keptWidth + width <= targetWidth) {\n\t\t\t\tresult += segment;\n\t\t\t\tkeptWidth += width;\n\t\t\t} else {\n\t\t\t\tkeepContiguousPrefix = false;\n\t\t\t}\n\t\t\tvisibleSoFar += width;\n\t\t\tif (visibleSoFar > maxWidth) {\n\t\t\t\toverflowed = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\texhaustedInput = !overflowed;\n\t} else {\n\t\tlet i = 0;\n\t\twhile (i < text.length) {\n\t\t\tconst ansi = extractAnsiCode(text, i);\n\t\t\tif (ansi) {\n\t\t\t\tpendingAnsi += ansi.code;\n\t\t\t\ti += ansi.length;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (text[i] === \"\\t\") {\n\t\t\t\tif (keepContiguousPrefix && keptWidth + 3 <= targetWidth) {\n\t\t\t\t\tif (pendingAnsi) {\n\t\t\t\t\t\tresult += pendingAnsi;\n\t\t\t\t\t\tpendingAnsi = \"\";\n\t\t\t\t\t}\n\t\t\t\t\tresult += \"\\t\";\n\t\t\t\t\tkeptWidth += 3;\n\t\t\t\t} else {\n\t\t\t\t\tkeepContiguousPrefix = false;\n\t\t\t\t\tpendingAnsi = \"\";\n\t\t\t\t}\n\t\t\t\tvisibleSoFar += 3;\n\t\t\t\tif (visibleSoFar > maxWidth) {\n\t\t\t\t\toverflowed = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tlet end = i;\n\t\t\twhile (end < text.length && text[end] !== \"\\t\") {\n\t\t\t\tconst nextAnsi = extractAnsiCode(text, end);\n\t\t\t\tif (nextAnsi) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tend++;\n\t\t\t}\n\n\t\t\tfor (const { segment } of graphemeSegmenter.segment(text.slice(i, end))) {\n\t\t\t\tconst width = graphemeWidth(segment);\n\t\t\t\tif (keepContiguousPrefix && keptWidth + width <= targetWidth) {\n\t\t\t\t\tif (pendingAnsi) {\n\t\t\t\t\t\tresult += pendingAnsi;\n\t\t\t\t\t\tpendingAnsi = \"\";\n\t\t\t\t\t}\n\t\t\t\t\tresult += segment;\n\t\t\t\t\tkeptWidth += width;\n\t\t\t\t} else {\n\t\t\t\t\tkeepContiguousPrefix = false;\n\t\t\t\t\tpendingAnsi = \"\";\n\t\t\t\t}\n\n\t\t\t\tvisibleSoFar += width;\n\t\t\t\tif (visibleSoFar > maxWidth) {\n\t\t\t\t\toverflowed = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (overflowed) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ti = end;\n\t\t}\n\t\texhaustedInput = i >= text.length;\n\t}\n\n\tif (!overflowed && exhaustedInput) {\n\t\treturn pad ? text + \" \".repeat(Math.max(0, maxWidth - visibleSoFar)) : text;\n\t}\n\n\treturn finalizeTruncatedResult(result, keptWidth, ellipsis, ellipsisWidth, maxWidth, pad);\n}\n\n/**\n * Extract a range of visible columns from a line. Handles ANSI codes and wide chars.\n * @param strict - If true, exclude wide chars at boundary that would extend past the range\n */\nexport function sliceByColumn(line: string, startCol: number, length: number, strict = false): string {\n\treturn sliceWithWidth(line, startCol, length, strict).text;\n}\n\n/** Like sliceByColumn but also returns the actual visible width of the result. */\nexport function sliceWithWidth(\n\tline: string,\n\tstartCol: number,\n\tlength: number,\n\tstrict = false,\n): { text: string; width: number } {\n\tif (length <= 0) return { text: \"\", width: 0 };\n\tconst endCol = startCol + length;\n\tlet result = \"\",\n\t\tresultWidth = 0,\n\t\tcurrentCol = 0,\n\t\ti = 0,\n\t\tpendingAnsi = \"\";\n\n\twhile (i < line.length) {\n\t\tconst ansi = extractAnsiCode(line, i);\n\t\tif (ansi) {\n\t\t\tif (currentCol >= startCol && currentCol < endCol) result += ansi.code;\n\t\t\telse if (currentCol < startCol) pendingAnsi += ansi.code;\n\t\t\ti += ansi.length;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet textEnd = i;\n\t\twhile (textEnd < line.length && !extractAnsiCode(line, textEnd)) textEnd++;\n\n\t\tfor (const { segment } of graphemeSegmenter.segment(line.slice(i, textEnd))) {\n\t\t\tconst w = graphemeWidth(segment);\n\t\t\tconst inRange = currentCol >= startCol && currentCol < endCol;\n\t\t\tconst fits = !strict || currentCol + w <= endCol;\n\t\t\tif (inRange && fits) {\n\t\t\t\tif (pendingAnsi) {\n\t\t\t\t\tresult += pendingAnsi;\n\t\t\t\t\tpendingAnsi = \"\";\n\t\t\t\t}\n\t\t\t\tresult += segment;\n\t\t\t\tresultWidth += w;\n\t\t\t}\n\t\t\tcurrentCol += w;\n\t\t\tif (currentCol >= endCol) break;\n\t\t}\n\t\ti = textEnd;\n\t\tif (currentCol >= endCol) break;\n\t}\n\treturn { text: result, width: resultWidth };\n}\n\n// Pooled tracker instance for extractSegments (avoids allocation per call)\nconst pooledStyleTracker = new AnsiCodeTracker();\n\n/**\n * Extract \"before\" and \"after\" segments from a line in a single pass.\n * Used for overlay compositing where we need content before and after the overlay region.\n * Preserves styling from before the overlay that should affect content after it.\n */\nexport function extractSegments(\n\tline: string,\n\tbeforeEnd: number,\n\tafterStart: number,\n\tafterLen: number,\n\tstrictAfter = false,\n): { before: string; beforeWidth: number; after: string; afterWidth: number } {\n\tlet before = \"\",\n\t\tbeforeWidth = 0,\n\t\tafter = \"\",\n\t\tafterWidth = 0;\n\tlet currentCol = 0,\n\t\ti = 0;\n\tlet pendingAnsiBefore = \"\";\n\tlet afterStarted = false;\n\tconst afterEnd = afterStart + afterLen;\n\n\t// Track styling state so \"after\" inherits styling from before the overlay\n\tpooledStyleTracker.clear();\n\n\twhile (i < line.length) {\n\t\tconst ansi = extractAnsiCode(line, i);\n\t\tif (ansi) {\n\t\t\t// Track all SGR codes to know styling state at afterStart\n\t\t\tpooledStyleTracker.process(ansi.code);\n\t\t\t// Include ANSI codes in their respective segments\n\t\t\tif (currentCol < beforeEnd) {\n\t\t\t\tpendingAnsiBefore += ansi.code;\n\t\t\t} else if (currentCol >= afterStart && currentCol < afterEnd && afterStarted) {\n\t\t\t\t// Only include after we've started \"after\" (styling already prepended)\n\t\t\t\tafter += ansi.code;\n\t\t\t}\n\t\t\ti += ansi.length;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet textEnd = i;\n\t\twhile (textEnd < line.length && !extractAnsiCode(line, textEnd)) textEnd++;\n\n\t\tfor (const { segment } of graphemeSegmenter.segment(line.slice(i, textEnd))) {\n\t\t\tconst w = graphemeWidth(segment);\n\n\t\t\tif (currentCol < beforeEnd && currentCol + w <= beforeEnd) {\n\t\t\t\tif (pendingAnsiBefore) {\n\t\t\t\t\tbefore += pendingAnsiBefore;\n\t\t\t\t\tpendingAnsiBefore = \"\";\n\t\t\t\t}\n\t\t\t\tbefore += segment;\n\t\t\t\tbeforeWidth += w;\n\t\t\t} else if (currentCol >= afterStart && currentCol < afterEnd) {\n\t\t\t\tconst fits = !strictAfter || currentCol + w <= afterEnd;\n\t\t\t\tif (fits) {\n\t\t\t\t\t// On first \"after\" grapheme, prepend inherited styling from before overlay\n\t\t\t\t\tif (!afterStarted) {\n\t\t\t\t\t\tafter += pooledStyleTracker.getActiveCodes();\n\t\t\t\t\t\tafterStarted = true;\n\t\t\t\t\t}\n\t\t\t\t\tafter += segment;\n\t\t\t\t\tafterWidth += w;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcurrentCol += w;\n\t\t\t// Early exit: done with \"before\" only, or done with both segments\n\t\t\tif (afterLen <= 0 ? currentCol >= beforeEnd : currentCol >= afterEnd) break;\n\t\t}\n\t\ti = textEnd;\n\t\tif (afterLen <= 0 ? currentCol >= beforeEnd : currentCol >= afterEnd) break;\n\t}\n\n\treturn { before, beforeWidth, after, afterWidth };\n}\n"]}
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAMA;;GAEG;AACH,wBAAgB,oBAAoB,IAAI,IAAI,CAAC,SAAS,CAErD;AAED;;GAEG;AACH,wBAAgB,gBAAgB,IAAI,IAAI,CAAC,SAAS,CAEjD;AAmCD,eAAO,MAAM,aAAa,QAC2H,CAAC;AAGtJ,eAAO,MAAM,mBAAmB,QAG/B,CAAC;AACF,eAAO,MAAM,0BAA0B,QAA2D,CAAC;AACnG,eAAO,MAAM,yBAAyB,QAAgE,CAAC;AAwLvG;;GAEG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CA4DhD;AAED,iFAAiF;AACjF,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAc1D;AAED,UAAU,iBAAiB;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;CACZ;AAED,mFAAmF;AACnF,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,iBAAiB,GAAG,SAAS,CAqBhG;AAED,qEAAqE;AACrE,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAsBpF;AAaD,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAsB3D;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAGjG;AAyWD,mFAAmF;AACnF,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAI5D;AA0FD;;;;;;;;;;GAUG;AACH;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,GAAG,IAAI,CAE3D;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAuBtE;AAmFD,eAAO,MAAM,iBAAiB,QAAyC,CAAC;AAExE;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEtD;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEvD;AAuED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,GAAG,MAAM,CASzG;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,CAC9B,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,MAAM,EAChB,QAAQ,GAAE,MAAc,EACxB,GAAG,GAAE,OAAe,GAClB,MAAM,CAmIR;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,UAAQ,GAAG,MAAM,CAEpG;AAED,kFAAkF;AAClF,wBAAgB,cAAc,CAC7B,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,EACd,MAAM,UAAQ,GACZ;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CA2CjC;AAKD;;;;GAIG;AACH,wBAAgB,eAAe,CAC9B,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,MAAM,EAClB,QAAQ,EAAE,MAAM,EAChB,WAAW,UAAQ,GACjB;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAiE5E"}
package/dist/utils.js CHANGED
@@ -33,11 +33,20 @@ function couldBeEmoji(segment) {
33
33
  // Regexes for character classification (same as string-width library)
34
34
  const zeroWidthRegex = /^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Mark}|\p{Surrogate})+$/v;
35
35
  const leadingNonPrintingRegex = /^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v;
36
+ const nonPrintingCharRegex = /^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Mark}|\p{Surrogate})$/v;
37
+ const markCharRegex = /^\p{Mark}$/v;
38
+ // Marks that terminals allocate cells for when attached to a base character.
39
+ // This includes Unicode spacing marks and non-spacing exceptions in legacy wcwidth tables.
40
+ const terminalSpacingMarkRegex = /^(?:[\p{Spacing_Mark}--[\u1734\u302E\u302F]]|[\u065F\u0F7F\u102B\u102C\u1031\u1033-\u1035\u1038\u103A-\u103E])+$/v;
36
41
  const rgiEmojiRegex = /^\p{RGI_Emoji}$/v;
37
42
  // Cache for non-ASCII strings
38
43
  const WIDTH_CACHE_SIZE = 512;
39
44
  const widthCache = new Map();
40
45
  export const cjkBreakRegex = /[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}\p{Script_Extensions=Bopomofo}]/u;
46
+ // CJK letters remain part of words and paths; only punctuation can separate prose from completions.
47
+ export const cjkPunctuationRegex = new RegExp(`(?:(?=\\p{Punctuation})${cjkBreakRegex.source}|[,.:;!?()[]{}“”‘’…—])`, "u");
48
+ export const autocompleteSeparatorRegex = new RegExp(`(?:\\s|${cjkPunctuationRegex.source})`, "u");
49
+ export const autocompleteBoundaryRegex = new RegExp(`(?:^|${autocompleteSeparatorRegex.source})`, "u");
41
50
  function isPrintableAscii(str) {
42
51
  for (let i = 0; i < str.length; i++) {
43
52
  const code = str.charCodeAt(i);
@@ -120,13 +129,14 @@ function truncateFragmentToWidth(text, maxWidth) {
120
129
  }
121
130
  function finalizeTruncatedResult(prefix, prefixWidth, ellipsis, ellipsisWidth, maxWidth, pad) {
122
131
  const reset = "\x1b[0m";
132
+ const hyperlinkClose = getActiveOsc8Close(prefix);
123
133
  const visibleWidth = prefixWidth + ellipsisWidth;
124
134
  let result;
125
135
  if (ellipsis.length > 0) {
126
- result = `${prefix}${reset}${ellipsis}${reset}`;
136
+ result = `${prefix}${hyperlinkClose}${reset}${ellipsis}${reset}`;
127
137
  }
128
138
  else {
129
- result = `${prefix}${reset}`;
139
+ result = `${prefix}${hyperlinkClose}${reset}`;
130
140
  }
131
141
  return pad ? result + " ".repeat(Math.max(0, maxWidth - visibleWidth)) : result;
132
142
  }
@@ -136,8 +146,16 @@ function finalizeTruncatedResult(prefix, prefixWidth, ellipsis, ellipsisWidth, m
136
146
  * check to avoid running the RGI_Emoji regex unnecessarily.
137
147
  */
138
148
  function graphemeWidth(segment) {
139
- if (segment === "\t") {
140
- return 3;
149
+ if (segment.length === 1) {
150
+ const code = segment.charCodeAt(0);
151
+ if (code >= 0x20 && code <= 0x7e)
152
+ return 1;
153
+ if (code === 0x09)
154
+ return 3;
155
+ }
156
+ // Some marks occupy cells even without a base character.
157
+ if (terminalSpacingMarkRegex.test(segment)) {
158
+ return [...segment].length;
141
159
  }
142
160
  // Zero-width clusters
143
161
  if (zeroWidthRegex.test(segment)) {
@@ -160,16 +178,30 @@ function graphemeWidth(segment) {
160
178
  return 2;
161
179
  }
162
180
  let width = eastAsianWidth(cp);
163
- // Trailing halfwidth/fullwidth forms and AM vowels that segment with a base.
164
- if (segment.length > 1) {
165
- for (const char of segment.slice(1)) {
181
+ // Intl.Segmenter can group multiple terminal-spacing code points into one
182
+ // grapheme. Count trailing visible code points that terminals may allocate
183
+ // cells for: Indic consonants after marks, halfwidth/fullwidth forms, and
184
+ // Thai/Lao AM vowels.
185
+ let followsMark = false;
186
+ const chars = [...base];
187
+ for (const char of chars.slice(1)) {
188
+ if (terminalSpacingMarkRegex.test(char)) {
189
+ width += 1;
190
+ followsMark = false;
191
+ }
192
+ else if (markCharRegex.test(char)) {
193
+ followsMark = true;
194
+ }
195
+ else if (!nonPrintingCharRegex.test(char)) {
166
196
  const c = char.codePointAt(0);
167
- if (c >= 0xff00 && c <= 0xffef) {
197
+ if (followsMark || (c >= 0xff00 && c <= 0xffef)) {
198
+ // halfwidth + fullwidth forms
168
199
  width += eastAsianWidth(c);
169
200
  }
170
201
  else if (c === 0x0e33 || c === 0x0eb3) {
171
202
  width += 1;
172
203
  }
204
+ followsMark = false;
173
205
  }
174
206
  }
175
207
  return width;
@@ -181,9 +213,11 @@ export function visibleWidth(str) {
181
213
  if (str.length === 0) {
182
214
  return 0;
183
215
  }
184
- // Fast path: pure ASCII printable
185
- if (isPrintableAscii(str)) {
186
- return str.length;
216
+ // Fast path: printable ASCII, tabs, and ANSI escape sequences. Styled lines take this path, so
217
+ // re-rendering after a theme change does not run grapheme segmentation on every line.
218
+ const asciiWidth = asciiVisibleWidth(str);
219
+ if (asciiWidth !== -1) {
220
+ return asciiWidth;
187
221
  }
188
222
  // Check cache
189
223
  const cached = widthCache.get(str);
@@ -195,22 +229,26 @@ export function visibleWidth(str) {
195
229
  if (str.includes("\t")) {
196
230
  clean = clean.replace(/\t/g, " ");
197
231
  }
198
- if (clean.includes("\x1b")) {
232
+ let escapeIndex = clean.indexOf("\x1b");
233
+ if (escapeIndex !== -1) {
199
234
  // Strip supported ANSI/OSC/APC escape sequences in one pass.
200
235
  // This covers CSI styling/cursor codes, OSC hyperlinks and prompt markers,
201
236
  // and APC sequences like CURSOR_MARKER.
202
237
  let stripped = "";
203
- let i = 0;
204
- while (i < clean.length) {
205
- const ansi = extractAnsiCode(clean, i);
206
- if (ansi) {
207
- i += ansi.length;
208
- continue;
238
+ let copyFrom = 0;
239
+ while (escapeIndex !== -1) {
240
+ const length = ansiCodeLength(clean, escapeIndex);
241
+ if (length > 0) {
242
+ stripped += clean.slice(copyFrom, escapeIndex);
243
+ escapeIndex += length;
244
+ copyFrom = escapeIndex;
209
245
  }
210
- stripped += clean[i];
211
- i++;
246
+ else {
247
+ escapeIndex++;
248
+ }
249
+ escapeIndex = clean.indexOf("\x1b", escapeIndex);
212
250
  }
213
- clean = stripped;
251
+ clean = stripped + clean.slice(copyFrom);
214
252
  }
215
253
  // Calculate width
216
254
  let width = 0;
@@ -227,6 +265,74 @@ export function visibleWidth(str) {
227
265
  widthCache.set(str, width);
228
266
  return width;
229
267
  }
268
+ /** Remove ANSI, OSC, and APC control sequences while preserving visible text. */
269
+ export function stripTerminalSequences(str) {
270
+ if (!str.includes("\x1b"))
271
+ return str;
272
+ let result = "";
273
+ let i = 0;
274
+ while (i < str.length) {
275
+ const ansi = extractAnsiCode(str, i);
276
+ if (ansi) {
277
+ i += ansi.length;
278
+ continue;
279
+ }
280
+ result += str[i];
281
+ i++;
282
+ }
283
+ return result;
284
+ }
285
+ /** Return the terminal-cell range occupied by the grapheme at a visible column. */
286
+ export function getGraphemeCellRange(line, column) {
287
+ let currentCol = 0;
288
+ let i = 0;
289
+ while (i < line.length) {
290
+ const ansi = extractAnsiCode(line, i);
291
+ if (ansi) {
292
+ i += ansi.length;
293
+ continue;
294
+ }
295
+ let textEnd = i;
296
+ while (textEnd < line.length && !extractAnsiCode(line, textEnd))
297
+ textEnd++;
298
+ for (const { segment } of graphemeSegmenter.segment(line.slice(i, textEnd))) {
299
+ const width = graphemeWidth(segment);
300
+ if (width > 0 && column >= currentCol && column < currentCol + width) {
301
+ return { start: currentCol, end: currentCol + width };
302
+ }
303
+ currentCol += width;
304
+ }
305
+ i = textEnd;
306
+ }
307
+ return undefined;
308
+ }
309
+ /** Return the OSC 8 hyperlink covering a visible terminal column. */
310
+ export function getOsc8LinkAtColumn(line, column) {
311
+ let activeUrl;
312
+ let currentCol = 0;
313
+ let i = 0;
314
+ while (i < line.length) {
315
+ const ansi = extractAnsiCode(line, i);
316
+ if (ansi) {
317
+ const hyperlink = /^\x1b\]8;[^;]*;([^\x07\x1b]*)(?:\x07|\x1b\\)$/.exec(ansi.code);
318
+ if (hyperlink)
319
+ activeUrl = hyperlink[1] || undefined;
320
+ i += ansi.length;
321
+ continue;
322
+ }
323
+ let textEnd = i;
324
+ while (textEnd < line.length && !extractAnsiCode(line, textEnd))
325
+ textEnd++;
326
+ for (const { segment } of graphemeSegmenter.segment(line.slice(i, textEnd))) {
327
+ const width = segment === "\t" ? 3 : graphemeWidth(segment);
328
+ if (column >= currentCol && column < currentCol + width)
329
+ return activeUrl;
330
+ currentCol += width;
331
+ }
332
+ i = textEnd;
333
+ }
334
+ return undefined;
335
+ }
230
336
  /**
231
337
  * Normalize text for terminal output without changing logical editor content.
232
338
  * Some terminals render precomposed Thai/Lao AM vowels inconsistently during
@@ -262,45 +368,68 @@ export function normalizeTerminalOutput(str) {
262
368
  * Extract ANSI escape sequences from a string at the given position.
263
369
  */
264
370
  export function extractAnsiCode(str, pos) {
265
- if (pos >= str.length || str[pos] !== "\x1b")
266
- return null;
371
+ const length = ansiCodeLength(str, pos);
372
+ return length > 0 ? { code: str.substring(pos, pos + length), length } : null;
373
+ }
374
+ /**
375
+ * Width of a string made of printable ASCII, tabs, and ANSI escape sequences, or -1 if it contains
376
+ * anything else. Matches `visibleWidth` for those strings without allocating.
377
+ */
378
+ function asciiVisibleWidth(str) {
379
+ let width = 0;
380
+ let i = 0;
381
+ while (i < str.length) {
382
+ const code = str.charCodeAt(i);
383
+ if (code >= 0x20 && code <= 0x7e) {
384
+ width++;
385
+ i++;
386
+ }
387
+ else if (code === 0x09) {
388
+ width += 3;
389
+ i++;
390
+ }
391
+ else if (code === 0x1b) {
392
+ const length = ansiCodeLength(str, i);
393
+ if (length === 0)
394
+ return -1;
395
+ i += length;
396
+ }
397
+ else {
398
+ return -1;
399
+ }
400
+ }
401
+ return width;
402
+ }
403
+ /** Length of the ANSI/OSC/APC escape sequence starting at `pos`, or 0 if there is none. */
404
+ function ansiCodeLength(str, pos) {
405
+ if (pos >= str.length || str.charCodeAt(pos) !== 0x1b)
406
+ return 0;
267
407
  const next = str[pos + 1];
268
408
  // CSI sequence: ESC [ ... m/G/K/H/J
269
409
  if (next === "[") {
270
- let j = pos + 2;
271
- while (j < str.length && !/[mGKHJ]/.test(str[j]))
272
- j++;
273
- if (j < str.length)
274
- return { code: str.substring(pos, j + 1), length: j + 1 - pos };
275
- return null;
410
+ for (let j = pos + 2; j < str.length; j++) {
411
+ const c = str.charCodeAt(j);
412
+ // m, G, K, H, J
413
+ if (c === 0x6d || c === 0x47 || c === 0x4b || c === 0x48 || c === 0x4a)
414
+ return j + 1 - pos;
415
+ }
416
+ return 0;
276
417
  }
277
418
  // OSC sequence: ESC ] ... BEL or ESC ] ... ST (ESC \)
278
419
  // Used for hyperlinks (OSC 8), window titles, etc.
279
- if (next === "]") {
280
- let j = pos + 2;
281
- while (j < str.length) {
282
- if (str[j] === "\x07")
283
- return { code: str.substring(pos, j + 1), length: j + 1 - pos };
284
- if (str[j] === "\x1b" && str[j + 1] === "\\")
285
- return { code: str.substring(pos, j + 2), length: j + 2 - pos };
286
- j++;
287
- }
288
- return null;
289
- }
290
420
  // APC sequence: ESC _ ... BEL or ESC _ ... ST (ESC \)
291
421
  // Used for cursor marker and application-specific commands
292
- if (next === "_") {
293
- let j = pos + 2;
294
- while (j < str.length) {
295
- if (str[j] === "\x07")
296
- return { code: str.substring(pos, j + 1), length: j + 1 - pos };
297
- if (str[j] === "\x1b" && str[j + 1] === "\\")
298
- return { code: str.substring(pos, j + 2), length: j + 2 - pos };
299
- j++;
422
+ if (next === "]" || next === "_") {
423
+ for (let j = pos + 2; j < str.length; j++) {
424
+ const c = str.charCodeAt(j);
425
+ if (c === 0x07)
426
+ return j + 1 - pos;
427
+ if (c === 0x1b && str[j + 1] === "\\")
428
+ return j + 2 - pos;
300
429
  }
301
- return null;
430
+ return 0;
302
431
  }
303
- return null;
432
+ return 0;
304
433
  }
305
434
  function parseOsc8Hyperlink(ansiCode) {
306
435
  if (!ansiCode.startsWith("\x1b]8;")) {
@@ -325,6 +454,27 @@ function formatOsc8Hyperlink(hyperlink) {
325
454
  function formatOsc8Close(terminator) {
326
455
  return `\x1b]8;;${terminator}`;
327
456
  }
457
+ function getActiveOsc8Close(prefix) {
458
+ if (!prefix.includes("\x1b]8;")) {
459
+ return "";
460
+ }
461
+ let activeHyperlink = null;
462
+ let i = 0;
463
+ while (i < prefix.length) {
464
+ const ansi = extractAnsiCode(prefix, i);
465
+ if (ansi) {
466
+ const hyperlink = parseOsc8Hyperlink(ansi.code);
467
+ if (hyperlink !== undefined) {
468
+ activeHyperlink = hyperlink;
469
+ }
470
+ i += ansi.length;
471
+ }
472
+ else {
473
+ i++;
474
+ }
475
+ }
476
+ return activeHyperlink ? formatOsc8Close(activeHyperlink.terminator) : "";
477
+ }
328
478
  /**
329
479
  * Track active ANSI SGR codes to preserve styling across line breaks.
330
480
  */
@@ -518,6 +668,9 @@ class AnsiCodeTracker {
518
668
  }
519
669
  return result;
520
670
  }
671
+ getActiveBackgroundCode() {
672
+ return this.bgColor ? `\x1b[${this.bgColor}m` : "";
673
+ }
521
674
  hasActiveCodes() {
522
675
  return (this.bold ||
523
676
  this.dim ||
@@ -549,18 +702,29 @@ class AnsiCodeTracker {
549
702
  }
550
703
  }
551
704
  function updateTrackerFromText(text, tracker) {
552
- let i = 0;
553
- while (i < text.length) {
554
- const ansiResult = extractAnsiCode(text, i);
555
- if (ansiResult) {
556
- tracker.process(ansiResult.code);
557
- i += ansiResult.length;
705
+ let i = text.indexOf("\x1b");
706
+ while (i !== -1) {
707
+ const length = ansiCodeLength(text, i);
708
+ if (length > 0) {
709
+ tracker.process(text.substring(i, i + length));
710
+ i += length;
558
711
  }
559
712
  else {
560
713
  i++;
561
714
  }
715
+ i = text.indexOf("\x1b", i);
562
716
  }
563
717
  }
718
+ /** Return only the background color active at the end of an ANSI-styled string. */
719
+ export function getActiveBackgroundAnsi(text) {
720
+ const tracker = new AnsiCodeTracker();
721
+ updateTrackerFromText(text, tracker);
722
+ return tracker.getActiveBackgroundCode();
723
+ }
724
+ function* graphemeSegments(text) {
725
+ for (const { segment } of graphemeSegmenter.segment(text))
726
+ yield segment;
727
+ }
564
728
  /**
565
729
  * Split text into words while keeping ANSI codes attached.
566
730
  */
@@ -586,13 +750,19 @@ function splitIntoTokensWithAnsi(text) {
586
750
  i += ansiResult.length;
587
751
  continue;
588
752
  }
589
- let end = i;
590
- while (end < text.length && !extractAnsiCode(text, end)) {
591
- end++;
753
+ // Visible text runs up to the next escape sequence.
754
+ let end = text.indexOf("\x1b", i + 1);
755
+ while (end !== -1 && ansiCodeLength(text, end) === 0) {
756
+ end = text.indexOf("\x1b", end + 1);
592
757
  }
593
- for (const { segment } of graphemeSegmenter.segment(text.slice(i, end))) {
758
+ if (end === -1)
759
+ end = text.length;
760
+ const chunk = text.slice(i, end);
761
+ // Printable ASCII characters are single graphemes, so skip the segmenter for them.
762
+ const ascii = isPrintableAscii(chunk);
763
+ for (const segment of ascii ? chunk : graphemeSegments(chunk)) {
594
764
  const segmentIsSpace = segment === " ";
595
- if (!segmentIsSpace && cjkBreakRegex.test(segment)) {
765
+ if (!ascii && !segmentIsSpace && cjkBreakRegex.test(segment)) {
596
766
  flushCurrent();
597
767
  const token = pendingAnsi + segment;
598
768
  pendingAnsi = "";
@@ -641,6 +811,15 @@ function splitIntoTokensWithAnsi(text) {
641
811
  * @param width - Maximum visible width per line
642
812
  * @returns Array of wrapped lines (NOT padded to width)
643
813
  */
814
+ /**
815
+ * Flatten cached lines. V8 keeps a string built by concatenation as a tree of its parts until something reads it
816
+ * whole, and a cached line kept as such a tree retains several times its own size. Converting a string to a number
817
+ * reads it whole, so V8 flattens it in place; the strings' values do not change.
818
+ */
819
+ export function flattenLines(lines) {
820
+ for (const line of lines)
821
+ Number(line);
822
+ }
644
823
  export function wrapTextWithAnsi(text, width) {
645
824
  if (!text) {
646
825
  return [""];
@@ -976,8 +1155,11 @@ export function sliceWithWidth(line, startCol, length, strict = false) {
976
1155
  while (i < line.length) {
977
1156
  const ansi = extractAnsiCode(line, i);
978
1157
  if (ansi) {
979
- if (currentCol >= startCol && currentCol < endCol)
980
- result += ansi.code;
1158
+ if (currentCol >= startCol && currentCol < endCol) {
1159
+ // Keep original order: codes from before the range must precede codes at the boundary
1160
+ result += pendingAnsi + ansi.code;
1161
+ pendingAnsi = "";
1162
+ }
981
1163
  else if (currentCol < startCol)
982
1164
  pendingAnsi += ansi.code;
983
1165
  i += ansi.length;