@xmoon76/dsh-pi-tui 0.5.5 → 0.5.6

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 (48) hide show
  1. package/README.en.md +30 -47
  2. package/README.md +30 -30
  3. package/cordis.patch.yml +77 -7
  4. package/dist/{bootstrap-DLOydLLj.mjs → bootstrap-DQ4YPL-7.mjs} +12416 -7243
  5. package/dist/builtins.mjs +3 -8
  6. package/dist/{application-runtime-CbBO4bY-.mjs → client-bootstrap-Cr1JCaF5.mjs} +3098 -1747
  7. package/dist/{dist-C7QMk0ws.mjs → dist-CIsR7cz4.mjs} +510 -224
  8. package/dist/{extensions-pcFiH7Qe.mjs → extensions-Bp0L37lP.mjs} +527 -249
  9. package/dist/extensions.mjs +1 -1
  10. package/dist/{host-bootstrap-CKdfLkNS.mjs → host-bootstrap-DilsvA6f.mjs} +106 -13
  11. package/dist/host-foundation-probe--5jtvHVe.mjs +413 -0
  12. package/dist/host-runtime.d.mts +10 -6
  13. package/dist/host-runtime.mjs +877 -10
  14. package/dist/index.d.mts +11 -17
  15. package/dist/index.mjs +13328 -6828
  16. package/dist/local-client.mjs +408 -61
  17. package/dist/{local-discovery-CXnLT4GF.mjs → local-discovery-C9VMjc0K.mjs} +10 -6
  18. package/dist/{local-discovery-DVFFpfBG.mjs → local-discovery-CDaQHA_R.mjs} +1 -1
  19. package/dist/local-host.mjs +188 -36
  20. package/dist/{local-transport-C9aonplC.mjs → local-transport-BVwFYq_Y.mjs} +1 -1
  21. package/dist/{context-summary-D9mhxPXL.mjs → pasted-path-range-CMnxuGPx.mjs} +6166 -227
  22. package/dist/{context-summary-Bz0AGXa1.mjs → pasted-path-range-r6qzV_tC.mjs} +5927 -444
  23. package/dist/{pi-tui-remote-contribution-DRk6Tl3J.mjs → pi-tui-remote-contribution-B0EQsP0N.mjs} +27 -20
  24. package/dist/{pi-tui-terminal-progress-contract-XTQKj-WW.mjs → pi-tui-terminal-progress-contract-MLXZ-i3t.mjs} +2 -2
  25. package/dist/pi-tui-web-access-contract-BN8Cc_Ho.mjs +118 -0
  26. package/dist/{runtime-status-0lp9CM0V.mjs → runtime-status-Cj1nFOdS.mjs} +72 -214
  27. package/dist/{session-4keoXjk0.mjs → session-BKGXyh80.mjs} +7487 -2562
  28. package/dist/{session-B2zqv4wr.mjs → session-CPt_U8_f.mjs} +7486 -2560
  29. package/dist/{startup-Ct2UUjUL.mjs → startup-7BYWuvBU.mjs} +121 -6
  30. package/dist/startup.mjs +1 -1
  31. package/dist/{terminal-progress-source-BhufrZ74.mjs → terminal-progress-source-DrqQhtT8.mjs} +305 -45
  32. package/dist/visual-tools.d.mts +2 -2
  33. package/dist/visual-tools.mjs +26 -31
  34. package/dist/web-preferences.d.mts +29 -0
  35. package/dist/web-preferences.mjs +15 -0
  36. package/dist/web-roster-CjqnUXNk.mjs +285 -0
  37. package/generated/dsh-presets/cordis.patch.yml +5 -3
  38. package/generated/dsh-presets/ptc.patch.yml +7 -7
  39. package/generated/dsh-presets/standard.patch.yml +6 -4
  40. package/package.json +182 -168
  41. package/dist/client-bootstrap-DwSFzcTW.mjs +0 -872
  42. package/dist/custom-items-CKrOBCox.mjs +0 -655
  43. package/dist/dispose-cause-BzcXo4hu.mjs +0 -123
  44. package/dist/host-foundation-probe-CYHsbAw6.mjs +0 -143
  45. package/dist/host-prerequisites-9JBTtVNu.mjs +0 -36
  46. package/dist/runtime-Bh5OsftD.mjs +0 -6798
  47. package/dist/runtime-C5ROZqFj.mjs +0 -2
  48. package/dist/terminal-progress-source-CsBinCJ_.mjs +0 -965
@@ -13,6 +13,7 @@ import { homedir as homedir$1 } from "os";
13
13
  import { basename as basename$1, dirname as dirname$1, join as join$1 } from "path";
14
14
  import { eastAsianWidth } from "get-east-asian-width";
15
15
  import { performance as performance$1 } from "node:perf_hooks";
16
+ import markedCjkFriendly from "marked-cjk-friendly";
16
17
  import { EventEmitter } from "events";
17
18
  //#region src/domain/footer/layout.ts
18
19
  /** The per-id default `Hide in TSP` value (Owner-frozen): the three items
@@ -656,55 +657,65 @@ function executableCommandItemIds(trustedCommands, authorizedIds, renderedLayout
656
657
  }
657
658
  //#endregion
658
659
  //#region packages/pi-tui/dist/index.mjs
659
- function fuzzyMatch(query, text) {
660
- const queryLower = query.toLowerCase();
661
- const textLower = text.toLowerCase();
662
- const matchQuery = (normalizedQuery) => {
663
- if (normalizedQuery.length === 0) return {
664
- matches: true,
665
- score: 0
666
- };
667
- if (normalizedQuery.length > textLower.length) return {
668
- matches: false,
669
- score: 0
670
- };
671
- let queryIndex = 0;
672
- let score = 0;
673
- let lastMatchIndex = -1;
674
- let consecutiveMatches = 0;
675
- while (queryIndex < normalizedQuery.length) {
676
- const i = textLower.indexOf(normalizedQuery[queryIndex], lastMatchIndex + 1);
677
- if (i === -1) break;
678
- const isWordBoundary = i === 0 || /[\s\-_./:]/.test(textLower[i - 1]);
679
- if (lastMatchIndex === i - 1) {
680
- consecutiveMatches++;
681
- score -= consecutiveMatches * 5;
682
- } else {
683
- consecutiveMatches = 0;
684
- if (lastMatchIndex >= 0) score += (i - lastMatchIndex - 1) * 2;
685
- }
686
- if (isWordBoundary) score -= 10;
687
- score += i * .1;
688
- lastMatchIndex = i;
689
- queryIndex++;
660
+ function scorePositions(textLower, positions) {
661
+ let score = 0;
662
+ let lastMatchIndex = -1;
663
+ let consecutiveMatches = 0;
664
+ for (const i of positions) {
665
+ if (lastMatchIndex === i - 1) {
666
+ consecutiveMatches++;
667
+ score -= consecutiveMatches * 5;
668
+ } else {
669
+ consecutiveMatches = 0;
670
+ if (lastMatchIndex >= 0) score += (i - lastMatchIndex - 1) * 2;
690
671
  }
691
- if (queryIndex < normalizedQuery.length) return {
672
+ if (i === 0 || /[\s\-_./:]/.test(textLower[i - 1])) score -= 10;
673
+ score += i * .1;
674
+ lastMatchIndex = i;
675
+ }
676
+ return score;
677
+ }
678
+ function matchQuery(normalizedQuery, textLower) {
679
+ if (normalizedQuery.length === 0) return {
680
+ matches: true,
681
+ score: 0
682
+ };
683
+ if (normalizedQuery.length > textLower.length) return {
684
+ matches: false,
685
+ score: 0
686
+ };
687
+ const positions = [];
688
+ let lastMatchIndex = -1;
689
+ for (let queryIndex = 0; queryIndex < normalizedQuery.length; queryIndex++) {
690
+ const i = textLower.indexOf(normalizedQuery[queryIndex], lastMatchIndex + 1);
691
+ if (i === -1) return {
692
692
  matches: false,
693
693
  score: 0
694
694
  };
695
- if (normalizedQuery === textLower) score -= 100;
696
- return {
697
- matches: true,
698
- score
699
- };
695
+ positions.push(i);
696
+ lastMatchIndex = i;
697
+ }
698
+ let score = scorePositions(textLower, positions);
699
+ for (let start = textLower.indexOf(normalizedQuery); start !== -1; start = textLower.indexOf(normalizedQuery, start + 1)) {
700
+ for (let k = 0; k < positions.length; k++) positions[k] = start + k;
701
+ score = Math.min(score, scorePositions(textLower, positions));
702
+ }
703
+ if (normalizedQuery === textLower) score -= 100;
704
+ return {
705
+ matches: true,
706
+ score
700
707
  };
701
- const primaryMatch = matchQuery(queryLower);
708
+ }
709
+ function fuzzyMatch(query, text) {
710
+ const queryLower = query.toLowerCase();
711
+ const textLower = text.toLowerCase();
712
+ const primaryMatch = matchQuery(queryLower, textLower);
702
713
  if (primaryMatch.matches) return primaryMatch;
703
714
  const alphaNumericMatch = queryLower.match(/^(?<letters>[a-z]+)(?<digits>[0-9]+)$/);
704
715
  const numericAlphaMatch = queryLower.match(/^(?<digits>[0-9]+)(?<letters>[a-z]+)$/);
705
716
  const swappedQuery = alphaNumericMatch ? `${alphaNumericMatch.groups?.digits ?? ""}${alphaNumericMatch.groups?.letters ?? ""}` : numericAlphaMatch ? `${numericAlphaMatch.groups?.letters ?? ""}${numericAlphaMatch.groups?.digits ?? ""}` : "";
706
717
  if (!swappedQuery) return primaryMatch;
707
- const swappedMatch = matchQuery(swappedQuery);
718
+ const swappedMatch = matchQuery(swappedQuery, textLower);
708
719
  if (!swappedMatch.matches) return primaryMatch;
709
720
  return {
710
721
  matches: true,
@@ -951,6 +962,44 @@ function stripTerminalSequences(str) {
951
962
  }
952
963
  return result;
953
964
  }
965
+ function extractAnsiCodes(str) {
966
+ let result = "";
967
+ let i = str.indexOf("\x1B");
968
+ while (i !== -1) {
969
+ const length = ansiCodeLength(str, i);
970
+ if (length > 0) {
971
+ result += str.substring(i, i + length);
972
+ i += length;
973
+ } else i++;
974
+ i = str.indexOf("\x1B", i);
975
+ }
976
+ return result;
977
+ }
978
+ const WHITESPACE_REGEX = /\s/;
979
+ /**
980
+ * Whether a token's visible text is only whitespace. Codes closing a styled word attach to the following space,
981
+ * e.g. "\x1b[22m ", so they are skipped. Stops at the first visible non-whitespace text without allocating a
982
+ * stripped copy, because styled words reach this check on every wrap.
983
+ */
984
+ function isWhitespaceToken(token) {
985
+ let i = 0;
986
+ while (i < token.length) {
987
+ const code = token.charCodeAt(i);
988
+ if (code === 27) {
989
+ const length = ansiCodeLength(token, i);
990
+ if (length === 0) return false;
991
+ i += length;
992
+ } else if (code === 32 || code >= 9 && code <= 13) i++;
993
+ else if (code < 128 || !WHITESPACE_REGEX.test(token[i])) return false;
994
+ else i++;
995
+ }
996
+ return true;
997
+ }
998
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]+/g;
999
+ /** Replace each run of C0 and C1 control characters (ESC, BEL, newlines, ...) with one space. */
1000
+ function replaceControlCharacters(str) {
1001
+ return str.replace(CONTROL_CHARACTERS, " ");
1002
+ }
954
1003
  /** Return the terminal-cell range occupied by the grapheme at a visible column. */
