utils.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  1. import { eastAsianWidth } from "get-east-asian-width";
  2. // segmenters (shared instance)
  3. const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
  4. const wordSegmenter = new Intl.Segmenter(undefined, { granularity: "word" });
  5. /**
  6. * Get the shared grapheme segmenter instance.
  7. */
  8. export function getGraphemeSegmenter(): Intl.Segmenter {
  9. return graphemeSegmenter;
  10. }
  11. /**
  12. * Get the shared word segmenter instance.
  13. */
  14. export function getWordSegmenter(): Intl.Segmenter {
  15. return wordSegmenter;
  16. }
  17. /**
  18. * Check if a grapheme cluster (after segmentation) could possibly be an RGI emoji.
  19. * This is a fast heuristic to avoid the expensive rgiEmojiRegex test.
  20. * The tested Unicode blocks are deliberately broad to account for future
  21. * Unicode additions.
  22. */
  23. function couldBeEmoji(segment: string): boolean {
  24. const cp = segment.codePointAt(0)!;
  25. return (
  26. (cp >= 0x1f000 && cp <= 0x1fbff) || // Emoji and Pictograph
  27. (cp >= 0x2300 && cp <= 0x23ff) || // Misc technical
  28. (cp >= 0x2600 && cp <= 0x27bf) || // Misc symbols, dingbats
  29. (cp >= 0x2b50 && cp <= 0x2b55) || // Specific stars/circles
  30. segment.includes("\uFE0F") || // Contains VS16 (emoji presentation selector)
  31. segment.length > 2 // Multi-codepoint sequences (ZWJ, skin tones, etc.)
  32. );
  33. }
  34. // Regexes for character classification (same as string-width library)
  35. const zeroWidthRegex = /^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Mark}|\p{Surrogate})+$/v;
  36. const leadingNonPrintingRegex = /^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v;
  37. const rgiEmojiRegex = /^\p{RGI_Emoji}$/v;
  38. // Cache for non-ASCII strings
  39. const WIDTH_CACHE_SIZE = 512;
  40. const widthCache = new Map<string, number>();
  41. const cjkBreakRegex =
  42. /[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}\p{Script_Extensions=Bopomofo}]/u;
  43. function isPrintableAscii(str: string): boolean {
  44. for (let i = 0; i < str.length; i++) {
  45. const code = str.charCodeAt(i);
  46. if (code < 0x20 || code > 0x7e) {
  47. return false;
  48. }
  49. }
  50. return true;
  51. }
  52. function truncateFragmentToWidth(text: string, maxWidth: number): { text: string; width: number } {
  53. if (maxWidth <= 0 || text.length === 0) {
  54. return { text: "", width: 0 };
  55. }
  56. if (isPrintableAscii(text)) {
  57. const clipped = text.slice(0, maxWidth);
  58. return { text: clipped, width: clipped.length };
  59. }
  60. const hasAnsi = text.includes("\x1b");
  61. const hasTabs = text.includes("\t");
  62. if (!hasAnsi && !hasTabs) {
  63. let result = "";
  64. let width = 0;
  65. for (const { segment } of graphemeSegmenter.segment(text)) {
  66. const w = graphemeWidth(segment);
  67. if (width + w > maxWidth) {
  68. break;
  69. }
  70. result += segment;
  71. width += w;
  72. }
  73. return { text: result, width };
  74. }
  75. let result = "";
  76. let width = 0;
  77. let i = 0;
  78. let pendingAnsi = "";
  79. while (i < text.length) {
  80. const ansi = extractAnsiCode(text, i);
  81. if (ansi) {
  82. pendingAnsi += ansi.code;
  83. i += ansi.length;
  84. continue;
  85. }
  86. if (text[i] === "\t") {
  87. if (width + 3 > maxWidth) {
  88. break;
  89. }
  90. if (pendingAnsi) {
  91. result += pendingAnsi;
  92. pendingAnsi = "";
  93. }
  94. result += "\t";
  95. width += 3;
  96. i++;
  97. continue;
  98. }
  99. let end = i;
  100. while (end < text.length && text[end] !== "\t") {
  101. const nextAnsi = extractAnsiCode(text, end);
  102. if (nextAnsi) {
  103. break;
  104. }
  105. end++;
  106. }
  107. for (const { segment } of graphemeSegmenter.segment(text.slice(i, end))) {
  108. const w = graphemeWidth(segment);
  109. if (width + w > maxWidth) {
  110. return { text: result, width };
  111. }
  112. if (pendingAnsi) {
  113. result += pendingAnsi;
  114. pendingAnsi = "";
  115. }
  116. result += segment;
  117. width += w;
  118. }
  119. i = end;
  120. }
  121. return { text: result, width };
  122. }
  123. function finalizeTruncatedResult(
  124. prefix: string,
  125. prefixWidth: number,
  126. ellipsis: string,
  127. ellipsisWidth: number,
  128. maxWidth: number,
  129. pad: boolean,
  130. ): string {
  131. const reset = "\x1b[0m";
  132. const visibleWidth = prefixWidth + ellipsisWidth;
  133. let result: string;
  134. if (ellipsis.length > 0) {
  135. result = `${prefix}${reset}${ellipsis}${reset}`;
  136. } else {
  137. result = `${prefix}${reset}`;
  138. }
  139. return pad ? result + " ".repeat(Math.max(0, maxWidth - visibleWidth)) : result;
  140. }
  141. /**
  142. * Calculate the terminal width of a single grapheme cluster.
  143. * Based on code from the string-width library, but includes a possible-emoji
  144. * check to avoid running the RGI_Emoji regex unnecessarily.
  145. */
  146. function graphemeWidth(segment: string): number {
  147. if (segment === "\t") {
  148. return 3;
  149. }
  150. // Zero-width clusters
  151. if (zeroWidthRegex.test(segment)) {
  152. return 0;
  153. }
  154. // Emoji check with pre-filter
  155. if (couldBeEmoji(segment) && rgiEmojiRegex.test(segment)) {
  156. return 2;
  157. }
  158. // Get base visible codepoint
  159. const base = segment.replace(leadingNonPrintingRegex, "");
  160. const cp = base.codePointAt(0);
  161. if (cp === undefined) {
  162. return 0;
  163. }
  164. // Regional indicator symbols (U+1F1E6..U+1F1FF) are often rendered as
  165. // full-width emoji in terminals, even when isolated during streaming.
  166. // Keep width conservative (2) to avoid terminal auto-wrap drift artifacts.
  167. if (cp >= 0x1f1e6 && cp <= 0x1f1ff) {
  168. return 2;
  169. }
  170. let width = eastAsianWidth(cp);
  171. // Trailing halfwidth/fullwidth forms and AM vowels that segment with a base.
  172. if (segment.length > 1) {
  173. for (const char of segment.slice(1)) {
  174. const c = char.codePointAt(0)!;
  175. if (c >= 0xff00 && c <= 0xffef) {
  176. width += eastAsianWidth(c);
  177. } else if (c === 0x0e33 || c === 0x0eb3) {
  178. width += 1;
  179. }
  180. }
  181. }
  182. return width;
  183. }
  184. /**
  185. * Calculate the visible width of a string in terminal columns.
  186. */
  187. export function visibleWidth(str: string): number {
  188. if (str.length === 0) {
  189. return 0;
  190. }
  191. // Fast path: pure ASCII printable
  192. if (isPrintableAscii(str)) {
  193. return str.length;
  194. }
  195. // Check cache
  196. const cached = widthCache.get(str);
  197. if (cached !== undefined) {
  198. return cached;
  199. }
  200. // Normalize: tabs to 3 spaces, strip ANSI escape codes
  201. let clean = str;
  202. if (str.includes("\t")) {
  203. clean = clean.replace(/\t/g, " ");
  204. }
  205. if (clean.includes("\x1b")) {
  206. // Strip supported ANSI/OSC/APC escape sequences in one pass.
  207. // This covers CSI styling/cursor codes, OSC hyperlinks and prompt markers,
  208. // and APC sequences like CURSOR_MARKER.
  209. let stripped = "";
  210. let i = 0;
  211. while (i < clean.length) {
  212. const ansi = extractAnsiCode(clean, i);
  213. if (ansi) {
  214. i += ansi.length;
  215. continue;
  216. }
  217. stripped += clean[i];
  218. i++;
  219. }
  220. clean = stripped;
  221. }
  222. // Calculate width
  223. let width = 0;
  224. for (const { segment } of graphemeSegmenter.segment(clean)) {
  225. width += graphemeWidth(segment);
  226. }
  227. // Cache result
  228. if (widthCache.size >= WIDTH_CACHE_SIZE) {
  229. const firstKey = widthCache.keys().next().value;
  230. if (firstKey !== undefined) {
  231. widthCache.delete(firstKey);
  232. }
  233. }
  234. widthCache.set(str, width);
  235. return width;
  236. }
  237. /**
  238. * Normalize text for terminal output without changing logical editor content.
  239. * Some terminals render precomposed Thai/Lao AM vowels inconsistently during
  240. * differential repaint. Their compatibility decompositions have the same cell
  241. * width but avoid stale-cell artifacts in terminal renderers.
  242. */
  243. const THAI_LAO_AM_REGEX = /[\u0e33\u0eb3]/;
  244. const THAI_LAO_AM_GLOBAL_REGEX = /[\u0e33\u0eb3]/g;
  245. export function normalizeTerminalOutput(str: string): string {
  246. if (!THAI_LAO_AM_REGEX.test(str)) return str;
  247. return str.replace(THAI_LAO_AM_GLOBAL_REGEX, (char) => (char === "\u0e33" ? "\u0e4d\u0e32" : "\u0ecd\u0eb2"));
  248. }
  249. /**
  250. * Extract ANSI escape sequences from a string at the given position.
  251. */
  252. export function extractAnsiCode(str: string, pos: number): { code: string; length: number } | null {
  253. if (pos >= str.length || str[pos] !== "\x1b") return null;
  254. const next = str[pos + 1];
  255. // CSI sequence: ESC [ ... m/G/K/H/J
  256. if (next === "[") {
  257. let j = pos + 2;
  258. while (j < str.length && !/[mGKHJ]/.test(str[j]!)) j++;
  259. if (j < str.length) return { code: str.substring(pos, j + 1), length: j + 1 - pos };
  260. return null;
  261. }
  262. // OSC sequence: ESC ] ... BEL or ESC ] ... ST (ESC \)
  263. // Used for hyperlinks (OSC 8), window titles, etc.
  264. if (next === "]") {
  265. let j = pos + 2;
  266. while (j < str.length) {
  267. if (str[j] === "\x07") return { code: str.substring(pos, j + 1), length: j + 1 - pos };
  268. if (str[j] === "\x1b" && str[j + 1] === "\\") return { code: str.substring(pos, j + 2), length: j + 2 - pos };
  269. j++;
  270. }
  271. return null;
  272. }
  273. // APC sequence: ESC _ ... BEL or ESC _ ... ST (ESC \)
  274. // Used for cursor marker and application-specific commands
  275. if (next === "_") {
  276. let j = pos + 2;
  277. while (j < str.length) {
  278. if (str[j] === "\x07") return { code: str.substring(pos, j + 1), length: j + 1 - pos };
  279. if (str[j] === "\x1b" && str[j + 1] === "\\") return { code: str.substring(pos, j + 2), length: j + 2 - pos };
  280. j++;
  281. }
  282. return null;
  283. }
  284. return null;
  285. }
  286. type Osc8Terminator = "\x07" | "\x1b\\";
  287. interface ActiveHyperlink {
  288. params: string;
  289. url: string;
  290. terminator: Osc8Terminator;
  291. }
  292. function parseOsc8Hyperlink(ansiCode: string): ActiveHyperlink | null | undefined {
  293. if (!ansiCode.startsWith("\x1b]8;")) {
  294. return undefined;
  295. }
  296. const terminator: Osc8Terminator = ansiCode.endsWith("\x07") ? "\x07" : "\x1b\\";
  297. const body = ansiCode.slice(4, terminator === "\x07" ? -1 : -2);
  298. const separatorIndex = body.indexOf(";");
  299. if (separatorIndex === -1) {
  300. return undefined;
  301. }
  302. const params = body.slice(0, separatorIndex);
  303. const url = body.slice(separatorIndex + 1);
  304. if (!url) {
  305. return null;
  306. }
  307. return { params, url, terminator };
  308. }
  309. function formatOsc8Hyperlink(hyperlink: ActiveHyperlink): string {
  310. return `\x1b]8;${hyperlink.params};${hyperlink.url}${hyperlink.terminator}`;
  311. }
  312. function formatOsc8Close(terminator: Osc8Terminator): string {
  313. return `\x1b]8;;${terminator}`;
  314. }
  315. /**
  316. * Track active ANSI SGR codes to preserve styling across line breaks.
  317. */
  318. class AnsiCodeTracker {
  319. // Track individual attributes separately so we can reset them specifically
  320. private bold = false;
  321. private dim = false;
  322. private italic = false;
  323. private underline = false;
  324. private blink = false;
  325. private inverse = false;
  326. private hidden = false;
  327. private strikethrough = false;
  328. private fgColor: string | null = null; // Stores the full code like "31" or "38;5;240"
  329. private bgColor: string | null = null; // Stores the full code like "41" or "48;5;240"
  330. private activeHyperlink: ActiveHyperlink | null = null;
  331. process(ansiCode: string): void {
  332. // OSC 8 hyperlink: \x1b]8;;<url>\x1b\\ (open) or \x1b]8;;\x1b\\ (close).
  333. // Preserve the original terminator because some terminals only make BEL-terminated
  334. // links clickable. OAuth login URLs use BEL, so reopening wrapped lines with ST
  335. // made only the first physical line clickable in those terminals.
  336. const hyperlink = parseOsc8Hyperlink(ansiCode);
  337. if (hyperlink !== undefined) {
  338. this.activeHyperlink = hyperlink;
  339. return;
  340. }
  341. if (!ansiCode.endsWith("m")) {
  342. return;
  343. }
  344. // Extract the parameters between \x1b[ and m
  345. const match = ansiCode.match(/\x1b\[([\d;]*)m/);
  346. if (!match) return;
  347. const params = match[1];
  348. if (params === "" || params === "0") {
  349. // Full reset
  350. this.reset();
  351. return;
  352. }
  353. // Parse parameters (can be semicolon-separated)
  354. const parts = params.split(";");
  355. let i = 0;
  356. while (i < parts.length) {
  357. const code = Number.parseInt(parts[i], 10);
  358. // Handle 256-color and RGB codes which consume multiple parameters
  359. if (code === 38 || code === 48) {
  360. // 38;5;N (256 color fg) or 38;2;R;G;B (RGB fg)
  361. // 48;5;N (256 color bg) or 48;2;R;G;B (RGB bg)
  362. if (parts[i + 1] === "5" && parts[i + 2] !== undefined) {
  363. // 256 color: 38;5;N or 48;5;N
  364. const colorCode = `${parts[i]};${parts[i + 1]};${parts[i + 2]}`;
  365. if (code === 38) {
  366. this.fgColor = colorCode;
  367. } else {
  368. this.bgColor = colorCode;
  369. }
  370. i += 3;
  371. continue;
  372. } else if (parts[i + 1] === "2" && parts[i + 4] !== undefined) {
  373. // RGB color: 38;2;R;G;B or 48;2;R;G;B
  374. const colorCode = `${parts[i]};${parts[i + 1]};${parts[i + 2]};${parts[i + 3]};${parts[i + 4]}`;
  375. if (code === 38) {
  376. this.fgColor = colorCode;
  377. } else {
  378. this.bgColor = colorCode;
  379. }
  380. i += 5;
  381. continue;
  382. }
  383. }
  384. // Standard SGR codes
  385. switch (code) {
  386. case 0:
  387. this.reset();
  388. break;
  389. case 1:
  390. this.bold = true;
  391. break;
  392. case 2:
  393. this.dim = true;
  394. break;
  395. case 3:
  396. this.italic = true;
  397. break;
  398. case 4:
  399. this.underline = true;
  400. break;
  401. case 5:
  402. this.blink = true;
  403. break;
  404. case 7:
  405. this.inverse = true;
  406. break;
  407. case 8:
  408. this.hidden = true;
  409. break;
  410. case 9:
  411. this.strikethrough = true;
  412. break;
  413. case 21:
  414. this.bold = false;
  415. break; // Some terminals
  416. case 22:
  417. this.bold = false;
  418. this.dim = false;
  419. break;
  420. case 23:
  421. this.italic = false;
  422. break;
  423. case 24:
  424. this.underline = false;
  425. break;
  426. case 25:
  427. this.blink = false;
  428. break;
  429. case 27:
  430. this.inverse = false;
  431. break;
  432. case 28:
  433. this.hidden = false;
  434. break;
  435. case 29:
  436. this.strikethrough = false;
  437. break;
  438. case 39:
  439. this.fgColor = null;
  440. break; // Default fg
  441. case 49:
  442. this.bgColor = null;
  443. break; // Default bg
  444. default:
  445. // Standard foreground colors 30-37, 90-97
  446. if ((code >= 30 && code <= 37) || (code >= 90 && code <= 97)) {
  447. this.fgColor = String(code);
  448. }
  449. // Standard background colors 40-47, 100-107
  450. else if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107)) {
  451. this.bgColor = String(code);
  452. }
  453. break;
  454. }
  455. i++;
  456. }
  457. }
  458. private reset(): void {
  459. this.bold = false;
  460. this.dim = false;
  461. this.italic = false;
  462. this.underline = false;
  463. this.blink = false;
  464. this.inverse = false;
  465. this.hidden = false;
  466. this.strikethrough = false;
  467. this.fgColor = null;
  468. this.bgColor = null;
  469. // SGR reset does not affect OSC 8 hyperlink state
  470. }
  471. /** Clear all state for reuse. */
  472. clear(): void {
  473. this.reset();
  474. this.activeHyperlink = null;
  475. }
  476. getActiveCodes(): string {
  477. const codes: string[] = [];
  478. if (this.bold) codes.push("1");
  479. if (this.dim) codes.push("2");
  480. if (this.italic) codes.push("3");
  481. if (this.underline) codes.push("4");
  482. if (this.blink) codes.push("5");
  483. if (this.inverse) codes.push("7");
  484. if (this.hidden) codes.push("8");
  485. if (this.strikethrough) codes.push("9");
  486. if (this.fgColor) codes.push(this.fgColor);
  487. if (this.bgColor) codes.push(this.bgColor);
  488. let result = codes.length > 0 ? `\x1b[${codes.join(";")}m` : "";
  489. if (this.activeHyperlink) {
  490. result += formatOsc8Hyperlink(this.activeHyperlink);
  491. }
  492. return result;
  493. }
  494. hasActiveCodes(): boolean {
  495. return (
  496. this.bold ||
  497. this.dim ||
  498. this.italic ||
  499. this.underline ||
  500. this.blink ||
  501. this.inverse ||
  502. this.hidden ||
  503. this.strikethrough ||
  504. this.fgColor !== null ||
  505. this.bgColor !== null ||
  506. this.activeHyperlink !== null
  507. );
  508. }
  509. /**
  510. * Get reset codes for attributes that need to be turned off at line end.
  511. * Underline must be closed to prevent bleeding into padding.
  512. * Active OSC 8 hyperlinks must be closed and re-opened on the next line.
  513. * Returns empty string if no attributes need closing.
  514. */
  515. getLineEndReset(): string {
  516. let result = "";
  517. if (this.underline) {
  518. result += "\x1b[24m"; // Underline off only
  519. }
  520. if (this.activeHyperlink) {
  521. result += formatOsc8Close(this.activeHyperlink.terminator); // Re-opened at line start via getActiveCodes()
  522. }
  523. return result;
  524. }
  525. }
  526. function updateTrackerFromText(text: string, tracker: AnsiCodeTracker): void {
  527. let i = 0;
  528. while (i < text.length) {
  529. const ansiResult = extractAnsiCode(text, i);
  530. if (ansiResult) {
  531. tracker.process(ansiResult.code);
  532. i += ansiResult.length;
  533. } else {
  534. i++;
  535. }
  536. }
  537. }
  538. /**
  539. * Split text into words while keeping ANSI codes attached.
  540. */
  541. function splitIntoTokensWithAnsi(text: string): string[] {
  542. const tokens: string[] = [];
  543. let current = "";
  544. let pendingAnsi = ""; // ANSI codes waiting to be attached to next visible content
  545. let currentKind: "space" | "word" | null = null;
  546. let i = 0;
  547. const flushCurrent = (): void => {
  548. if (!current) {
  549. return;
  550. }
  551. tokens.push(current);
  552. current = "";
  553. currentKind = null;
  554. };
  555. while (i < text.length) {
  556. const ansiResult = extractAnsiCode(text, i);
  557. if (ansiResult) {
  558. // Hold ANSI codes separately - they'll be attached to the next visible char
  559. pendingAnsi += ansiResult.code;
  560. i += ansiResult.length;
  561. continue;
  562. }
  563. let end = i;
  564. while (end < text.length && !extractAnsiCode(text, end)) {
  565. end++;
  566. }
  567. for (const { segment } of graphemeSegmenter.segment(text.slice(i, end))) {
  568. const segmentIsSpace = segment === " ";
  569. if (!segmentIsSpace && cjkBreakRegex.test(segment)) {
  570. flushCurrent();
  571. const token = pendingAnsi + segment;
  572. pendingAnsi = "";
  573. tokens.push(token);
  574. continue;
  575. }
  576. const segmentKind = segmentIsSpace ? "space" : "word";
  577. if (current && currentKind !== segmentKind) {
  578. flushCurrent();
  579. }
  580. // Attach any pending ANSI codes to this visible character
  581. if (pendingAnsi) {
  582. current += pendingAnsi;
  583. pendingAnsi = "";
  584. }
  585. currentKind = segmentKind;
  586. current += segment;
  587. }
  588. i = end;
  589. }
  590. // Handle any remaining pending ANSI codes (attach to last token)
  591. if (pendingAnsi) {
  592. if (current) {
  593. current += pendingAnsi;
  594. } else if (tokens.length > 0) {
  595. tokens[tokens.length - 1] += pendingAnsi;
  596. } else {
  597. current = pendingAnsi;
  598. }
  599. }
  600. if (current) {
  601. tokens.push(current);
  602. }
  603. return tokens;
  604. }
  605. /**
  606. * Wrap text with ANSI codes preserved.
  607. *
  608. * ONLY does word wrapping - NO padding, NO background colors.
  609. * Returns lines where each line is <= width visible chars.
  610. * Active ANSI codes are preserved across line breaks.
  611. *
  612. * @param text - Text to wrap (may contain ANSI codes and newlines)
  613. * @param width - Maximum visible width per line
  614. * @returns Array of wrapped lines (NOT padded to width)
  615. */
  616. export function wrapTextWithAnsi(text: string, width: number): string[] {
  617. if (!text) {
  618. return [""];
  619. }
  620. // Handle newlines by processing each line separately
  621. // Track ANSI state across lines so styles carry over after literal newlines
  622. const inputLines = text.split("\n");
  623. const result: string[] = [];
  624. const tracker = new AnsiCodeTracker();
  625. for (const inputLine of inputLines) {
  626. // Prepend active ANSI codes from previous lines (except for first line)
  627. const prefix = result.length > 0 ? tracker.getActiveCodes() : "";
  628. const wrappedLines = wrapSingleLine(prefix + inputLine, width);
  629. for (const wrappedLine of wrappedLines) {
  630. result.push(wrappedLine);
  631. }
  632. // Update tracker with codes from this line for next iteration
  633. updateTrackerFromText(inputLine, tracker);
  634. }
  635. return result.length > 0 ? result : [""];
  636. }
  637. function wrapSingleLine(line: string, width: number): string[] {
  638. if (!line) {
  639. return [""];
  640. }
  641. const visibleLength = visibleWidth(line);
  642. if (visibleLength <= width) {
  643. return [line];
  644. }
  645. const wrapped: string[] = [];
  646. const tracker = new AnsiCodeTracker();
  647. const tokens = splitIntoTokensWithAnsi(line);
  648. let currentLine = "";
  649. let currentVisibleLength = 0;
  650. for (const token of tokens) {
  651. const tokenVisibleLength = visibleWidth(token);
  652. const isWhitespace = token.trim() === "";
  653. // Token itself is too long - break it character by character
  654. if (tokenVisibleLength > width && !isWhitespace) {
  655. if (currentLine) {
  656. // Add specific reset for underline only (preserves background)
  657. const lineEndReset = tracker.getLineEndReset();
  658. if (lineEndReset) {
  659. currentLine += lineEndReset;
  660. }
  661. wrapped.push(currentLine);
  662. currentLine = "";
  663. currentVisibleLength = 0;
  664. }
  665. // Break long token - breakLongWord handles its own resets
  666. const broken = breakLongWord(token, width, tracker);
  667. for (let i = 0; i < broken.length - 1; i++) {
  668. wrapped.push(broken[i]!);
  669. }
  670. currentLine = broken[broken.length - 1];
  671. currentVisibleLength = visibleWidth(currentLine);
  672. continue;
  673. }
  674. // Check if adding this token would exceed width
  675. const totalNeeded = currentVisibleLength + tokenVisibleLength;
  676. if (totalNeeded > width && currentVisibleLength > 0) {
  677. // Trim trailing whitespace, then add underline reset (not full reset, to preserve background)
  678. let lineToWrap = currentLine.trimEnd();
  679. const lineEndReset = tracker.getLineEndReset();
  680. if (lineEndReset) {
  681. lineToWrap += lineEndReset;
  682. }
  683. wrapped.push(lineToWrap);
  684. if (isWhitespace) {
  685. // Don't start new line with whitespace
  686. currentLine = tracker.getActiveCodes();
  687. currentVisibleLength = 0;
  688. } else {
  689. currentLine = tracker.getActiveCodes() + token;
  690. currentVisibleLength = tokenVisibleLength;
  691. }
  692. } else {
  693. // Add to current line
  694. currentLine += token;
  695. currentVisibleLength += tokenVisibleLength;
  696. }
  697. updateTrackerFromText(token, tracker);
  698. }
  699. if (currentLine) {
  700. // No reset at end of final line - let caller handle it
  701. wrapped.push(currentLine);
  702. }
  703. // Trailing whitespace can cause lines to exceed the requested width
  704. return wrapped.length > 0 ? wrapped.map((line) => line.trimEnd()) : [""];
  705. }
  706. export const PUNCTUATION_REGEX = /[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;
  707. /**
  708. * Check if a character is whitespace.
  709. */
  710. export function isWhitespaceChar(char: string): boolean {
  711. return /\s/.test(char);
  712. }
  713. /**
  714. * Check if a character is punctuation.
  715. */
  716. export function isPunctuationChar(char: string): boolean {
  717. return PUNCTUATION_REGEX.test(char);
  718. }
  719. function breakLongWord(word: string, width: number, tracker: AnsiCodeTracker): string[] {
  720. const lines: string[] = [];
  721. let currentLine = tracker.getActiveCodes();
  722. let currentWidth = 0;
  723. // First, separate ANSI codes from visible content
  724. // We need to handle ANSI codes specially since they're not graphemes
  725. let i = 0;
  726. const segments: Array<{ type: "ansi" | "grapheme"; value: string }> = [];
  727. while (i < word.length) {
  728. const ansiResult = extractAnsiCode(word, i);
  729. if (ansiResult) {
  730. segments.push({ type: "ansi", value: ansiResult.code });
  731. i += ansiResult.length;
  732. } else {
  733. // Find the next ANSI code or end of string
  734. let end = i;
  735. while (end < word.length) {
  736. const nextAnsi = extractAnsiCode(word, end);
  737. if (nextAnsi) break;
  738. end++;
  739. }
  740. // Segment this non-ANSI portion into graphemes
  741. const textPortion = word.slice(i, end);
  742. for (const seg of graphemeSegmenter.segment(textPortion)) {
  743. segments.push({ type: "grapheme", value: seg.segment });
  744. }
  745. i = end;
  746. }
  747. }
  748. // Now process segments
  749. for (const seg of segments) {
  750. if (seg.type === "ansi") {
  751. currentLine += seg.value;
  752. tracker.process(seg.value);
  753. continue;
  754. }
  755. const grapheme = seg.value;
  756. // Skip empty graphemes to avoid issues with string-width calculation
  757. if (!grapheme) continue;
  758. const graphemeWidth = visibleWidth(grapheme);
  759. if (currentWidth + graphemeWidth > width) {
  760. // Add specific reset for underline only (preserves background)
  761. const lineEndReset = tracker.getLineEndReset();
  762. if (lineEndReset) {
  763. currentLine += lineEndReset;
  764. }
  765. lines.push(currentLine);
  766. currentLine = tracker.getActiveCodes();
  767. currentWidth = 0;
  768. }
  769. currentLine += grapheme;
  770. currentWidth += graphemeWidth;
  771. }
  772. if (currentLine) {
  773. // No reset at end of final segment - caller handles continuation
  774. lines.push(currentLine);
  775. }
  776. return lines.length > 0 ? lines : [""];
  777. }
  778. /**
  779. * Apply background color to a line, padding to full width.
  780. *
  781. * @param line - Line of text (may contain ANSI codes)
  782. * @param width - Total width to pad to
  783. * @param bgFn - Background color function
  784. * @returns Line with background applied and padded to width
  785. */
  786. export function applyBackgroundToLine(line: string, width: number, bgFn: (text: string) => string): string {
  787. // Calculate padding needed
  788. const visibleLen = visibleWidth(line);
  789. const paddingNeeded = Math.max(0, width - visibleLen);
  790. const padding = " ".repeat(paddingNeeded);
  791. // Apply background to content + padding
  792. const withPadding = line + padding;
  793. return bgFn(withPadding);
  794. }
  795. /**
  796. * Truncate text to fit within a maximum visible width, adding ellipsis if needed.
  797. * Optionally pad with spaces to reach exactly maxWidth.
  798. * Properly handles ANSI escape codes (they don't count toward width).
  799. *
  800. * @param text - Text to truncate (may contain ANSI codes)
  801. * @param maxWidth - Maximum visible width
  802. * @param ellipsis - Ellipsis string to append when truncating (default: "...")
  803. * @param pad - If true, pad result with spaces to exactly maxWidth (default: false)
  804. * @returns Truncated text, optionally padded to exactly maxWidth
  805. */
  806. export function truncateToWidth(
  807. text: string,
  808. maxWidth: number,
  809. ellipsis: string = "...",
  810. pad: boolean = false,
  811. ): string {
  812. if (maxWidth <= 0) {
  813. return "";
  814. }
  815. if (text.length === 0) {
  816. return pad ? " ".repeat(maxWidth) : "";
  817. }
  818. const ellipsisWidth = visibleWidth(ellipsis);
  819. if (ellipsisWidth >= maxWidth) {
  820. const textWidth = visibleWidth(text);
  821. if (textWidth <= maxWidth) {
  822. return pad ? text + " ".repeat(maxWidth - textWidth) : text;
  823. }
  824. const clippedEllipsis = truncateFragmentToWidth(ellipsis, maxWidth);
  825. if (clippedEllipsis.width === 0) {
  826. return pad ? " ".repeat(maxWidth) : "";
  827. }
  828. return finalizeTruncatedResult("", 0, clippedEllipsis.text, clippedEllipsis.width, maxWidth, pad);
  829. }
  830. if (isPrintableAscii(text)) {
  831. if (text.length <= maxWidth) {
  832. return pad ? text + " ".repeat(maxWidth - text.length) : text;
  833. }
  834. const targetWidth = maxWidth - ellipsisWidth;
  835. return finalizeTruncatedResult(text.slice(0, targetWidth), targetWidth, ellipsis, ellipsisWidth, maxWidth, pad);
  836. }
  837. const targetWidth = maxWidth - ellipsisWidth;
  838. let result = "";
  839. let pendingAnsi = "";
  840. let visibleSoFar = 0;
  841. let keptWidth = 0;
  842. let keepContiguousPrefix = true;
  843. let overflowed = false;
  844. let exhaustedInput = false;
  845. const hasAnsi = text.includes("\x1b");
  846. const hasTabs = text.includes("\t");
  847. if (!hasAnsi && !hasTabs) {
  848. for (const { segment } of graphemeSegmenter.segment(text)) {
  849. const width = graphemeWidth(segment);
  850. if (keepContiguousPrefix && keptWidth + width <= targetWidth) {
  851. result += segment;
  852. keptWidth += width;
  853. } else {
  854. keepContiguousPrefix = false;
  855. }
  856. visibleSoFar += width;
  857. if (visibleSoFar > maxWidth) {
  858. overflowed = true;
  859. break;
  860. }
  861. }
  862. exhaustedInput = !overflowed;
  863. } else {
  864. let i = 0;
  865. while (i < text.length) {
  866. const ansi = extractAnsiCode(text, i);
  867. if (ansi) {
  868. pendingAnsi += ansi.code;
  869. i += ansi.length;
  870. continue;
  871. }
  872. if (text[i] === "\t") {
  873. if (keepContiguousPrefix && keptWidth + 3 <= targetWidth) {
  874. if (pendingAnsi) {
  875. result += pendingAnsi;
  876. pendingAnsi = "";
  877. }
  878. result += "\t";
  879. keptWidth += 3;
  880. } else {
  881. keepContiguousPrefix = false;
  882. pendingAnsi = "";
  883. }
  884. visibleSoFar += 3;
  885. if (visibleSoFar > maxWidth) {
  886. overflowed = true;
  887. break;
  888. }
  889. i++;
  890. continue;
  891. }
  892. let end = i;
  893. while (end < text.length && text[end] !== "\t") {
  894. const nextAnsi = extractAnsiCode(text, end);
  895. if (nextAnsi) {
  896. break;
  897. }
  898. end++;
  899. }
  900. for (const { segment } of graphemeSegmenter.segment(text.slice(i, end))) {
  901. const width = graphemeWidth(segment);
  902. if (keepContiguousPrefix && keptWidth + width <= targetWidth) {
  903. if (pendingAnsi) {
  904. result += pendingAnsi;
  905. pendingAnsi = "";
  906. }
  907. result += segment;
  908. keptWidth += width;
  909. } else {
  910. keepContiguousPrefix = false;
  911. pendingAnsi = "";
  912. }
  913. visibleSoFar += width;
  914. if (visibleSoFar > maxWidth) {
  915. overflowed = true;
  916. break;
  917. }
  918. }
  919. if (overflowed) {
  920. break;
  921. }
  922. i = end;
  923. }
  924. exhaustedInput = i >= text.length;
  925. }
  926. if (!overflowed && exhaustedInput) {
  927. return pad ? text + " ".repeat(Math.max(0, maxWidth - visibleSoFar)) : text;
  928. }
  929. return finalizeTruncatedResult(result, keptWidth, ellipsis, ellipsisWidth, maxWidth, pad);
  930. }
  931. /**
  932. * Extract a range of visible columns from a line. Handles ANSI codes and wide chars.
  933. * @param strict - If true, exclude wide chars at boundary that would extend past the range
  934. */
  935. export function sliceByColumn(line: string, startCol: number, length: number, strict = false): string {
  936. return sliceWithWidth(line, startCol, length, strict).text;
  937. }
  938. /** Like sliceByColumn but also returns the actual visible width of the result. */
  939. export function sliceWithWidth(
  940. line: string,
  941. startCol: number,
  942. length: number,
  943. strict = false,
  944. ): { text: string; width: number } {
  945. if (length <= 0) return { text: "", width: 0 };
  946. const endCol = startCol + length;
  947. let result = "",
  948. resultWidth = 0,
  949. currentCol = 0,
  950. i = 0,
  951. pendingAnsi = "";
  952. while (i < line.length) {
  953. const ansi = extractAnsiCode(line, i);
  954. if (ansi) {
  955. if (currentCol >= startCol && currentCol < endCol) result += ansi.code;
  956. else if (currentCol < startCol) pendingAnsi += ansi.code;
  957. i += ansi.length;
  958. continue;
  959. }
  960. let textEnd = i;
  961. while (textEnd < line.length && !extractAnsiCode(line, textEnd)) textEnd++;
  962. for (const { segment } of graphemeSegmenter.segment(line.slice(i, textEnd))) {
  963. const w = graphemeWidth(segment);
  964. const inRange = currentCol >= startCol && currentCol < endCol;
  965. const fits = !strict || currentCol + w <= endCol;
  966. if (inRange && fits) {
  967. if (pendingAnsi) {
  968. result += pendingAnsi;
  969. pendingAnsi = "";
  970. }
  971. result += segment;
  972. resultWidth += w;
  973. }
  974. currentCol += w;
  975. if (currentCol >= endCol) break;
  976. }
  977. i = textEnd;
  978. if (currentCol >= endCol) break;
  979. }
  980. return { text: result, width: resultWidth };
  981. }
  982. // Pooled tracker instance for extractSegments (avoids allocation per call)
  983. const pooledStyleTracker = new AnsiCodeTracker();
  984. /**
  985. * Extract "before" and "after" segments from a line in a single pass.
  986. * Used for overlay compositing where we need content before and after the overlay region.
  987. * Preserves styling from before the overlay that should affect content after it.
  988. */
  989. export function extractSegments(
  990. line: string,
  991. beforeEnd: number,
  992. afterStart: number,
  993. afterLen: number,
  994. strictAfter = false,
  995. ): { before: string; beforeWidth: number; after: string; afterWidth: number } {
  996. let before = "",
  997. beforeWidth = 0,
  998. after = "",
  999. afterWidth = 0;
  1000. let currentCol = 0,
  1001. i = 0;
  1002. let pendingAnsiBefore = "";
  1003. let afterStarted = false;
  1004. const afterEnd = afterStart + afterLen;
  1005. // Track styling state so "after" inherits styling from before the overlay
  1006. pooledStyleTracker.clear();
  1007. while (i < line.length) {
  1008. const ansi = extractAnsiCode(line, i);
  1009. if (ansi) {
  1010. // Track all SGR codes to know styling state at afterStart
  1011. pooledStyleTracker.process(ansi.code);
  1012. // Include ANSI codes in their respective segments
  1013. if (currentCol < beforeEnd) {
  1014. pendingAnsiBefore += ansi.code;
  1015. } else if (currentCol >= afterStart && currentCol < afterEnd && afterStarted) {
  1016. // Only include after we've started "after" (styling already prepended)
  1017. after += ansi.code;
  1018. }
  1019. i += ansi.length;
  1020. continue;
  1021. }
  1022. let textEnd = i;
  1023. while (textEnd < line.length && !extractAnsiCode(line, textEnd)) textEnd++;
  1024. for (const { segment } of graphemeSegmenter.segment(line.slice(i, textEnd))) {
  1025. const w = graphemeWidth(segment);
  1026. if (currentCol < beforeEnd) {
  1027. if (pendingAnsiBefore) {
  1028. before += pendingAnsiBefore;
  1029. pendingAnsiBefore = "";
  1030. }
  1031. before += segment;
  1032. beforeWidth += w;
  1033. } else if (currentCol >= afterStart && currentCol < afterEnd) {
  1034. const fits = !strictAfter || currentCol + w <= afterEnd;
  1035. if (fits) {
  1036. // On first "after" grapheme, prepend inherited styling from before overlay
  1037. if (!afterStarted) {
  1038. after += pooledStyleTracker.getActiveCodes();
  1039. afterStarted = true;
  1040. }
  1041. after += segment;
  1042. afterWidth += w;
  1043. }
  1044. }
  1045. currentCol += w;
  1046. // Early exit: done with "before" only, or done with both segments
  1047. if (afterLen <= 0 ? currentCol >= beforeEnd : currentCol >= afterEnd) break;
  1048. }
  1049. i = textEnd;
  1050. if (afterLen <= 0 ? currentCol >= beforeEnd : currentCol >= afterEnd) break;
  1051. }
  1052. return { before, beforeWidth, after, afterWidth };
  1053. }