955
1004
  function getGraphemeCellRange(line, column) {
956
1005
  let currentCol = 0;
@@ -1433,9 +1482,10 @@ function wrapSingleLine(line, width) {
1433
1482
  let currentVisibleLength = 0;
1434
1483
  for (const token of tokens) {
1435
1484
  const tokenVisibleLength = visibleWidth(token);
1436
- const isWhitespace = token.trim() === "";
1485
+ const isWhitespace = isWhitespaceToken(token);
1437
1486
  if (tokenVisibleLength > width && !isWhitespace) {
1438
1487
  if (currentLine) {
1488
+ currentLine = currentLine.trimEnd();
1439
1489
  const lineEndReset = tracker.getLineEndReset();
1440
1490
  if (lineEndReset) currentLine += lineEndReset;
1441
1491
  wrapped.push(currentLine);
@@ -1448,19 +1498,25 @@ function wrapSingleLine(line, width) {
1448
1498
  currentVisibleLength = visibleWidth(currentLine);
1449
1499
  continue;
1450
1500
  }
1451
- if (currentVisibleLength + tokenVisibleLength > width && currentVisibleLength > 0) {
1501
+ const totalNeeded = currentVisibleLength + tokenVisibleLength;
1502
+ if (totalNeeded > width && currentVisibleLength > 0) {
1452
1503
  let lineToWrap = currentLine.trimEnd();
1504
+ if (isWhitespace) {
1505
+ lineToWrap += extractAnsiCodes(token);
1506
+ updateTrackerFromText(token, tracker);
1507
+ }
1453
1508
  const lineEndReset = tracker.getLineEndReset();
1454
1509
  if (lineEndReset) lineToWrap += lineEndReset;
1455
1510
  wrapped.push(lineToWrap);
1456
1511
  if (isWhitespace) {
1457
1512
  currentLine = tracker.getActiveCodes();
1458
1513
  currentVisibleLength = 0;
1459
- } else {
1460
- currentLine = tracker.getActiveCodes() + token;
1461
- currentVisibleLength = tokenVisibleLength;
1514
+ continue;
1462
1515
  }
1463
- } else {
1516
+ currentLine = tracker.getActiveCodes() + token;
1517
+ currentVisibleLength = tokenVisibleLength;
1518
+ } else if (isWhitespace && totalNeeded > width && token.includes("\x1B")) currentLine += extractAnsiCodes(token);
1519
+ else {
1464
1520
  currentLine += token;
1465
1521
  currentVisibleLength += tokenVisibleLength;
1466
1522
  }
@@ -1723,7 +1779,7 @@ function extractSegments(line, beforeEnd, afterStart, afterLen, strictAfter = fa
1723
1779
  if (ansi) {
1724
1780
  pooledStyleTracker.process(ansi.code);
1725
1781
  if (currentCol < beforeEnd) pendingAnsiBefore += ansi.code;
1726
- else if (currentCol >= afterStart && currentCol < afterEnd && afterStarted) after += ansi.code;
1782
+ else if (currentCol >= afterStart && currentCol < afterEnd && (afterStarted || ansi.code.startsWith("\x1B_"))) after += ansi.code;
1727
1783
  i += ansi.length;
1728
1784
  continue;
1729
1785
  }
@@ -1784,14 +1840,12 @@ function escapeRegex(value) {
1784
1840
  }
1785
1841
  function buildFdPathQuery(query) {
1786
1842
  const normalized = toDisplayPath(query);
1787
- if (!normalized.includes("/")) return normalized;
1843
+ if (!normalized.includes("/")) return escapeRegex(normalized);
1788
1844
  const hasTrailingSeparator = normalized.endsWith("/");
1789
1845
  const trimmed = normalized.replace(/^\/+|\/+$/g, "");
1790
1846
  if (!trimmed) return normalized;
1791
1847
  const separatorPattern = "[\\\\/]";
1792
- const segments = trimmed.split("/").filter(Boolean).map((segment) => escapeRegex(segment));
1793
- if (segments.length === 0) return normalized;
1794
- let pattern = segments.join(separatorPattern);
1848
+ let pattern = trimmed.split("/").filter(Boolean).map((segment) => escapeRegex(segment)).join(separatorPattern);
1795
1849
  if (hasTrailingSeparator) pattern += separatorPattern;
1796
1850
  return pattern;
1797
1851
  }
@@ -2419,6 +2473,13 @@ const SYMBOL_KEYS = /* @__PURE__ */ new Set([
2419
2473
  ">",
2420
2474
  "?"
2421
2475
  ]);
2476
+ const SHIFTED_SYMBOL_KEYS = /* @__PURE__ */ new Set("~!@#$%^&*()_+|{}:<>?");
2477
+ const MODIFIER_NAMES = [
2478
+ "shift",
2479
+ "alt",
2480
+ "ctrl",
2481
+ "super"
2482
+ ];
2422
2483
  const MODIFIERS = {
2423
2484
  shift: 1,
2424
2485
  alt: 2,
@@ -2446,8 +2507,22 @@ const FUNCTIONAL_CODEPOINTS = {
2446
2507
  pageUp: -12,
2447
2508
  pageDown: -13,
2448
2509
  home: -14,
2449
- end: -15
2510
+ end: -15,
2511
+ f1: -21,
2512
+ f2: -22,
2513
+ f3: -23,
2514
+ f4: -24,
2515
+ f5: -25,
2516
+ f6: -26,
2517
+ f7: -27,
2518
+ f8: -28,
2519
+ f9: -29,
2520
+ f10: -30,
2521
+ f11: -31,
2522
+ f12: -32
2450
2523
  };
2524
+ const KITTY_FUNCTIONAL_PUA_START = 57344;
2525
+ const KITTY_FUNCTIONAL_PUA_END = 63743;
2451
2526
  const KITTY_FUNCTIONAL_KEY_EQUIVALENTS = /* @__PURE__ */ new Map([
2452
2527
  [57399, 48],
2453
2528
  [57400, 49],
@@ -2484,6 +2559,15 @@ function normalizeShiftedLetterIdentityCodepoint(codepoint, modifier) {
2484
2559
  if ((modifier & -193 & MODIFIERS.shift) !== 0 && codepoint >= 65 && codepoint <= 90) return codepoint + 32;
2485
2560
  return codepoint;
2486
2561
  }
2562
+ function getLogicalShiftedSymbolCandidate(codepoint, modifier, allowedSymbols) {
2563
+ if (codepoint === void 0 || (modifier & MODIFIERS.shift) === 0) return void 0;
2564
+ const normalizedCodepoint = normalizeKittyFunctionalCodepoint(codepoint);
2565
+ if (!allowedSymbols.has(String.fromCharCode(normalizedCodepoint))) return void 0;
2566
+ return {
2567
+ codepoint: normalizedCodepoint,
2568
+ modifier: modifier & ~MODIFIERS.shift
2569
+ };
2570
+ }
2487
2571
  const LEGACY_KEY_SEQUENCES = {
2488
2572
  up: ["\x1B[A", "\x1BOA"],
2489
2573
  down: ["\x1B[B", "\x1BOB"],
@@ -2627,7 +2711,7 @@ const matchesLegacyModifierSequence = (data, key, modifier) => {
2627
2711
  if (modifier === MODIFIERS.ctrl) return matchesLegacySequence(data, LEGACY_CTRL_SEQUENCES[key]);
2628
2712
  return false;
2629
2713
  };
2630
- const KITTY_EVENT_SEQUENCE = /^\x1b\[\d+(?::\d*)?(?::\d+)?;\d+:(?<event>[23])(?:u|~|[ABCDHF])$/u;
2714
+ const KITTY_EVENT_SEQUENCE = /^\x1b\[\d+(?::\d*)?(?::\d+)?;\d+:(?<event>[23])(?:u|~|[ABCDHFPQS])$/u;
2631
2715
  function kittyEventType(data) {
2632
2716
  const match = KITTY_EVENT_SEQUENCE.exec(data);
2633
2717
  if (match === null) return void 0;
@@ -2696,7 +2780,19 @@ function parseKittySequence(data) {
2696
2780
  5: FUNCTIONAL_CODEPOINTS.pageUp,
2697
2781
  6: FUNCTIONAL_CODEPOINTS.pageDown,
2698
2782
  7: FUNCTIONAL_CODEPOINTS.home,
2699
- 8: FUNCTIONAL_CODEPOINTS.end
2783
+ 8: FUNCTIONAL_CODEPOINTS.end,
2784
+ 11: FUNCTIONAL_CODEPOINTS.f1,
2785
+ 12: FUNCTIONAL_CODEPOINTS.f2,
2786
+ 13: FUNCTIONAL_CODEPOINTS.f3,
2787
+ 14: FUNCTIONAL_CODEPOINTS.f4,
2788
+ 15: FUNCTIONAL_CODEPOINTS.f5,
2789
+ 17: FUNCTIONAL_CODEPOINTS.f6,
2790
+ 18: FUNCTIONAL_CODEPOINTS.f7,
2791
+ 19: FUNCTIONAL_CODEPOINTS.f8,
2792
+ 20: FUNCTIONAL_CODEPOINTS.f9,
2793
+ 21: FUNCTIONAL_CODEPOINTS.f10,
2794
+ 23: FUNCTIONAL_CODEPOINTS.f11,
2795
+ 24: FUNCTIONAL_CODEPOINTS.f12
2700
2796
  }[keyNum];
2701
2797
  if (codepoint !== void 0) return {
2702
2798
  codepoint,
@@ -2714,14 +2810,33 @@ function parseKittySequence(data) {
2714
2810
  eventType
2715
2811
  };
2716
2812
  }
2813
+ const fKeyMatch = data.match(/^\x1b\[(?:1;(\d+)(?::(\d+))?)?([PQS])$/);
2814
+ if (fKeyMatch) {
2815
+ const modValue = fKeyMatch[1] ? parseInt(fKeyMatch[1], 10) : 1;
2816
+ const eventType = parseEventType(fKeyMatch[2]);
2817
+ return {
2818
+ codepoint: {
2819
+ P: FUNCTIONAL_CODEPOINTS.f1,
2820
+ Q: FUNCTIONAL_CODEPOINTS.f2,
2821
+ S: FUNCTIONAL_CODEPOINTS.f4
2822
+ }[fKeyMatch[3]],
2823
+ modifier: modValue - 1,
2824
+ eventType
2825
+ };
2826
+ }
2717
2827
  return null;
2718
2828
  }
2719
2829
  function matchesKittySequence(data, expectedCodepoint, expectedModifier) {
2720
2830
  const parsed = parseKittySequence(data);
2721
2831
  if (!parsed) return false;
2722
- if ((parsed.modifier & -193) !== (expectedModifier & -193)) return false;
2832
+ const actualMod = parsed.modifier & -193;
2833
+ const expectedMod = expectedModifier & -193;
2723
2834
  const normalizedCodepoint = normalizeShiftedLetterIdentityCodepoint(normalizeKittyFunctionalCodepoint(parsed.codepoint), parsed.modifier);
2724
- if (normalizedCodepoint === normalizeShiftedLetterIdentityCodepoint(normalizeKittyFunctionalCodepoint(expectedCodepoint), expectedModifier)) return true;
2835
+ const normalizedExpectedCodepoint = normalizeShiftedLetterIdentityCodepoint(normalizeKittyFunctionalCodepoint(expectedCodepoint), expectedModifier);
2836
+ if (actualMod === expectedMod && normalizedCodepoint === normalizedExpectedCodepoint) return true;
2837
+ const logicalShiftedSymbol = getLogicalShiftedSymbolCandidate(parsed.shiftedKey, actualMod, SYMBOL_KEYS);
2838
+ if (logicalShiftedSymbol && (logicalShiftedSymbol.modifier & -193) === expectedMod && logicalShiftedSymbol.codepoint === normalizeKittyFunctionalCodepoint(expectedCodepoint)) return true;
2839
+ if (actualMod !== expectedMod) return false;
2725
2840
  if (parsed.baseLayoutKey !== void 0 && parsed.baseLayoutKey === expectedCodepoint) {
2726
2841
  const cp = normalizedCodepoint;
2727
2842
  const isLatinLetter = cp >= 97 && cp <= 122;
@@ -2786,10 +2901,11 @@ function isDigitKey(key) {
2786
2901
  return key >= "0" && key <= "9";
2787
2902
  }
2788
2903
  function matchesPrintableModifyOtherKeys(data, expectedKeycode, expectedModifier) {
2789
- if (expectedModifier === 0) return false;
2790
2904
  const parsed = parseModifyOtherKeysSequence(data);
2791
- if (!parsed || parsed.modifier !== expectedModifier) return false;
2792
- return normalizeShiftedLetterIdentityCodepoint(parsed.codepoint, parsed.modifier) === normalizeShiftedLetterIdentityCodepoint(expectedKeycode, expectedModifier);
2905
+ if (!parsed) return false;
2906
+ if (parsed.modifier === expectedModifier && normalizeShiftedLetterIdentityCodepoint(parsed.codepoint, parsed.modifier) === normalizeShiftedLetterIdentityCodepoint(expectedKeycode, expectedModifier)) return true;
2907
+ const logicalShiftedSymbol = getLogicalShiftedSymbolCandidate(parsed.codepoint, parsed.modifier, SHIFTED_SYMBOL_KEYS);
2908
+ return logicalShiftedSymbol?.modifier === expectedModifier && logicalShiftedSymbol.codepoint === expectedKeycode;
2793
2909
  }
2794
2910
  function formatKeyNameWithModifiers(keyName, modifier) {
2795
2911
  const mods = [];
@@ -2802,15 +2918,22 @@ function formatKeyNameWithModifiers(keyName, modifier) {
2802
2918
  return mods.length > 0 ? `${mods.join("+")}+${keyName}` : keyName;
2803
2919
  }
2804
2920
  function parseKeyId(keyId) {
2805
- const parts = keyId.toLowerCase().split("+");
2806
- const key = parts[parts.length - 1];
2807
- if (!key) return null;
2921
+ let key = keyId.toLowerCase();
2922
+ const modifiers = /* @__PURE__ */ new Set();
2923
+ while (true) {
2924
+ const modifier = MODIFIER_NAMES.find((name) => key.startsWith(`${name}+`));
2925
+ if (!modifier) break;
2926
+ if (modifiers.has(modifier)) return null;
2927
+ modifiers.add(modifier);
2928
+ key = key.slice(modifier.length + 1);
2929
+ }
2930
+ if (!key || key.includes("+") && key !== "+") return null;
2808
2931
  return {
2809
2932
  key,
2810
- ctrl: parts.includes("ctrl"),
2811
- shift: parts.includes("shift"),
2812
- alt: parts.includes("alt"),
2813
- super: parts.includes("super")
2933
+ ctrl: modifiers.has("ctrl"),
2934
+ shift: modifiers.has("shift"),
2935
+ alt: modifiers.has("alt"),
2936
+ super: modifiers.has("super")
2814
2937
  };
2815
2938
  }
2816
2939
  /**
@@ -2942,9 +3065,11 @@ function matchesKey(data, keyId) {
2942
3065
  case "f9":
2943
3066
  case "f10":
2944
3067
  case "f11":
2945
- case "f12":
2946
- if (modifier !== 0) return false;
2947
- return matchesLegacySequence(data, LEGACY_KEY_SEQUENCES[key]);
3068
+ case "f12": {
3069
+ const functionKey = key;
3070
+ if (modifier === 0 && matchesLegacySequence(data, LEGACY_KEY_SEQUENCES[functionKey])) return true;
3071
+ return matchesKittySequence(data, FUNCTIONAL_CODEPOINTS[functionKey], modifier);
3072
+ }
2948
3073
  }
2949
3074
  if (key.length === 1 && (key >= "a" && key <= "z" || isDigitKey(key) || SYMBOL_KEYS.has(key))) {
2950
3075
  const codepoint = key.charCodeAt(0);
@@ -2967,7 +3092,7 @@ function matchesKey(data, keyId) {
2967
3092
  return matchesKittySequence(data, codepoint, MODIFIERS.shift) || matchesPrintableModifyOtherKeys(data, codepoint, MODIFIERS.shift);
2968
3093
  }
2969
3094
  if (modifier !== 0) return matchesKittySequence(data, codepoint, modifier) || matchesPrintableModifyOtherKeys(data, codepoint, modifier);
2970
- return data === key || matchesKittySequence(data, codepoint, 0);
3095
+ return data === key || matchesKittySequence(data, codepoint, 0) || matchesPrintableModifyOtherKeys(data, codepoint, 0);
2971
3096
  }
2972
3097
  return false;
2973
3098
  }
@@ -2995,6 +3120,7 @@ function formatParsedKey(codepoint, modifier, baseLayoutKey) {
2995
3120
  else if (effectiveCodepoint === FUNCTIONAL_CODEPOINTS.end) keyName = "end";
2996
3121
  else if (effectiveCodepoint === FUNCTIONAL_CODEPOINTS.pageUp) keyName = "pageUp";
2997
3122
  else if (effectiveCodepoint === FUNCTIONAL_CODEPOINTS.pageDown) keyName = "pageDown";
3123
+ else if (effectiveCodepoint <= FUNCTIONAL_CODEPOINTS.f1 && effectiveCodepoint >= FUNCTIONAL_CODEPOINTS.f12) keyName = `f${FUNCTIONAL_CODEPOINTS.f1 - effectiveCodepoint + 1}`;
2998
3124
  else if (effectiveCodepoint === ARROW_CODEPOINTS.up) keyName = "up";
2999
3125
  else if (effectiveCodepoint === ARROW_CODEPOINTS.down) keyName = "down";
3000
3126
  else if (effectiveCodepoint === ARROW_CODEPOINTS.left) keyName = "left";
@@ -3007,9 +3133,15 @@ function formatParsedKey(codepoint, modifier, baseLayoutKey) {
3007
3133
  }
3008
3134
  function parseKey(data) {
3009
3135
  const kitty = parseKittySequence(data);
3010
- if (kitty) return formatParsedKey(kitty.codepoint, kitty.modifier, kitty.baseLayoutKey);
3136
+ if (kitty) {
3137
+ const logicalShiftedSymbol = getLogicalShiftedSymbolCandidate(kitty.shiftedKey, kitty.modifier, SYMBOL_KEYS);
3138
+ return formatParsedKey(logicalShiftedSymbol?.codepoint ?? kitty.codepoint, logicalShiftedSymbol?.modifier ?? kitty.modifier, kitty.baseLayoutKey);
3139
+ }
3011
3140
  const modifyOtherKeys = parseModifyOtherKeysSequence(data);
3012
- if (modifyOtherKeys) return formatParsedKey(modifyOtherKeys.codepoint, modifyOtherKeys.modifier);
3141
+ if (modifyOtherKeys) {
3142
+ const logicalShiftedSymbol = getLogicalShiftedSymbolCandidate(modifyOtherKeys.codepoint, modifyOtherKeys.modifier, SHIFTED_SYMBOL_KEYS);
3143
+ return formatParsedKey(logicalShiftedSymbol?.codepoint ?? modifyOtherKeys.codepoint, logicalShiftedSymbol?.modifier ?? modifyOtherKeys.modifier);
3144
+ }
3013
3145
  if (_kittyProtocolActive) {
3014
3146
  if (data === "\x1B\r" || data === "\n") return "shift+enter";
3015
3147
  }
@@ -3086,6 +3218,7 @@ function decodeKittyPrintable(data) {
3086
3218
  if (modifier & MODIFIERS.shift && typeof shiftedKey === "number") effectiveCodepoint = shiftedKey;
3087
3219
  effectiveCodepoint = normalizeKittyFunctionalCodepoint(effectiveCodepoint);
3088
3220
  if (!Number.isFinite(effectiveCodepoint) || effectiveCodepoint < 32) return void 0;
3221
+ if (effectiveCodepoint >= KITTY_FUNCTIONAL_PUA_START && effectiveCodepoint <= KITTY_FUNCTIONAL_PUA_END) return;
3089
3222
  try {
3090
3223
  return String.fromCodePoint(effectiveCodepoint);
3091
3224
  } catch {
@@ -3217,10 +3350,20 @@ function detectCapabilitiesFromEnvironment(tmuxForwardsHyperlink) {
3217
3350
  hyperlinks: false
3218
3351
  };
3219
3352
  if (termProgram === "herdr") return {
3220
- images: null,
3353
+ images: "kitty",
3221
3354
  trueColor: hasTrueColorHint,
3222
3355
  hyperlinks: true
3223
3356
  };
3357
+ if (termProgram === "rex") return {
3358
+ images: "kitty",
3359
+ trueColor: true,
3360
+ hyperlinks: true
3361
+ };
3362
+ if (termProgram === "orca" && process.env.ORCA_IMAGE_PROTOCOL === "kitty") return {
3363
+ images: "kitty",
3364
+ trueColor: true,
3365
+ hyperlinks: true
3366
+ };
3224
3367
  if (process.env.KITTY_WINDOW_ID || termProgram === "kitty" || termProgram === "tern") return {
3225
3368
  images: "kitty",
3226
3369
  trueColor: true,
@@ -3465,8 +3608,10 @@ function encodeITerm2(base64Data, options = {}) {
3465
3608
  }
3466
3609
  const kittyImageMetadata = /* @__PURE__ */ new Map();
3467
3610
  let kittyTransmissionGeneration = 0;
3611
+ let maxKittyImageRows = 0;
3468
3612
  function registerKittyImageMetadata(metadata) {
3469
3613
  kittyTransmissionGeneration += 1;
3614
+ maxKittyImageRows = Math.max(maxKittyImageRows, metadata.rows);
3470
3615
  kittyImageMetadata.delete(metadata.imageId);
3471
3616
  kittyImageMetadata.set(metadata.imageId, {
3472
3617
  ...metadata,
@@ -3477,6 +3622,10 @@ function registerKittyImageMetadata(metadata) {
3477
3622
  if (oldestImageId !== void 0) kittyImageMetadata.delete(oldestImageId);
3478
3623
  }
3479
3624
  }
3625
+ /** Return the row height of the tallest Kitty image registered so far. */
3626
+ function getMaxKittyImageRows() {
3627
+ return maxKittyImageRows;
3628
+ }
3480
3629
  function getRegisteredKittyImageMetadataFromControls(controls) {
3481
3630
  const imageId = /(?:^|,)i=(\d+)(?:,|$)/.exec(controls)?.[1];
3482
3631
  return imageId === void 0 ? void 0 : kittyImageMetadata.get(Number.parseInt(imageId, 10));
@@ -3893,6 +4042,14 @@ function isFocusable(component) {
3893
4042
  * TUI finds and strips this marker, then positions the hardware cursor there.
3894
4043
  */
3895
4044
  const CURSOR_MARKER = "\x1B_pi:c\x07";
4045
+ /** Fake cursor markers - zero-width APC sequences around the text drawn as the cursor. See resolveFakeCursors(). */
4046
+ const FAKE_CURSOR_START = "\x1B_pi:fc\x07";
4047
+ const FAKE_CURSOR_END = "\x1B_pi:/fc\x07";
4048
+ const FOCUSED_FAKE_CURSOR = /(\x1b_pi:c\x07)\x1b_pi:fc\x07(.*?)(?:\x1b_pi:\/fc\x07|$)/s;
4049
+ /** Wrap text in fake cursor markers. */
4050
+ function renderFakeCursor(text) {
4051
+ return `${FAKE_CURSOR_START}${text}${FAKE_CURSOR_END}`;
4052
+ }
3896
4053
  /** Parse a SizeValue into absolute value given a reference size */
3897
4054
  function parseSizeValue(value, referenceSize) {
3898
4055
  if (value === void 0) return void 0;
@@ -4272,6 +4429,24 @@ var TuiBase = class TuiBase extends Container {
4272
4429
  afterTerminalStart() {}
4273
4430
  beforeTerminalStop(_options) {}
4274
4431
  afterTerminalStop(_options) {}
4432
+ /** Mode resets written before the terminal's own resets when the process exits without stop(). */
4433
+ getExitRestorePrefix() {
4434
+ return `${this.terminalColorSchemeNotificationsEnabled ? "\x1B[?2031l" : ""}\x1b[?25h`;
4435
+ }
4436
+ /** Mode resets written after the terminal's own resets when the process exits without stop(). */
4437
+ getExitRestoreSuffix() {
4438
+ return "";
4439
+ }
4440
+ /**
4441
+ * Last-resort restore for exit paths that skip stop(), e.g. a direct process.exit() (#11170).
4442
+ * Hard kills and native aborts run no JavaScript and cannot be covered.
4443
+ */
4444
+ exitRestoreHandler = () => {
4445
+ if (this.stopped) return;
4446
+ try {
4447
+ this.terminal.restoreOnExit?.(this.getExitRestorePrefix(), this.getExitRestoreSuffix());
4448
+ } catch {}
4449
+ };
4275
4450
  get fullRedraws() {
4276
4451
  return this.fullRedrawCount;
4277
4452
  }
@@ -4611,6 +4786,8 @@ var TuiBase = class TuiBase extends Container {
4611
4786
  }
4612
4787
  start() {
4613
4788
  this.stopped = false;
4789
+ process.off("exit", this.exitRestoreHandler);
4790
+ process.on("exit", this.exitRestoreHandler);
4614
4791
  this.beforeTerminalStart();
4615
4792
  this.terminal.start((data) => this.handleTerminalInput(data), () => this.requestRender());
4616
4793
  this.terminalStarted = true;
@@ -4646,6 +4823,7 @@ var TuiBase = class TuiBase extends Container {
4646
4823
  }
4647
4824
  stop(options = {}) {
4648
4825
  this.stopped = true;
4826
+ process.off("exit", this.exitRestoreHandler);
4649
4827
  this.terminalStarted = false;
4650
4828
  this.cancelRenderTimer();
4651
4829
  this.settleBackgroundProbe(void 0);
@@ -4941,7 +5119,7 @@ var TuiBase = class TuiBase extends Container {
4941
5119
  for (const entry of visibleEntries) {
4942
5120
  const { component, options } = entry;
4943
5121
  const { width, maxHeight } = this.resolveOverlayLayout(options, 0, termWidth, termHeight);
4944
- let overlayLines = component.render(width);
5122
+ let overlayLines = this.resolveFakeCursors(component.render(width));
4945
5123
  if (maxHeight !== void 0 && overlayLines.length > maxHeight) overlayLines = overlayLines.slice(0, maxHeight);
4946
5124
  const { row, col } = this.resolveOverlayLayout(options, overlayLines.length, termWidth, termHeight);
4947
5125
  entry.bounds = {
@@ -5038,6 +5216,17 @@ var TuiBase = class TuiBase extends Container {
5038
5216
  return null;
5039
5217
  }
5040
5218
  /**
5219
+ * Resolve fake cursor markers to reverse video. When the hardware cursor is shown, a fake cursor
5220
+ * directly after CURSOR_MARKER is dropped because the terminal cursor is drawn there. Fake cursors
5221
+ * of components without focus have no CURSOR_MARKER and stay visible.
5222
+ */
5223
+ resolveFakeCursors(lines) {
5224
+ return lines.map((line) => {
5225
+ if (!line.includes("\x1B_pi:fc\x07")) return line;
5226
+ return (this.showHardwareCursor ? line.replace(FOCUSED_FAKE_CURSOR, "$1$2") : line).replaceAll(FAKE_CURSOR_START, "\x1B[7m").replaceAll(FAKE_CURSOR_END, "\x1B[27m");
5227
+ });
5228
+ }
5229
+ /**
5041
5230
  * Query the terminal's theme colors: the default foreground (OSC 10), the default background
5042
5231
  * (OSC 11), and ANSI colors 0-15 (OSC 4), followed by a DA1 request that marks the end of the
5043
5232
  * replies. Resolves when the DA1 reply or all color replies arrive, or when the timeout expires.
@@ -5395,6 +5584,18 @@ function getKeybindings() {
5395
5584
  return globalKeybindings;
5396
5585
  }
5397
5586
  /**
5587
+ * Returns the selection index after a `tui.select.pageUp` or `tui.select.pageDown` key, moved by `pageSize` and
5588
+ * clamped to `0..itemCount - 1`. Returns undefined when `data` is not a selection page key, and 0 for a page key on
5589
+ * an empty list, so callers must still check that the list has items before selecting.
5590
+ */
5591
+ function getSelectPageIndex(keybindings, data, selectedIndex, itemCount, pageSize) {
5592
+ let direction;
5593
+ if (keybindings.matches(data, "tui.select.pageUp")) direction = -1;
5594
+ else if (keybindings.matches(data, "tui.select.pageDown")) direction = 1;
5595
+ else return void 0;
5596
+ return Math.max(0, Math.min(itemCount - 1, selectedIndex + direction * pageSize));
5597
+ }
5598
+ /**
5398
5599
  * Text component - displays multi-line text with word wrapping
5399
5600
  */
5400
5601
  var Text = class {
@@ -5412,6 +5613,7 @@ var Text = class {
5412
5613
  this.customBgFn = customBgFn;
5413
5614
  }
5414
5615
  setText(text) {
5616
+ if (text === this.text) return;
5415
5617
  this.text = text;
5416
5618
  this.cachedText = void 0;
5417
5619
  this.cachedWidth = void 0;
@@ -5616,6 +5818,7 @@ const MIN_DESCRIPTION_WIDTH = 10;
5616
5818
  const normalizeToSingleLine = (text) => text.replace(/[\r\n]+/g, " ").trim();
5617
5819
  const clamp = (value, min, max) => Math.max(min, Math.min(value, max));
5618
5820
  var SelectList = class {
5821
+ capturesViewportInput = true;
5619
5822
  items = [];
5620
5823
  filteredItems = [];
5621
5824
  selectedIndex = 0;
@@ -5716,12 +5919,17 @@ var SelectList = class {
5716
5919
  }
5717
5920
  handleInput(keyData) {
5718
5921
  const kb = getKeybindings();
5922
+ const pageIndex = getSelectPageIndex(kb, keyData, this.selectedIndex, this.filteredItems.length, this.maxVisible);
5719
5923
  if (kb.matches(keyData, "tui.select.up")) {
5720
5924
  this.selectedIndex = this.selectedIndex === 0 ? this.filteredItems.length - 1 : this.selectedIndex - 1;
5721
5925
  this.notifySelectionChange();
5722
5926
  } else if (kb.matches(keyData, "tui.select.down")) {
5723
5927
  this.selectedIndex = this.selectedIndex === this.filteredItems.length - 1 ? 0 : this.selectedIndex + 1;
5724
5928
  this.notifySelectionChange();
5929
+ } else if (pageIndex !== void 0) {
5930
+ if (this.filteredItems.length === 0 || pageIndex === this.selectedIndex) return;
5931
+ this.selectedIndex = pageIndex;
5932
+ this.notifySelectionChange();
5725
5933
  } else if (kb.matches(keyData, "tui.select.confirm")) {
5726
5934
  const selectedItem = this.filteredItems[this.selectedIndex];
5727
5935
  if (selectedItem && this.onSelect) this.onSelect(selectedItem);
@@ -6004,6 +6212,10 @@ var Editor = class Editor {
6004
6212
  };
6005
6213
  /** Focusable interface - set by TUI when focus changes */
6006
6214
  focused = false;
6215
+ /** The open autocomplete menu receives fullscreen viewport keys, such as PageUp/PageDown. */
6216
+ get capturesViewportInput() {
6217
+ return this.autocompleteState !== null;
6218
+ }
6007
6219
  tui;
6008
6220
  theme;
6009
6221
  paddingX = 0;
@@ -6074,6 +6286,15 @@ var Editor = class Editor {
6074
6286
  * unchanged body never needs another scan (X064). */
6075
6287
  pasteImagePlaceholders = /* @__PURE__ */ new Map();
6076
6288
  onSubmit;
6289
+ /** Pre-clear submit ADMISSION (dsh-pi-tui divergence X075): called with
6290
+ * the expanded submitted value BEFORE {@link onBeforeSubmitClear} and
6291
+ * before any draft/undo/paste-registry mutation. Returning `false` (or
6292
+ * throwing) aborts THIS submit gesture as if it never started: the draft,
6293
+ * caret, paste registry and Undo history stay exactly as they were, and
6294
+ * no history row/ack/business dispatch happens. The host uses it for the
6295
+ * one refusal that cannot be expressed after the clear: a terminal
6296
+ * pasted image path whose attachment read is still in flight. */
6297
+ onMaySubmit;
6077
6298
  /** Called with the submitted text immediately BEFORE the draft/undo clear.
6078
6299
  * The host reserves submission-time resources first and returns a ONE-SHOT
6079
6300
  * release: it runs in a finally after the synchronous clear + onSubmit
@@ -6328,10 +6549,11 @@ var Editor = class Editor {
6328
6549
  if (after.length > 0) {
6329
6550
  const firstGrapheme = [...this.segment(after, "grapheme")][0]?.segment || "";
6330
6551
  const restAfter = after.slice(firstGrapheme.length);
6331
- const cursor = `\x1b[7m${firstGrapheme}\x1b[0m`;
6552
+ const cursor = renderFakeCursor(firstGrapheme);
6332
6553
  displayText = before + marker + cursor + restAfter;
6333
6554
  } else {
6334
- displayText = before + marker + "\x1B[7m \x1B[0m";
6555
+ const cursor = renderFakeCursor(" ");
6556
+ displayText = before + marker + cursor;
6335
6557
  lineVisibleWidth = lineVisibleWidth + 1;
6336
6558
  if (lineVisibleWidth > contentWidth && paddingX > 0) cursorInPadding = true;
6337
6559
  }
@@ -6480,7 +6702,7 @@ var Editor = class Editor {
6480
6702
  this.cancelAutocomplete();
6481
6703
  return;
6482
6704
  }
6483
- if (kb.matches(data, "tui.select.up") || kb.matches(data, "tui.select.down")) {
6705
+ if (kb.matches(data, "tui.select.up") || kb.matches(data, "tui.select.down") || kb.matches(data, "tui.select.pageUp") || kb.matches(data, "tui.select.pageDown")) {
6484
6706
  this.autocompleteList.handleInput(data);
6485
6707
  return;
6486
6708
  }
@@ -7017,6 +7239,7 @@ var Editor = class Editor {
7017
7239
  }
7018
7240
  submitValue() {
7019
7241
  const result = this.expandPasteMarkersSinglePass(this.state.lines.join("\n")).text.trim();
7242
+ if (this.onMaySubmit?.(result) === false) return;
7020
7243
  const release = this.onBeforeSubmitClear?.(result);
7021
7244
  try {
7022
7245
  this.clearDraftAfterSubmit();
@@ -8482,7 +8705,7 @@ var Input = class {
8482
8705
  const placeholder = truncateToWidth(this.placeholder, availableWidth, "");
8483
8706
  const atCursor = [...segmenter$1.segment(placeholder)][0]?.segment ?? " ";
8484
8707
  const afterCursor = placeholder.slice(atCursor.length);
8485
- const textWithCursor = (this.focused ? CURSOR_MARKER : "") + `\x1b[7m${this.placeholderStyle(atCursor)}\x1b[27m` + this.placeholderStyle(afterCursor);
8708
+ const textWithCursor = (this.focused ? CURSOR_MARKER : "") + renderFakeCursor(this.placeholderStyle(atCursor)) + this.placeholderStyle(afterCursor);
8486
8709
  const padding = " ".repeat(Math.max(0, availableWidth - visibleWidth(textWithCursor)));
8487
8710
  return [this.prompt + textWithCursor + padding];
8488
8711
  }
@@ -8513,7 +8736,7 @@ var Input = class {
8513
8736
  const atCursor = cursorGrapheme?.segment ?? " ";
8514
8737
  const afterCursor = visibleText.slice(cursorDisplay + atCursor.length);
8515
8738
  const marker = this.focused ? CURSOR_MARKER : "";
8516
- const cursorChar = `\x1b[7m${atCursor}\x1b[27m`;
8739
+ const cursorChar = renderFakeCursor(atCursor);
8517
8740
  const textWithCursor = beforeCursor + marker + cursorChar + afterCursor;
8518
8741
  const visualLength = visibleWidth(textWithCursor);
8519
8742
  const padding = " ".repeat(Math.max(0, availableWidth - visualLength));
@@ -9788,7 +10011,13 @@ function renderLatex(source, options = {}) {
9788
10011
  return lines.map((line) => line.slice(indentation).trimEnd()).join("\n").trimEnd().replaceAll(PROTECTED_SPACE, " ");
9789
10012
  }
9790
10013
  const STRICT_STRIKETHROUGH_REGEX = /^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/;
9791
- var StrictStrikethroughTokenizer = class extends Tokenizer {
10014
+ var MarkdownTokenizer = class extends Tokenizer {
10015
+ url(src) {
10016
+ const token = super.url(src);
10017
+ if (!token) return void 0;
10018
+ const punctuationIndex = token.raw.search(cjkPunctuationRegex);
10019
+ return punctuationIndex < 0 ? token : super.url(token.raw.slice(0, punctuationIndex));
10020
+ }
9792
10021
  del(src) {
9793
10022
  const match = STRICT_STRIKETHROUGH_REGEX.exec(src);
9794
10023
  if (!match) return;
@@ -9801,73 +10030,6 @@ var StrictStrikethroughTokenizer = class extends Tokenizer {
9801
10030
  };
9802
10031
  }
9803
10032
  };
9804
- const FULLWIDTH_LEFT_PAREN = 65288;
9805
- const FULLWIDTH_RIGHT_PAREN = 65289;
9806
- const CJK_URL_TERMINATOR_REGEX = /[\u3000-\u303f\uff01-\uff07\uff0a-\uff0f\uff1a-\uff20\uff3b-\uff40\uff5b-\uff65\u2013\u2014\u2018\u2019\u201c\u201d\u2026]/;
9807
- /**
9808
- * Index at which to cut an autolink match, or -1 to keep it whole. Non-paren
9809
- * CJK punctuation terminates the URL outside of full-width parens; full-width
9810
- * parens only terminate it when unbalanced. Punctuation inside a balanced
9811
- * parenthetical (e.g. the ,in (北京,1949年)) stays part of the URL —
9812
- * prose parentheticals contain spaces and never survive marked's match this
9813
- * far, so a balanced group is almost always deliberate URL content.
9814
- */
9815
- function findCjkUrlBoundary(match) {
9816
- let parenDepth = 0;
9817
- let unmatchedOpen = -1;
9818
- for (let i = 0; i < match.length; i++) {
9819
- const code = match.charCodeAt(i);
9820
- if (code === FULLWIDTH_LEFT_PAREN) {
9821
- parenDepth++;
9822
- if (unmatchedOpen === -1) unmatchedOpen = i;
9823
- } else if (code === FULLWIDTH_RIGHT_PAREN) {
9824
- if (parenDepth === 0) return i;
9825
- parenDepth--;
9826
- if (parenDepth === 0) unmatchedOpen = -1;
9827
- } else if (parenDepth === 0 && CJK_URL_TERMINATOR_REGEX.test(match[i])) return i;
9828
- }
9829
- return parenDepth > 0 ? unmatchedOpen : -1;
9830
- }
9831
- var CjkBoundaryUrlTokenizer = class extends StrictStrikethroughTokenizer {
9832
- url(src) {
9833
- const cap = this.rules.inline.url.exec(src);
9834
- if (!cap) return;
9835
- if (cap[2] === "@") {
9836
- const text = cap[0];
9837
- return {
9838
- type: "link",
9839
- raw: text,
9840
- text,
9841
- href: `mailto:${text}`,
9842
- tokens: [{
9843
- type: "text",
9844
- raw: text,
9845
- text
9846
- }]
9847
- };
9848
- }
9849
- const boundary = findCjkUrlBoundary(cap[0]);
9850
- if (boundary !== -1) cap[0] = cap[0].slice(0, boundary);
9851
- if (!cap[0]) return;
9852
- let previous;
9853
- do {
9854
- previous = cap[0];
9855
- cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? "";
9856
- } while (previous !== cap[0]);
9857
- const text = cap[0];
9858
- return {
9859
- type: "link",
9860
- raw: text,
9861
- text,
9862
- href: cap[1] === "www." ? `http://${text}` : text,
9863
- tokens: [{
9864
- type: "text",
9865
- raw: text,
9866
- text
9867
- }]
9868
- };
9869
- }
9870
- };
9871
10033
  function isEscaped(source, index) {
9872
10034
  let backslashes = 0;
9873
10035
  for (let position = index - 1; position >= 0 && source[position] === "\\"; position--) backslashes++;
@@ -9917,28 +10079,37 @@ function tokenizeInlineLatex(source) {
9917
10079
  text
9918
10080
  };
9919
10081
  }
10082
+ const TABLE_DELIMITER_ROW_REGEX = /^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/;
10083
+ function containsTableStart(source) {
10084
+ const lines = source.split("\n");
10085
+ for (let index = 0; index < lines.length - 1; index++) {
10086
+ const delimiterRow = lines[index + 1];
10087
+ if ((delimiterRow.includes("|") || lines[index].includes("|")) && TABLE_DELIMITER_ROW_REGEX.test(delimiterRow)) return true;
10088
+ }
10089
+ return false;
10090
+ }
9920
10091
  function tokenizeBlockLatex(source) {
9921
10092
  const dollarMatch = /^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*?)\$\$[ \t]*(?:\n|$)/.exec(source);
9922
- if (dollarMatch?.[1]) return {
10093
+ if (dollarMatch?.[1] && !containsTableStart(dollarMatch[1])) return {
9923
10094
  type: "latexBlock",
9924
10095
  raw: dollarMatch[0],
9925
10096
  text: dollarMatch[1].trim()
9926
10097
  };
9927
10098
  const bracketMatch = /^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*?)\\\][ \t]*(?:\n|$)/.exec(source);
9928
- if (bracketMatch?.[1]) return {
10099
+ if (bracketMatch?.[1] && !containsTableStart(bracketMatch[1])) return {
9929
10100
  type: "latexBlock",
9930
10101
  raw: bracketMatch[0],
9931
10102
  text: bracketMatch[1].trim()
9932
10103
  };
9933
10104
  const pendingBracket = /^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*)$/.exec(source);
9934
- if (pendingBracket) return {
10105
+ if (pendingBracket?.[1] && !containsTableStart(pendingBracket[1])) return {
9935
10106
  type: "latexBlock",
9936
10107
  raw: pendingBracket[0],
9937
10108
  text: pendingBracket[1],
9938
10109
  pending: true
9939
10110
  };
9940
10111
  const pendingDollar = /^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*)$/.exec(source);
9941
- if (pendingDollar?.[1] && looksLikePendingDollarMath(pendingDollar[1])) return {
10112
+ if (pendingDollar?.[1] && looksLikePendingDollarMath(pendingDollar[1]) && !containsTableStart(pendingDollar[1])) return {
9942
10113
  type: "latexBlock",
9943
10114
  raw: pendingDollar[0],
9944
10115
  text: pendingDollar[1],
@@ -9983,8 +10154,11 @@ function trimPartialClosingFences(tokens) {
9983
10154
  token.text = token.text.slice(0, -lastLine.length).replace(/\n$/, "");
9984
10155
  }
9985
10156
  const markdownParser = new Marked();
9986
- markdownParser.setOptions({ tokenizer: new CjkBoundaryUrlTokenizer() });
9987
- markdownParser.use({ extensions: [...LATEX_MARKDOWN_EXTENSIONS] });
10157
+ markdownParser.setOptions({ tokenizer: new MarkdownTokenizer() });
10158
+ markdownParser.use({
10159
+ tokenizer: { emStrong: markedCjkFriendly().tokenizer?.emStrong },
10160
+ extensions: [...LATEX_MARKDOWN_EXTENSIONS]
10161
+ });
9988
10162
  var Markdown = class {
9989
10163
  text;
9990
10164
  paddingX;
@@ -9997,6 +10171,8 @@ var Markdown = class {
9997
10171
  cachedWidth;
9998
10172
  cachedLines;
9999
10173
  cachedTokens;
10174
+ blocks;
10175
+ blockHighlightedCode;
10000
10176
  constructor(text, paddingX, paddingY, theme, defaultTextStyle, options) {
10001
10177
  this.text = text;
10002
10178
  this.paddingX = paddingX;
@@ -10007,9 +10183,14 @@ var Markdown = class {
10007
10183
  }
10008
10184
  setText(text) {
10009
10185
  this.text = text;
10010
- this.invalidate();
10186
+ this.clearRenderCache();
10011
10187
  }
10012
10188
  invalidate() {
10189
+ this.clearRenderCache();
10190
+ this.blocks = void 0;
10191
+ this.defaultStylePrefix = void 0;
10192
+ }
10193
+ clearRenderCache() {
10013
10194
  this.cachedText = void 0;
10014
10195
  this.cachedWidth = void 0;
10015
10196
  this.cachedLines = void 0;
@@ -10019,6 +10200,7 @@ var Markdown = class {
10019
10200
  const contentWidth = Math.max(1, width - this.paddingX * 2);
10020
10201
  const text = this.options.transform?.(this.text, contentWidth) ?? this.text;
10021
10202
  if (!text || text.trim() === "") {
10203
+ this.blocks = void 0;
10022
10204
  const result = [];
10023
10205
  this.cachedText = this.text;
10024
10206
  this.cachedWidth = width;
@@ -10036,46 +10218,65 @@ var Markdown = class {
10036
10218
  tokens
10037
10219
  });
10038
10220
  }
10039
- const renderedLines = [];
10221
+ const reuseBlocks = Object.keys(tokens.links).length === 0;
10222
+ const previousBlocks = this.blocks?.deref();
10223
+ const blocks = /* @__PURE__ */ new Map();
10224
+ this.blocks = new WeakRef(blocks);
10225
+ const contentLines = [];
10040
10226
  for (let i = 0; i < tokens.length; i++) {
10041
10227
  const token = tokens[i];
10042
- const nextToken = tokens[i + 1];
10043
- const tokenLines = this.renderToken(token, contentWidth, nextToken?.type);
10044
- for (const tokenLine of tokenLines) renderedLines.push(tokenLine);
10228
+ const nextTokenType = tokens[i + 1]?.type;
10229
+ const block = (reuseBlocks ? blocks.get(token.raw) ?? previousBlocks?.get(token.raw) : void 0) ?? {
10230
+ width: -1,
10231
+ nextTokenType,
10232
+ lines: [],
10233
+ highlightedCode: /* @__PURE__ */ new Map()
10234
+ };
10235
+ if (block.width !== width || block.nextTokenType !== nextTokenType) this.renderBlock(block, token, nextTokenType, width, contentWidth);
10236
+ if (reuseBlocks) blocks.set(token.raw, block);
10237
+ for (const line of block.lines) contentLines.push(line);
10045
10238
  }
10046
- const wrappedLines = [];
10047
- for (const line of renderedLines) if (isImageLine(line)) wrappedLines.push(line);
10048
- else for (const wrappedLine of wrapTextWithAnsi(line, contentWidth)) wrappedLines.push(wrappedLine);
10049
- const leftMargin = " ".repeat(this.paddingX);
10050
- const rightMargin = " ".repeat(this.paddingX);
10051
10239
  const bgFn = this.defaultTextStyle?.bgColor;
10052
- const contentLines = [];
10053
- for (const line of wrappedLines) {
10054
- if (isImageLine(line)) {
10055
- contentLines.push(line);
10056
- continue;
10057
- }
10058
- const lineWithMargins = leftMargin + line + rightMargin;
10059
- if (bgFn) contentLines.push(applyBackgroundToLine(lineWithMargins, width, bgFn));
10060
- else {
10061
- const visibleLen = visibleWidth(lineWithMargins);
10062
- const paddingNeeded = Math.max(0, width - visibleLen);
10063
- contentLines.push(lineWithMargins + " ".repeat(paddingNeeded));
10064
- }
10065
- }
10066
10240
  const emptyLine = " ".repeat(width);
10067
10241
  const emptyLines = [];
10068
10242
  for (let i = 0; i < this.paddingY; i++) {
10069
10243
  const line = bgFn ? applyBackgroundToLine(emptyLine, width, bgFn) : emptyLine;
10070
10244
  emptyLines.push(line);
10071
10245
  }
10246
+ flattenLines(emptyLines);
10072
10247
  const result = emptyLines.concat(contentLines, emptyLines);
10073
- flattenLines(result);
10074
10248
  this.cachedText = this.text;
10075
10249
  this.cachedWidth = width;
10076
10250
  this.cachedLines = result;
10077
10251
  return result.length > 0 ? result : [""];
10078
10252
  }
10253
+ /** Render one top-level block to output lines: wrapped, with margins, and padded or backgrounded to the width. */
10254
+ renderBlock(block, token, nextTokenType, width, contentWidth) {
10255
+ this.blockHighlightedCode = block.highlightedCode;
10256
+ const leftMargin = " ".repeat(this.paddingX);
10257
+ const rightMargin = " ".repeat(this.paddingX);
10258
+ const bgFn = this.defaultTextStyle?.bgColor;
10259
+ const lines = [];
10260
+ for (const line of this.renderToken(token, contentWidth, nextTokenType)) {
10261
+ if (isImageLine(line)) {
10262
+ lines.push(line);
10263
+ continue;
10264
+ }
10265
+ for (const wrappedLine of wrapTextWithAnsi(line, contentWidth)) {
10266
+ const lineWithMargins = leftMargin + wrappedLine + rightMargin;
10267
+ if (bgFn) lines.push(applyBackgroundToLine(lineWithMargins, width, bgFn));
10268
+ else {
10269
+ const paddingNeeded = Math.max(0, width - visibleWidth(lineWithMargins));
10270
+ lines.push(lineWithMargins + " ".repeat(paddingNeeded));
10271
+ }
10272
+ }
10273
+ }
10274
+ this.blockHighlightedCode = void 0;
10275
+ flattenLines(lines);
10276
+ block.lines = lines;
10277
+ block.width = width;
10278
+ block.nextTokenType = nextTokenType;
10279
+ }
10079
10280
  /**
10080
10281
  * Apply default text style to a string.
10081
10282
  * This is the base styling applied to all text content.
@@ -10148,7 +10349,8 @@ var Markdown = class {
10148
10349
  break;
10149
10350
  case "latexBlock": {
10150
10351
  const latexToken = token;
10151
- const rendered = !latexToken.pending && this.options.renderLatex !== false ? renderLatex(latexToken.text, { display: true }) ?? latexToken.raw.trim() : latexToken.raw.trim();
10352
+ let rendered = !latexToken.pending && this.options.renderLatex !== false ? renderLatex(latexToken.text, { display: true }) : void 0;
10353
+ if (rendered === void 0 || rendered.split("\n").some((line) => visibleWidth(line) > width)) rendered = latexToken.raw.trim();
10152
10354
  for (const line of rendered.split("\n")) lines.push(this.applyDefaultStyle(line));
10153
10355
  if (nextTokenType && nextTokenType !== "space") lines.push("");
10154
10356
  break;
@@ -10157,8 +10359,13 @@ var Markdown = class {
10157
10359
  const indent = this.theme.codeBlockIndent ?? " ";
10158
10360
  lines.push(this.theme.codeBlockBorder(`\`\`\`${token.lang || ""}`));
10159
10361
  if (this.theme.highlightCode) {
10160
- const highlightedLines = this.theme.highlightCode(token.text, token.lang);
10161
- for (const hlLine of highlightedLines) lines.push(`${indent}${hlLine}`);
10362
+ const key = `${token.lang ?? ""}\0${token.text}`;
10363
+ let highlighted = this.blockHighlightedCode?.get(key);
10364
+ if (!highlighted) {
10365
+ highlighted = this.theme.highlightCode(token.text, token.lang);
10366
+ this.blockHighlightedCode?.set(key, highlighted);
10367
+ }
10368
+ for (const hlLine of highlighted) lines.push(`${indent}${hlLine}`);
10162
10369
  } else {
10163
10370
  const codeLines = token.text.split("\n");
10164
10371
  for (const codeLine of codeLines) lines.push(`${indent}${this.theme.codeBlock(codeLine)}`);
@@ -10185,7 +10392,12 @@ var Markdown = class {
10185
10392
  const lineWithReappliedStyle = line.replace(/\x1b\[0m/g, `\x1b[0m${quoteStylePrefix}`);
10186
10393
  return quoteStyle(lineWithReappliedStyle);
10187
10394
  };
10188
- const quoteContentWidth = Math.max(1, width - 2);
10395
+ if (width < 3) {
10396
+ const quoteTokens = token.tokens || [];
10397
+ for (let i = 0; i < quoteTokens.length; i++) for (const line of this.renderToken(quoteTokens[i], width, quoteTokens[i + 1]?.type, styleContext)) lines.push(line);
10398
+ break;
10399
+ }
10400
+ const quoteContentWidth = width - 2;
10189
10401
  const quoteInlineStyleContext = {
10190
10402
  applyText: (text) => text,
10191
10403
  stylePrefix: quoteStylePrefix
@@ -10195,7 +10407,7 @@ var Markdown = class {
10195
10407
  for (let i = 0; i < quoteTokens.length; i++) {
10196
10408
  const quoteToken = quoteTokens[i];
10197
10409
  const nextQuoteToken = quoteTokens[i + 1];
10198
- renderedQuoteLines.push(...this.renderToken(quoteToken, quoteContentWidth, nextQuoteToken?.type, quoteInlineStyleContext));
10410
+ for (const line of this.renderToken(quoteToken, quoteContentWidth, nextQuoteToken?.type, quoteInlineStyleContext)) renderedQuoteLines.push(line);
10199
10411
  }
10200
10412
  while (renderedQuoteLines.length > 0 && renderedQuoteLines[renderedQuoteLines.length - 1] === "") renderedQuoteLines.pop();
10201
10413
  for (const quoteLine of renderedQuoteLines) {
@@ -10733,6 +10945,7 @@ function fitValueParts(parts, maxWidth) {
10733
10945
  return parts.slice(0, kept).map((part) => part.text).join("");
10734
10946
  }
10735
10947
  var SettingsList = class {
10948
+ capturesViewportInput = true;
10736
10949
  items;
10737
10950
  filteredItems;
10738
10951
  theme;
@@ -11036,12 +11249,16 @@ var SettingsList = class {
11036
11249
  }
11037
11250
  const kb = getKeybindings();
11038
11251
  const displayItems = this.getDisplayItems();
11252
+ const pageIndex = getSelectPageIndex(kb, data, this.selectedIndex, displayItems.length, this.maxVisible);
11039
11253
  if (kb.matches(data, "tui.select.up")) {
11040
11254
  if (displayItems.length === 0) return;
11041
11255
  this.selectedIndex = this.selectedIndex === 0 ? displayItems.length - 1 : this.selectedIndex - 1;
11042
11256
  } else if (kb.matches(data, "tui.select.down")) {
11043
11257
  if (displayItems.length === 0) return;
11044
11258
  this.selectedIndex = this.selectedIndex === displayItems.length - 1 ? 0 : this.selectedIndex + 1;
11259
+ } else if (pageIndex !== void 0) {
11260
+ if (displayItems.length === 0) return;
11261
+ this.selectedIndex = pageIndex;
11045
11262
  } else if (kb.matches(data, "tui.select.confirm") || data === " " && (!this.searchEnabled || this.searchInput?.getValue().length === 0)) this.activateItem();
11046
11263
  else if (kb.matches(data, "tui.select.cancel")) this.onCancel();
11047
11264
  else if (this.searchEnabled && this.searchInput) {
@@ -11182,6 +11399,12 @@ function getNativePlatformHelper() {
11182
11399
  if (process.platform !== "darwin" && process.platform !== "win32") return void 0;
11183
11400
  return loadNativePlatformHelper(process.platform);
11184
11401
  }
11402
+ /**
11403
+ * Program Status Protocol (OSC 7501): a program tells the terminal whether it is idle, working,
11404
+ * blocked on the user, done, or failed. Only the root record is supported.
11405
+ *
11406
+ * Spec: https://www.superlogical.com/rex/docs/build/program-status
11407
+ */
11185
11408
  /** Feature detection query. A supporting terminal replies with the same body. */
11186
11409
  const PROGRAM_STATUS_QUERY = "\x1B]7501;?\x1B\\";
11187
11410
  /** The reply to {@link PROGRAM_STATUS_QUERY}. Later spec revisions may add pairs after the `?`. */
@@ -11189,7 +11412,6 @@ function isProgramStatusReply(sequence) {
11189
11412
  return /^\x1b\]7501;\?[^\x07\x1b]*(?:\x07|\x1b\\)$/.test(sequence);
11190
11413
  }
11191
11414
  const APP_PATTERN = /^[A-Za-z0-9_.+-]{1,32}$/;
11192
- const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]+/g;
11193
11415
  /** Decoded `msg` limit. Its base64 encoding stays under the 2732-byte encoded limit. */
11194
11416
  const MAX_MESSAGE_BYTES = 2048;
11195
11417
  function truncateUtf8(text, maxBytes) {
@@ -11209,7 +11431,7 @@ function formatProgramStatus(status) {
11209
11431
  const pairs = [`state=${status.state}`];
11210
11432
  if (status.app !== void 0 && APP_PATTERN.test(status.app)) pairs.push(`app=${status.app}`);
11211
11433
  if (status.state === "blocked" && status.kind) pairs.push(`kind=${status.kind}`);
11212
- const message = truncateUtf8((status.message ?? "").replace(CONTROL_CHARACTERS, " ").trim(), MAX_MESSAGE_BYTES);
11434
+ const message = truncateUtf8(replaceControlCharacters(status.message ?? "").trim(), MAX_MESSAGE_BYTES);
11213
11435
  if (message) pairs.push(`msg=${Buffer.from(message, "utf8").toString("base64")}`);
11214
11436
  return `\x1b]7501;${pairs.join(":")}\x1b\\`;
11215
11437
  }
@@ -11236,6 +11458,10 @@ const DEFAULT_SEQUENCE_TIMEOUT_MS = 50;
11236
11458
  const DEFAULT_ESCAPE_TIMEOUT_MS$1 = 10;
11237
11459
  const BRACKETED_PASTE_START = "\x1B[200~";
11238
11460
  const BRACKETED_PASTE_END = "\x1B[201~";
11461
+ const TERMINAL_REPLY_HEADER_PATTERN = /^\x1b(?:\](?:1[01];|4;\d{1,3};|7501;\?)|P>\||_G(?:[a-z]=\d+,)*[a-z]=\d+;)/;
11462
+ function isControlString(data) {
11463
+ return data.startsWith(`${ESC}]`) || data.startsWith(`${ESC}P`) || data.startsWith(`${ESC}_`);
11464
+ }
11239
11465
  /**
11240
11466
  * A never-terminating ESC prefix (corrupt stream, oversized paste) must not
11241
11467
  * reslice the buffer once per byte — cap the scan and degrade the ESC to a
@@ -11327,8 +11553,20 @@ function extractCompleteSequences(buffer) {
11327
11553
  while (pos < buffer.length) {
11328
11554
  const remaining = buffer.slice(pos);
11329
11555
  if (remaining.startsWith(ESC)) {
11556
+ const terminalReply = isControlString(remaining) && TERMINAL_REPLY_HEADER_PATTERN.test(remaining);
11330
11557
  let seqEnd = 1;
11331
11558
  while (seqEnd <= remaining.length) {
11559
+ if (terminalReply && seqEnd > 2) {
11560
+ const char = remaining[seqEnd - 1];
11561
+ if (char === "" || char === "") {
11562
+ pos += seqEnd;
11563
+ break;
11564
+ }
11565
+ if (char === ESC && seqEnd < remaining.length && remaining[seqEnd] !== "\\") {
11566
+ pos += seqEnd - 1;
11567
+ break;
11568
+ }
11569
+ }
11332
11570
  const candidate = remaining.slice(0, seqEnd);
11333
11571
  const status = isCompleteSequence(candidate);
11334
11572
  if (status === "complete") {
@@ -11446,10 +11684,14 @@ var StdinBuffer = class extends EventEmitter {
11446
11684
  this.buffer = result.remainder;
11447
11685
  for (const sequence of result.sequences) this.emitDataSequence(sequence);
11448
11686
  if (this.buffer.length > 0) {
11687
+ if (TERMINAL_REPLY_HEADER_PATTERN.test(this.buffer)) return;
11449
11688
  const timeoutMs = this.buffer === ESC ? this.escapeTimeoutMs : this.timeoutMs;
11450
11689
  this.timeout = setTimeout(() => {
11451
11690
  const flushed = this.flush();
11452
- for (const sequence of flushed) this.emitDataSequence(sequence);
11691
+ for (const sequence of flushed) if (sequence.length > 2 && isControlString(sequence)) {
11692
+ this.emitDataSequence(sequence.slice(0, 2));
11693
+ this.process(sequence.slice(2));
11694
+ } else this.emitDataSequence(sequence);
11453
11695
  }, timeoutMs);
11454
11696
  }
11455
11697
  }
@@ -11549,8 +11791,11 @@ function refreshTerminalDimensions() {
11549
11791
  process.kill(process.pid, "SIGWINCH");
11550
11792
  } catch {}
11551
11793
  }
11794
+ function isNativeShiftEnterCandidate(data) {
11795
+ return data === "\r" || data === "\x1B\r";
11796
+ }
11552
11797
  function normalizeNativeShiftEnterInput(data, shouldDetectNativeShiftEnter, isShiftPressed) {
11553
- if (shouldDetectNativeShiftEnter && data === "\r" && isShiftPressed) return NATIVE_SHIFT_ENTER_SEQUENCE;
11798
+ if (shouldDetectNativeShiftEnter && isNativeShiftEnterCandidate(data) && isShiftPressed) return NATIVE_SHIFT_ENTER_SEQUENCE;
11554
11799
  return data;
11555
11800
  }
11556
11801
  const DEFAULT_ESCAPE_TIMEOUT_MS = 10;
@@ -11833,7 +12078,7 @@ var ProcessTerminal = class {
11833
12078
  }
11834
12079
  forwardInputSequence(sequence) {
11835
12080
  if (!this.inputHandler) return;
11836
- const shouldDetectNativeShiftEnter = sequence === "\r" && (isAppleTerminalSession() || process.platform === "win32");
12081
+ const shouldDetectNativeShiftEnter = isNativeShiftEnterCandidate(sequence) && (isAppleTerminalSession() || process.platform === "win32");
11837
12082
  const input = normalizeNativeShiftEnterInput(sequence, shouldDetectNativeShiftEnter, shouldDetectNativeShiftEnter && isNativeModifierPressed("shift"));
11838
12083
  this.inputHandler(input);
11839
12084
  }
@@ -11926,6 +12171,18 @@ var ProcessTerminal = class {
11926
12171
  if (process.stdin.setRawMode) process.stdin.setRawMode(this.wasRaw);
11927
12172
  this.started = false;
11928
12173
  }
12174
+ restoreOnExit(before, after) {
12175
+ let sequence = before;
12176
+ if (this.progressState !== "clear") sequence += TERMINAL_PROGRESS_CLEAR_SEQUENCE;
12177
+ if (this.programStatusSupported && this.programStatus) sequence += formatProgramStatus({ state: "clear" });
12178
+ sequence += "\x1B[?2004l";
12179
+ if (this.keyboardProtocolPushed || this._kittyProtocolActive) sequence += "\x1B[<u";
12180
+ if (this._modifyOtherKeysActive) sequence += "\x1B[>4;0m";
12181
+ sequence += after;
12182
+ try {
12183
+ fs.writeSync(process.stdout.fd, sequence);
12184
+ } catch {}
12185
+ }
11929
12186
  write(data) {
11930
12187
  process.stdout.write(data);
11931
12188
  if (this.writeLogPath) try {
@@ -11958,7 +12215,7 @@ var ProcessTerminal = class {
11958
12215
  process.stdout.write("\x1B[2J\x1B[H");
11959
12216
  }
11960
12217
  setTitle(title) {
11961
- process.stdout.write(`\x1b]0;${title}\x07`);
12218
+ process.stdout.write(`\x1b]0;${replaceControlCharacters(title)}\x07`);
11962
12219
  }
11963
12220
  setProgramStatus(status) {
11964
12221
  this.programStatus = status.state === "clear" ? void 0 : status;
@@ -12280,7 +12537,7 @@ var AltScreenFlashContainer = class {
12280
12537
  });
12281
12538
  }
12282
12539
  };
12283
- const OSC133_ZONE_PREFIX$1 = /^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;
12540
+ const OSC133_ZONE_PREFIX$2 = /^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;
12284
12541
  /** The largest number of image body rows an upward crop search may cross (X074). */
12285
12542
  const MAX_SIXEL_CROP_SCAN_ROWS = 12;
12286
12543
  function intersect(a, b) {
@@ -12589,7 +12846,7 @@ function paintBox(box, screen, totalWidth, context) {
12589
12846
  const sourceIndex = offset + row - box.rect.y;
12590
12847
  const sourceLine = box.lines[sourceIndex];
12591
12848
  if (sourceLine === void 0) continue;
12592
- let line = sourceLine.replace(OSC133_ZONE_PREFIX$1, "");
12849
+ let line = sourceLine.replace(OSC133_ZONE_PREFIX$2, "");
12593
12850
  if (line.startsWith("\x1B_pi:tmux-image:v1:i=")) {
12594
12851
  const marker = getManagedKittyVirtualMarker(line);
12595
12852
  if (marker === void 0) throw new Error("managed kitty virtual marker is malformed");
@@ -12638,40 +12895,49 @@ function paintBox(box, screen, totalWidth, context) {
12638
12895
  }
12639
12896
  for (const child of box.children) paintBox(child, screen, totalWidth, context);
12640
12897
  if (box.scrollView && box.scrollContentLines && box.scrollView.scrollTop > 0 && box.rect.height > 0) {
12641
- const scanFloor = Math.max(0, box.scrollView.scrollTop - MAX_SIXEL_CROP_SCAN_ROWS);
12642
- for (let imageRow = box.scrollView.scrollTop - 1; imageRow >= 0; imageRow--) {
12898
+ const scrollTop = box.scrollView.scrollTop;
12899
+ const kittyScanFloor = Math.max(0, scrollTop - getMaxKittyImageRows());
12900
+ const sixelScanFloor = Math.max(0, scrollTop - MAX_SIXEL_CROP_SCAN_ROWS);
12901
+ let sixelSearch = true;
12902
+ let kittySearch = true;
12903
+ for (let imageRow = scrollTop - 1; imageRow >= 0; imageRow--) {
12904
+ if (!sixelSearch && !kittySearch) break;
12643
12905
  const imageLine = box.scrollContentLines[imageRow] ?? "";
12644
- const block = sixelBlock(imageLine, sixelScreen);
12645
- if (block !== void 0) {
12646
- const hiddenRows = box.scrollView.scrollTop - imageRow;
12647
- const visibleRows = Math.min(box.rect.height, block.rows - hiddenRows);
12648
- if (hiddenRows < block.rows && visibleRows > 0 && box.rect.x === 0 && box.rect.width >= totalWidth) {
12649
- if (block.kind === "candidate") {
12650
- context.sixelDemands.push({
12651
- line: imageLine,
12652
- cropTopRows: hiddenRows,
12653
- visibleRows,
12654
- physicalRow: box.rect.y
12655
- });
12656
- screen[box.rect.y] = sixelScreen?.materialize(imageLine, hiddenRows, visibleRows) ?? block.fallback;
12657
- } else {
12658
- const cropped = sixelScreen?.crop(imageLine, hiddenRows, visibleRows);
12659
- if (cropped !== void 0) screen[box.rect.y] = cropped;
12906
+ if (sixelSearch) {
12907
+ const block = sixelBlock(imageLine, sixelScreen);
12908
+ if (block !== void 0) {
12909
+ const hiddenRows = scrollTop - imageRow;
12910
+ const visibleRows = Math.min(box.rect.height, block.rows - hiddenRows);
12911
+ if (hiddenRows < block.rows && visibleRows > 0 && box.rect.x === 0 && box.rect.width >= totalWidth) {
12912
+ if (block.kind === "candidate") {
12913
+ context.sixelDemands.push({
12914
+ line: imageLine,
12915
+ cropTopRows: hiddenRows,
12916
+ visibleRows,
12917
+ physicalRow: box.rect.y
12918
+ });
12919
+ screen[box.rect.y] = sixelScreen?.materialize(imageLine, hiddenRows, visibleRows) ?? block.fallback;
12920
+ } else {
12921
+ const cropped = sixelScreen?.crop(imageLine, hiddenRows, visibleRows);
12922
+ if (cropped !== void 0) screen[box.rect.y] = cropped;
12923
+ }
12660
12924
  }
12925
+ break;
12661
12926
  }
12662
- break;
12663
12927
  }
12664
- const metadata = getKittyImageMetadata(imageLine);
12665
- if (metadata) {
12666
- const hiddenRows = box.scrollView.scrollTop - imageRow;
12667
- if (hiddenRows < metadata.rows) {
12668
- const cropped = cropKittyImageLine(imageLine, hiddenRows, Math.min(box.rect.height, metadata.rows - hiddenRows));
12669
- if (box.rect.x === 0 && box.rect.width >= totalWidth) screen[box.rect.y] = cropped;
12928
+ if (kittySearch) {
12929
+ const metadata = getKittyImageMetadata(imageLine);
12930
+ if (metadata) {
12931
+ const hiddenRows = scrollTop - imageRow;
12932
+ if (hiddenRows < metadata.rows) {
12933
+ const cropped = cropKittyImageLine(imageLine, hiddenRows, Math.min(box.rect.height, metadata.rows - hiddenRows));
12934
+ if (box.rect.x === 0 && box.rect.width >= totalWidth) screen[box.rect.y] = cropped;
12935
+ }
12936
+ break;
12670
12937
  }
12671
- break;
12672
12938
  }
12673
- if (imageLine !== "") break;
12674
- if (sixelScreen !== void 0 && imageRow <= scanFloor) break;
12939
+ if (sixelSearch && (imageLine !== "" || imageRow <= sixelScanFloor)) sixelSearch = false;
12940
+ if (kittySearch && imageRow <= kittyScanFloor) kittySearch = false;
12675
12941
  }
12676
12942
  }
12677
12943
  paintScrollbar(box, screen, totalWidth, sixelScreen);
@@ -12823,7 +13089,7 @@ const FOCUS_IN = "\x1B[I";
12823
13089
  const FOCUS_OUT = "\x1B[O";
12824
13090
  const BEGIN_SYNCHRONIZED_OUTPUT = "\x1B[?2026h";
12825
13091
  const END_SYNCHRONIZED_OUTPUT = "\x1B[?2026l";
12826
- const OSC133_ZONE_PREFIX = /^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;
13092
+ const OSC133_ZONE_PREFIX$1 = /^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;
12827
13093
  const OSC133_PROMPT_START = /^\x1b\]133;A(?:\x07|\x1b\\)/;
12828
13094
  const PAGE_SCROLL_OVERLAP = 4;
12829
13095
  const ALT_WHEEL_SCROLL_MULTIPLIER = 5;
@@ -12832,7 +13098,15 @@ const MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES = 33554432;
12832
13098
  const MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES = 67108864;
12833
13099
  const DOUBLE_CLICK_INTERVAL_MS = 500;
12834
13100
  const COPY_ERROR_FLASH_DURATION_MS = 5e3;
12835
- const TERMINAL_WORD_SELECTION_JOINERS = /* @__PURE__ */ new Set(["/", "-"]);
13101
+ const TERMINAL_WORD_SELECTION_JOINERS = /* @__PURE__ */ new Set([
13102
+ "/",
13103
+ "-",
13104
+ "+",
13105
+ "\\",
13106
+ "~",
13107
+ "_",
13108
+ "."
13109
+ ]);
12836
13110
  const wordSegmenter = getWordSegmenter();
12837
13111
  /** Alternate-screen TUI with a scrollable, application-owned viewport. */
12838
13112
  var TuiAltScreen = class extends TuiBase {
@@ -13104,7 +13378,7 @@ var TuiAltScreen = class extends TuiBase {
13104
13378
  if (options.preserveScreen) this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}\x1b[?25h${END_SYNCHRONIZED_OUTPUT}`);
13105
13379
  else {
13106
13380
  const width = Math.max(1, this.terminal.columns);
13107
- const documentLines = this.render(width).map((line) => line.replace(OSC133_ZONE_PREFIX, "")).map((line) => this.sixelScreen?.candidate(line)?.fallback ?? line);
13381
+ const documentLines = this.resolveFakeCursors(this.render(width)).map((line) => line.replace(OSC133_ZONE_PREFIX$1, "")).map((line) => this.sixelScreen?.candidate(line)?.fallback ?? line);
13108
13382
  this.lastDocument = this.applyLineResets(documentLines.map((line) => line.replaceAll(CURSOR_MARKER, ""))).map((line) => this.sixelFootprint(line) !== void 0 ? "" : isImageLine(line) || visibleWidth(line) <= width ? line : sliceByColumn(line, 0, width, true));
13109
13383
  let buffer = `${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}${DISABLE_AUTOWRAP}`;
13110
13384
  for (let row = 0; row < this.lastDocument.length; row++) {
@@ -13119,6 +13393,14 @@ var TuiAltScreen = class extends TuiBase {
13119
13393
  this.savedCapabilities = void 0;
13120
13394
  }
13121
13395
  }
13396
+ getExitRestorePrefix() {
13397
+ const prefix = super.getExitRestorePrefix();
13398
+ if (!this.altScreenActive) return prefix;
13399
+ return `${END_SYNCHRONIZED_OUTPUT}${this.mouseEnabled ? DISABLE_MOUSE : ""}${ENABLE_AUTOWRAP}${prefix}`;
13400
+ }
13401
+ getExitRestoreSuffix() {
13402
+ return `${super.getExitRestoreSuffix()}${this.altScreenActive ? `${EXIT_ALT_SCREEN}\x1b[?25h` : ""}`;
13403
+ }
13122
13404
  deleteKittyImages() {
13123
13405
  return this.imageProtocol === "kitty" ? deleteAllKittyImages() : "";
13124
13406
  }
@@ -13385,6 +13667,7 @@ var TuiAltScreen = class extends TuiBase {
13385
13667
  flash(message, durationMs) {
13386
13668
  this.flashes.flash(message, durationMs);
13387
13669
  }
13670
+ /** Focused overlays and components that capture viewport input receive viewport keys instead of the transcript. */
13388
13671
  shouldDeferViewportInputToOverlay() {
13389
13672
  return this.isOverlayFocused() && this.activeSearch?.overlay?.isFocused() !== true;
13390
13673
  }
@@ -13545,6 +13828,7 @@ var TuiAltScreen = class extends TuiBase {
13545
13828
  }
13546
13829
  }
13547
13830
  if (this.shouldDeferViewportInputToOverlay()) return void 0;
13831
+ if (this.getFocusedComponent()?.capturesViewportInput === true) return void 0;
13548
13832
  if (!isRelease && this.onBeforeViewportInput?.(data) === true) return { consume: true };
13549
13833
  const primaryScrollable = this.getPrimaryScrollView().canScroll;
13550
13834
  if (keybindings.matches(data, "tui.altScreen.search")) {
@@ -14520,7 +14804,7 @@ var TuiAltScreen = class extends TuiBase {
14520
14804
  if (this.sixelScreen !== void 0) {
14521
14805
  if (this.sixelScreen.reconcileVisible(this, nextLayout.sixelDemands)) nextLayout = renderLayoutFrame(root, width, height, () => this.requestRender(), this.sixelScreen);
14522
14806
  }
14523
- let screen = nextLayout.lines.map((line) => line.replace(OSC133_ZONE_PREFIX, ""));
14807
+ let screen = this.resolveFakeCursors(nextLayout.lines.map((line) => line.replace(OSC133_ZONE_PREFIX$1, "")));
14524
14808
  screen = this.applySearchHighlights(screen, nextLayout);
14525
14809
  screen = this.compositeScrollToEndIndicator(screen, nextLayout, width);
14526
14810
  screen = this.compositeOverlays(screen, width, height);
@@ -14617,6 +14901,8 @@ var TuiAltScreen = class extends TuiBase {
14617
14901
  this.onFramePainted?.();
14618
14902
  }
14619
14903
  };
14904
+ /** OSC 133 prompt markers at the start of a rendered line. Fullscreen uses them for prompt navigation. */
14905
+ const OSC133_ZONE_PREFIX = /^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;
14620
14906
  const KITTY_SEQUENCE_PREFIX = "\x1B_G";
14621
14907
  const MAX_RENDER_WRITE_CHARS = 1048576;
14622
14908
  const EMPTY_IMAGE_IDS = [];
@@ -15078,7 +15364,7 @@ var TuiMainScreen = class extends TuiBase {
15078
15364
  const currentScreenRow = hardwareCursorRow - prevViewportTop;
15079
15365
  return targetRow - viewportTop - currentScreenRow;
15080
15366
  };
15081
- let rawLines = this.render(width);
15367
+ let rawLines = this.resolveFakeCursors(this.render(width).map((line) => line.replace(OSC133_ZONE_PREFIX, "")));
15082
15368
  if (this.hasOverlayEntries) {
15083
15369
  rawLines = this.compositeOverlays(rawLines, width, height);
15084
15370
  this.suppressOverlayCoveredSixelBlocks(rawLines);
@@ -15428,4 +15714,4 @@ var TuiMainScreen = class extends TuiBase {
15428
15714
  }
15429
15715
  };
15430
15716
  //#endregion
15431
- export { resolveUserCommandItemActivationIds as $, isKeyRelease as A, CUSTOM_FOOTER_ITEM_PREFIX as B, fuzzyFilter as C, getKeybindings as D, getGraphemeSegmenter as E, sliceByColumn as F, customItemName as G, activeFooterItemIds as H, stripTerminalSequences as I, executableCommandItemIds as J, effectiveCustomCommandRefreshMs as K, truncateToWidth as L, matchesKey as M, parseKey as N, imageFallback as O, registerKittyImageMetadata as P, resolveTrustedFooterCommand as Q, visibleWidth as R, findAltScreenSearchMatches as S, getCellDimensions as T, customCommandConfigOf as U, DEFAULT_CUSTOM_COMMAND_REFRESH_MS as V, customItemId as W, parseFooterCustomItems as X, parseFooterCustomItem as Y, parseFooterCommandConfig as Z, TuiMainScreen as _, HStack as a, isFooterLayout as at, decodePrintableKey as b, Key as c, stripControlChars as ct, ProcessTerminal as d, resolveUserCommandItemFallbackActivationIds as et, ScrollView as f, TuiAltScreen as g, Text as h, Editor as i, hideFooterRefInTsp as it, isKeyRepeat as j, isFocusable as k, Markdown as l, Spacer as m, CombinedAutocompleteProvider as n, MAX_COMMAND_TIMEOUT_MS as nt, Image as o, parseFooterLayout as ot, SettingsList as p, effectiveCustomCommandTimeoutMs as q, Container as r, defaultHideInTsp as rt, Input as s, resolveCommandFooterFallback as st, AltScreenSearchIndex as t, resolveUserLayerFooterMode as tt, MouseRegion as u, VStack as v, getCapabilities as w, dispatchMouseEvent as x, decodeKittyPrintable as y, wrapTextWithAnsi as z };
15717
+ export { parseFooterCommandConfig as $, imageFallback as A, visibleWidth as B, findAltScreenSearchMatches as C, getGraphemeSegmenter as D, getCellDimensions as E, parseKey as F, customCommandConfigOf as G, CUSTOM_FOOTER_ITEM_PREFIX as H, registerKittyImageMetadata as I, effectiveCustomCommandRefreshMs as J, customItemId as K, sliceByColumn as L, isKeyRelease as M, isKeyRepeat as N, getKeybindings as O, matchesKey as P, parseFooterCustomItems as Q, stripTerminalSequences as R, dispatchMouseEvent as S, getCapabilities as T, DEFAULT_CUSTOM_COMMAND_REFRESH_MS as U, wrapTextWithAnsi as V, activeFooterItemIds as W, executableCommandItemIds as X, effectiveCustomCommandTimeoutMs as Y, parseFooterCustomItem as Z, TuiAltScreen as _, Editor as a, defaultHideInTsp as at, decodeKittyPrintable as b, Input as c, parseFooterLayout as ct, MouseRegion as d, resolveTrustedFooterCommand as et, ProcessTerminal as f, Text as g, Spacer as h, Container as i, MAX_COMMAND_TIMEOUT_MS as it, isFocusable as j, getOsc8LinkAtColumn as k, Key as l, resolveCommandFooterFallback as lt, SettingsList as m, CURSOR_MARKER as n, resolveUserCommandItemFallbackActivationIds as nt, HStack as o, hideFooterRefInTsp as ot, ScrollView as p, customItemName as q, CombinedAutocompleteProvider as r, resolveUserLayerFooterMode as rt, Image as s, isFooterLayout as st, AltScreenSearchIndex as t, resolveUserCommandItemActivationIds as tt, Markdown as u, stripControlChars as ut, TuiMainScreen as v, fuzzyFilter as w, decodePrintableKey as x, VStack as y, truncateToWidth as z };