keys.ts 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400
  1. /**
  2. * Keyboard input handling for terminal applications.
  3. *
  4. * Supports both legacy terminal sequences and Kitty keyboard protocol.
  5. * See: https://sw.kovidgoyal.net/kitty/keyboard-protocol/
  6. * Reference: https://github.com/sst/opentui/blob/7da92b4088aebfe27b9f691c04163a48821e49fd/packages/core/src/lib/parse.keypress.ts
  7. *
  8. * Symbol keys are also supported, however some ctrl+symbol combos
  9. * overlap with ASCII codes, e.g. ctrl+[ = ESC.
  10. * See: https://sw.kovidgoyal.net/kitty/keyboard-protocol/#legacy-ctrl-mapping-of-ascii-keys
  11. * Those can still be * used for ctrl+shift combos
  12. *
  13. * API:
  14. * - matchesKey(data, keyId) - Check if input matches a key identifier
  15. * - parseKey(data) - Parse input and return the key identifier
  16. * - Key - Helper object for creating typed key identifiers
  17. * - setKittyProtocolActive(active) - Set global Kitty protocol state
  18. * - isKittyProtocolActive() - Query global Kitty protocol state
  19. */
  20. // =============================================================================
  21. // Global Kitty Protocol State
  22. // =============================================================================
  23. let _kittyProtocolActive = false;
  24. /**
  25. * Set the global Kitty keyboard protocol state.
  26. * Called by ProcessTerminal after detecting protocol support.
  27. */
  28. export function setKittyProtocolActive(active: boolean): void {
  29. _kittyProtocolActive = active;
  30. }
  31. /**
  32. * Query whether Kitty keyboard protocol is currently active.
  33. */
  34. export function isKittyProtocolActive(): boolean {
  35. return _kittyProtocolActive;
  36. }
  37. // =============================================================================
  38. // Type-Safe Key Identifiers
  39. // =============================================================================
  40. type Letter =
  41. | "a"
  42. | "b"
  43. | "c"
  44. | "d"
  45. | "e"
  46. | "f"
  47. | "g"
  48. | "h"
  49. | "i"
  50. | "j"
  51. | "k"
  52. | "l"
  53. | "m"
  54. | "n"
  55. | "o"
  56. | "p"
  57. | "q"
  58. | "r"
  59. | "s"
  60. | "t"
  61. | "u"
  62. | "v"
  63. | "w"
  64. | "x"
  65. | "y"
  66. | "z";
  67. type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
  68. type SymbolKey =
  69. | "`"
  70. | "-"
  71. | "="
  72. | "["
  73. | "]"
  74. | "\\"
  75. | ";"
  76. | "'"
  77. | ","
  78. | "."
  79. | "/"
  80. | "!"
  81. | "@"
  82. | "#"
  83. | "$"
  84. | "%"
  85. | "^"
  86. | "&"
  87. | "*"
  88. | "("
  89. | ")"
  90. | "_"
  91. | "+"
  92. | "|"
  93. | "~"
  94. | "{"
  95. | "}"
  96. | ":"
  97. | "<"
  98. | ">"
  99. | "?";
  100. type SpecialKey =
  101. | "escape"
  102. | "esc"
  103. | "enter"
  104. | "return"
  105. | "tab"
  106. | "space"
  107. | "backspace"
  108. | "delete"
  109. | "insert"
  110. | "clear"
  111. | "home"
  112. | "end"
  113. | "pageUp"
  114. | "pageDown"
  115. | "up"
  116. | "down"
  117. | "left"
  118. | "right"
  119. | "f1"
  120. | "f2"
  121. | "f3"
  122. | "f4"
  123. | "f5"
  124. | "f6"
  125. | "f7"
  126. | "f8"
  127. | "f9"
  128. | "f10"
  129. | "f11"
  130. | "f12";
  131. type BaseKey = Letter | Digit | SymbolKey | SpecialKey;
  132. type ModifierName = "ctrl" | "shift" | "alt" | "super";
  133. type ModifiedKeyId<Key extends string, RemainingModifiers extends ModifierName = ModifierName> = {
  134. [M in RemainingModifiers]: `${M}+${Key}` | `${M}+${ModifiedKeyId<Key, Exclude<RemainingModifiers, M>>}`;
  135. }[RemainingModifiers];
  136. /**
  137. * Union type of all valid key identifiers.
  138. * Provides autocomplete and catches typos at compile time.
  139. */
  140. export type KeyId = BaseKey | ModifiedKeyId<BaseKey>;
  141. /**
  142. * Helper object for creating typed key identifiers with autocomplete.
  143. *
  144. * Usage:
  145. * - Key.escape, Key.enter, Key.tab, etc. for special keys
  146. * - Key.backtick, Key.comma, Key.period, etc. for symbol keys
  147. * - Key.ctrl("c"), Key.alt("x"), Key.super("k") for single modifiers
  148. * - Key.ctrlShift("p"), Key.ctrlAlt("x"), Key.ctrlSuper("k") for combined modifiers
  149. */
  150. export const Key = {
  151. // Special keys
  152. escape: "escape" as const,
  153. esc: "esc" as const,
  154. enter: "enter" as const,
  155. return: "return" as const,
  156. tab: "tab" as const,
  157. space: "space" as const,
  158. backspace: "backspace" as const,
  159. delete: "delete" as const,
  160. insert: "insert" as const,
  161. clear: "clear" as const,
  162. home: "home" as const,
  163. end: "end" as const,
  164. pageUp: "pageUp" as const,
  165. pageDown: "pageDown" as const,
  166. up: "up" as const,
  167. down: "down" as const,
  168. left: "left" as const,
  169. right: "right" as const,
  170. f1: "f1" as const,
  171. f2: "f2" as const,
  172. f3: "f3" as const,
  173. f4: "f4" as const,
  174. f5: "f5" as const,
  175. f6: "f6" as const,
  176. f7: "f7" as const,
  177. f8: "f8" as const,
  178. f9: "f9" as const,
  179. f10: "f10" as const,
  180. f11: "f11" as const,
  181. f12: "f12" as const,
  182. // Symbol keys
  183. backtick: "`" as const,
  184. hyphen: "-" as const,
  185. equals: "=" as const,
  186. leftbracket: "[" as const,
  187. rightbracket: "]" as const,
  188. backslash: "\\" as const,
  189. semicolon: ";" as const,
  190. quote: "'" as const,
  191. comma: "," as const,
  192. period: "." as const,
  193. slash: "/" as const,
  194. exclamation: "!" as const,
  195. at: "@" as const,
  196. hash: "#" as const,
  197. dollar: "$" as const,
  198. percent: "%" as const,
  199. caret: "^" as const,
  200. ampersand: "&" as const,
  201. asterisk: "*" as const,
  202. leftparen: "(" as const,
  203. rightparen: ")" as const,
  204. underscore: "_" as const,
  205. plus: "+" as const,
  206. pipe: "|" as const,
  207. tilde: "~" as const,
  208. leftbrace: "{" as const,
  209. rightbrace: "}" as const,
  210. colon: ":" as const,
  211. lessthan: "<" as const,
  212. greaterthan: ">" as const,
  213. question: "?" as const,
  214. // Single modifiers
  215. ctrl: <K extends BaseKey>(key: K): `ctrl+${K}` => `ctrl+${key}`,
  216. shift: <K extends BaseKey>(key: K): `shift+${K}` => `shift+${key}`,
  217. alt: <K extends BaseKey>(key: K): `alt+${K}` => `alt+${key}`,
  218. super: <K extends BaseKey>(key: K): `super+${K}` => `super+${key}`,
  219. // Combined modifiers
  220. ctrlShift: <K extends BaseKey>(key: K): `ctrl+shift+${K}` => `ctrl+shift+${key}`,
  221. shiftCtrl: <K extends BaseKey>(key: K): `shift+ctrl+${K}` => `shift+ctrl+${key}`,
  222. ctrlAlt: <K extends BaseKey>(key: K): `ctrl+alt+${K}` => `ctrl+alt+${key}`,
  223. altCtrl: <K extends BaseKey>(key: K): `alt+ctrl+${K}` => `alt+ctrl+${key}`,
  224. shiftAlt: <K extends BaseKey>(key: K): `shift+alt+${K}` => `shift+alt+${key}`,
  225. altShift: <K extends BaseKey>(key: K): `alt+shift+${K}` => `alt+shift+${key}`,
  226. ctrlSuper: <K extends BaseKey>(key: K): `ctrl+super+${K}` => `ctrl+super+${key}`,
  227. superCtrl: <K extends BaseKey>(key: K): `super+ctrl+${K}` => `super+ctrl+${key}`,
  228. shiftSuper: <K extends BaseKey>(key: K): `shift+super+${K}` => `shift+super+${key}`,
  229. superShift: <K extends BaseKey>(key: K): `super+shift+${K}` => `super+shift+${key}`,
  230. altSuper: <K extends BaseKey>(key: K): `alt+super+${K}` => `alt+super+${key}`,
  231. superAlt: <K extends BaseKey>(key: K): `super+alt+${K}` => `super+alt+${key}`,
  232. // Triple modifiers
  233. ctrlShiftAlt: <K extends BaseKey>(key: K): `ctrl+shift+alt+${K}` => `ctrl+shift+alt+${key}`,
  234. ctrlShiftSuper: <K extends BaseKey>(key: K): `ctrl+shift+super+${K}` => `ctrl+shift+super+${key}`,
  235. } as const;
  236. // =============================================================================
  237. // Constants
  238. // =============================================================================
  239. const SYMBOL_KEYS = new Set([
  240. "`",
  241. "-",
  242. "=",
  243. "[",
  244. "]",
  245. "\\",
  246. ";",
  247. "'",
  248. ",",
  249. ".",
  250. "/",
  251. "!",
  252. "@",
  253. "#",
  254. "$",
  255. "%",
  256. "^",
  257. "&",
  258. "*",
  259. "(",
  260. ")",
  261. "_",
  262. "+",
  263. "|",
  264. "~",
  265. "{",
  266. "}",
  267. ":",
  268. "<",
  269. ">",
  270. "?",
  271. ]);
  272. const MODIFIERS = {
  273. shift: 1,
  274. alt: 2,
  275. ctrl: 4,
  276. super: 8,
  277. } as const;
  278. const LOCK_MASK = 64 + 128; // Caps Lock + Num Lock
  279. const CODEPOINTS = {
  280. escape: 27,
  281. tab: 9,
  282. enter: 13,
  283. space: 32,
  284. backspace: 127,
  285. kpEnter: 57414, // Numpad Enter (Kitty protocol)
  286. } as const;
  287. const ARROW_CODEPOINTS = {
  288. up: -1,
  289. down: -2,
  290. right: -3,
  291. left: -4,
  292. } as const;
  293. const FUNCTIONAL_CODEPOINTS = {
  294. delete: -10,
  295. insert: -11,
  296. pageUp: -12,
  297. pageDown: -13,
  298. home: -14,
  299. end: -15,
  300. } as const;
  301. const KITTY_FUNCTIONAL_KEY_EQUIVALENTS = new Map<number, number>([
  302. [57399, 48], // KP_0 -> 0
  303. [57400, 49], // KP_1 -> 1
  304. [57401, 50], // KP_2 -> 2
  305. [57402, 51], // KP_3 -> 3
  306. [57403, 52], // KP_4 -> 4
  307. [57404, 53], // KP_5 -> 5
  308. [57405, 54], // KP_6 -> 6
  309. [57406, 55], // KP_7 -> 7
  310. [57407, 56], // KP_8 -> 8
  311. [57408, 57], // KP_9 -> 9
  312. [57409, 46], // KP_DECIMAL -> .
  313. [57410, 47], // KP_DIVIDE -> /
  314. [57411, 42], // KP_MULTIPLY -> *
  315. [57412, 45], // KP_SUBTRACT -> -
  316. [57413, 43], // KP_ADD -> +
  317. [57415, 61], // KP_EQUAL -> =
  318. [57416, 44], // KP_SEPARATOR -> ,
  319. [57417, ARROW_CODEPOINTS.left],
  320. [57418, ARROW_CODEPOINTS.right],
  321. [57419, ARROW_CODEPOINTS.up],
  322. [57420, ARROW_CODEPOINTS.down],
  323. [57421, FUNCTIONAL_CODEPOINTS.pageUp],
  324. [57422, FUNCTIONAL_CODEPOINTS.pageDown],
  325. [57423, FUNCTIONAL_CODEPOINTS.home],
  326. [57424, FUNCTIONAL_CODEPOINTS.end],
  327. [57425, FUNCTIONAL_CODEPOINTS.insert],
  328. [57426, FUNCTIONAL_CODEPOINTS.delete],
  329. ]);
  330. function normalizeKittyFunctionalCodepoint(codepoint: number): number {
  331. return KITTY_FUNCTIONAL_KEY_EQUIVALENTS.get(codepoint) ?? codepoint;
  332. }
  333. function normalizeShiftedLetterIdentityCodepoint(codepoint: number, modifier: number): number {
  334. const effectiveModifier = modifier & ~LOCK_MASK;
  335. if ((effectiveModifier & MODIFIERS.shift) !== 0 && codepoint >= 65 && codepoint <= 90) {
  336. return codepoint + 32;
  337. }
  338. return codepoint;
  339. }
  340. const LEGACY_KEY_SEQUENCES = {
  341. up: ["\x1b[A", "\x1bOA"],
  342. down: ["\x1b[B", "\x1bOB"],
  343. right: ["\x1b[C", "\x1bOC"],
  344. left: ["\x1b[D", "\x1bOD"],
  345. home: ["\x1b[H", "\x1bOH", "\x1b[1~", "\x1b[7~"],
  346. end: ["\x1b[F", "\x1bOF", "\x1b[4~", "\x1b[8~"],
  347. insert: ["\x1b[2~"],
  348. delete: ["\x1b[3~"],
  349. pageUp: ["\x1b[5~", "\x1b[[5~"],
  350. pageDown: ["\x1b[6~", "\x1b[[6~"],
  351. clear: ["\x1b[E", "\x1bOE"],
  352. f1: ["\x1bOP", "\x1b[11~", "\x1b[[A"],
  353. f2: ["\x1bOQ", "\x1b[12~", "\x1b[[B"],
  354. f3: ["\x1bOR", "\x1b[13~", "\x1b[[C"],
  355. f4: ["\x1bOS", "\x1b[14~", "\x1b[[D"],
  356. f5: ["\x1b[15~", "\x1b[[E"],
  357. f6: ["\x1b[17~"],
  358. f7: ["\x1b[18~"],
  359. f8: ["\x1b[19~"],
  360. f9: ["\x1b[20~"],
  361. f10: ["\x1b[21~"],
  362. f11: ["\x1b[23~"],
  363. f12: ["\x1b[24~"],
  364. } as const;
  365. const LEGACY_SHIFT_SEQUENCES = {
  366. up: ["\x1b[a"],
  367. down: ["\x1b[b"],
  368. right: ["\x1b[c"],
  369. left: ["\x1b[d"],
  370. clear: ["\x1b[e"],
  371. insert: ["\x1b[2$"],
  372. delete: ["\x1b[3$"],
  373. pageUp: ["\x1b[5$"],
  374. pageDown: ["\x1b[6$"],
  375. home: ["\x1b[7$"],
  376. end: ["\x1b[8$"],
  377. } as const;
  378. const LEGACY_CTRL_SEQUENCES = {
  379. up: ["\x1bOa"],
  380. down: ["\x1bOb"],
  381. right: ["\x1bOc"],
  382. left: ["\x1bOd"],
  383. clear: ["\x1bOe"],
  384. insert: ["\x1b[2^"],
  385. delete: ["\x1b[3^"],
  386. pageUp: ["\x1b[5^"],
  387. pageDown: ["\x1b[6^"],
  388. home: ["\x1b[7^"],
  389. end: ["\x1b[8^"],
  390. } as const;
  391. const LEGACY_SEQUENCE_KEY_IDS: Record<string, KeyId> = {
  392. "\x1bOA": "up",
  393. "\x1bOB": "down",
  394. "\x1bOC": "right",
  395. "\x1bOD": "left",
  396. "\x1bOH": "home",
  397. "\x1bOF": "end",
  398. "\x1b[E": "clear",
  399. "\x1bOE": "clear",
  400. "\x1bOe": "ctrl+clear",
  401. "\x1b[e": "shift+clear",
  402. "\x1b[2~": "insert",
  403. "\x1b[2$": "shift+insert",
  404. "\x1b[2^": "ctrl+insert",
  405. "\x1b[3$": "shift+delete",
  406. "\x1b[3^": "ctrl+delete",
  407. "\x1b[[5~": "pageUp",
  408. "\x1b[[6~": "pageDown",
  409. "\x1b[a": "shift+up",
  410. "\x1b[b": "shift+down",
  411. "\x1b[c": "shift+right",
  412. "\x1b[d": "shift+left",
  413. "\x1bOa": "ctrl+up",
  414. "\x1bOb": "ctrl+down",
  415. "\x1bOc": "ctrl+right",
  416. "\x1bOd": "ctrl+left",
  417. "\x1b[5$": "shift+pageUp",
  418. "\x1b[6$": "shift+pageDown",
  419. "\x1b[7$": "shift+home",
  420. "\x1b[8$": "shift+end",
  421. "\x1b[5^": "ctrl+pageUp",
  422. "\x1b[6^": "ctrl+pageDown",
  423. "\x1b[7^": "ctrl+home",
  424. "\x1b[8^": "ctrl+end",
  425. "\x1bOP": "f1",
  426. "\x1bOQ": "f2",
  427. "\x1bOR": "f3",
  428. "\x1bOS": "f4",
  429. "\x1b[11~": "f1",
  430. "\x1b[12~": "f2",
  431. "\x1b[13~": "f3",
  432. "\x1b[14~": "f4",
  433. "\x1b[[A": "f1",
  434. "\x1b[[B": "f2",
  435. "\x1b[[C": "f3",
  436. "\x1b[[D": "f4",
  437. "\x1b[[E": "f5",
  438. "\x1b[15~": "f5",
  439. "\x1b[17~": "f6",
  440. "\x1b[18~": "f7",
  441. "\x1b[19~": "f8",
  442. "\x1b[20~": "f9",
  443. "\x1b[21~": "f10",
  444. "\x1b[23~": "f11",
  445. "\x1b[24~": "f12",
  446. "\x1bb": "alt+left",
  447. "\x1bf": "alt+right",
  448. "\x1bp": "alt+up",
  449. "\x1bn": "alt+down",
  450. } as const;
  451. type LegacyModifierKey = keyof typeof LEGACY_SHIFT_SEQUENCES;
  452. const matchesLegacySequence = (data: string, sequences: readonly string[]): boolean => sequences.includes(data);
  453. const matchesLegacyModifierSequence = (data: string, key: LegacyModifierKey, modifier: number): boolean => {
  454. if (modifier === MODIFIERS.shift) {
  455. return matchesLegacySequence(data, LEGACY_SHIFT_SEQUENCES[key]);
  456. }
  457. if (modifier === MODIFIERS.ctrl) {
  458. return matchesLegacySequence(data, LEGACY_CTRL_SEQUENCES[key]);
  459. }
  460. return false;
  461. };
  462. // =============================================================================
  463. // Kitty Protocol Parsing
  464. // =============================================================================
  465. /**
  466. * Event types from Kitty keyboard protocol (flag 2)
  467. * 1 = key press, 2 = key repeat, 3 = key release
  468. */
  469. export type KeyEventType = "press" | "repeat" | "release";
  470. interface ParsedKittySequence {
  471. codepoint: number;
  472. shiftedKey?: number; // Shifted version of the key (when shift is pressed)
  473. baseLayoutKey?: number; // Key in standard PC-101 layout (for non-Latin layouts)
  474. modifier: number;
  475. eventType: KeyEventType;
  476. }
  477. interface ParsedModifyOtherKeysSequence {
  478. codepoint: number;
  479. modifier: number;
  480. }
  481. // Store the last parsed event type for isKeyRelease() to query
  482. let _lastEventType: KeyEventType = "press";
  483. /**
  484. * Check if the last parsed key event was a key release.
  485. * Only meaningful when Kitty keyboard protocol with flag 2 is active.
  486. */
  487. export function isKeyRelease(data: string): boolean {
  488. // Don't treat bracketed paste content as key release, even if it contains
  489. // patterns like ":3F" (e.g., bluetooth MAC addresses like "90:62:3F:A5").
  490. // Terminal.ts re-wraps paste content with bracketed paste markers before
  491. // passing to TUI, so pasted data will always contain \x1b[200~.
  492. if (data.includes("\x1b[200~")) {
  493. return false;
  494. }
  495. // Quick check: release events with flag 2 contain ":3"
  496. // Format: \x1b[<codepoint>;<modifier>:3u
  497. if (
  498. data.includes(":3u") ||
  499. data.includes(":3~") ||
  500. data.includes(":3A") ||
  501. data.includes(":3B") ||
  502. data.includes(":3C") ||
  503. data.includes(":3D") ||
  504. data.includes(":3H") ||
  505. data.includes(":3F")
  506. ) {
  507. return true;
  508. }
  509. return false;
  510. }
  511. /**
  512. * Check if the last parsed key event was a key repeat.
  513. * Only meaningful when Kitty keyboard protocol with flag 2 is active.
  514. */
  515. export function isKeyRepeat(data: string): boolean {
  516. // Don't treat bracketed paste content as key repeat, even if it contains
  517. // patterns like ":2F". See isKeyRelease() for details.
  518. if (data.includes("\x1b[200~")) {
  519. return false;
  520. }
  521. if (
  522. data.includes(":2u") ||
  523. data.includes(":2~") ||
  524. data.includes(":2A") ||
  525. data.includes(":2B") ||
  526. data.includes(":2C") ||
  527. data.includes(":2D") ||
  528. data.includes(":2H") ||
  529. data.includes(":2F")
  530. ) {
  531. return true;
  532. }
  533. return false;
  534. }
  535. function parseEventType(eventTypeStr: string | undefined): KeyEventType {
  536. if (!eventTypeStr) return "press";
  537. const eventType = parseInt(eventTypeStr, 10);
  538. if (eventType === 2) return "repeat";
  539. if (eventType === 3) return "release";
  540. return "press";
  541. }
  542. function parseKittySequence(data: string): ParsedKittySequence | null {
  543. // CSI u format with alternate keys (flag 4):
  544. // \x1b[<codepoint>u
  545. // \x1b[<codepoint>;<mod>u
  546. // \x1b[<codepoint>;<mod>:<event>u
  547. // \x1b[<codepoint>:<shifted>;<mod>u
  548. // \x1b[<codepoint>:<shifted>:<base>;<mod>u
  549. // \x1b[<codepoint>::<base>;<mod>u (no shifted key, only base)
  550. //
  551. // With flag 2, event type is appended after modifier colon: 1=press, 2=repeat, 3=release
  552. // With flag 4, alternate keys are appended after codepoint with colons
  553. const csiUMatch = data.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);
  554. if (csiUMatch) {
  555. const codepoint = parseInt(csiUMatch[1]!, 10);
  556. const shiftedKey = csiUMatch[2] && csiUMatch[2].length > 0 ? parseInt(csiUMatch[2], 10) : undefined;
  557. const baseLayoutKey = csiUMatch[3] ? parseInt(csiUMatch[3], 10) : undefined;
  558. const modValue = csiUMatch[4] ? parseInt(csiUMatch[4], 10) : 1;
  559. const eventType = parseEventType(csiUMatch[5]);
  560. _lastEventType = eventType;
  561. return { codepoint, shiftedKey, baseLayoutKey, modifier: modValue - 1, eventType };
  562. }
  563. // Arrow keys with modifier: \x1b[1;<mod>A/B/C/D or \x1b[1;<mod>:<event>A/B/C/D
  564. const arrowMatch = data.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);
  565. if (arrowMatch) {
  566. const modValue = parseInt(arrowMatch[1]!, 10);
  567. const eventType = parseEventType(arrowMatch[2]);
  568. const arrowCodes: Record<string, number> = { A: -1, B: -2, C: -3, D: -4 };
  569. _lastEventType = eventType;
  570. return { codepoint: arrowCodes[arrowMatch[3]!]!, modifier: modValue - 1, eventType };
  571. }
  572. // Functional keys: \x1b[<num>~ or \x1b[<num>;<mod>~ or \x1b[<num>;<mod>:<event>~
  573. const funcMatch = data.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);
  574. if (funcMatch) {
  575. const keyNum = parseInt(funcMatch[1]!, 10);
  576. const modValue = funcMatch[2] ? parseInt(funcMatch[2], 10) : 1;
  577. const eventType = parseEventType(funcMatch[3]);
  578. const funcCodes: Record<number, number> = {
  579. 2: FUNCTIONAL_CODEPOINTS.insert,
  580. 3: FUNCTIONAL_CODEPOINTS.delete,
  581. 5: FUNCTIONAL_CODEPOINTS.pageUp,
  582. 6: FUNCTIONAL_CODEPOINTS.pageDown,
  583. 7: FUNCTIONAL_CODEPOINTS.home,
  584. 8: FUNCTIONAL_CODEPOINTS.end,
  585. };
  586. const codepoint = funcCodes[keyNum];
  587. if (codepoint !== undefined) {
  588. _lastEventType = eventType;
  589. return { codepoint, modifier: modValue - 1, eventType };
  590. }
  591. }
  592. // Home/End with modifier: \x1b[1;<mod>H/F or \x1b[1;<mod>:<event>H/F
  593. const homeEndMatch = data.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);
  594. if (homeEndMatch) {
  595. const modValue = parseInt(homeEndMatch[1]!, 10);
  596. const eventType = parseEventType(homeEndMatch[2]);
  597. const codepoint = homeEndMatch[3] === "H" ? FUNCTIONAL_CODEPOINTS.home : FUNCTIONAL_CODEPOINTS.end;
  598. _lastEventType = eventType;
  599. return { codepoint, modifier: modValue - 1, eventType };
  600. }
  601. return null;
  602. }
  603. function matchesKittySequence(data: string, expectedCodepoint: number, expectedModifier: number): boolean {
  604. const parsed = parseKittySequence(data);
  605. if (!parsed) return false;
  606. const actualMod = parsed.modifier & ~LOCK_MASK;
  607. const expectedMod = expectedModifier & ~LOCK_MASK;
  608. // Check if modifiers match
  609. if (actualMod !== expectedMod) return false;
  610. const normalizedCodepoint = normalizeShiftedLetterIdentityCodepoint(
  611. normalizeKittyFunctionalCodepoint(parsed.codepoint),
  612. parsed.modifier,
  613. );
  614. const normalizedExpectedCodepoint = normalizeShiftedLetterIdentityCodepoint(
  615. normalizeKittyFunctionalCodepoint(expectedCodepoint),
  616. expectedModifier,
  617. );
  618. // Primary match: codepoint matches directly after normalizing functional keys
  619. if (normalizedCodepoint === normalizedExpectedCodepoint) return true;
  620. // Alternate match: use base layout key for non-Latin keyboard layouts.
  621. // This allows Ctrl+С (Cyrillic) to match Ctrl+c (Latin) when terminal reports
  622. // the base layout key (the key in standard PC-101 layout).
  623. //
  624. // Only fall back to base layout key when the codepoint is NOT already a
  625. // recognized Latin letter (a-z) or symbol (e.g., /, -, [, ;, etc.).
  626. // When the codepoint is a recognized key, it is authoritative regardless
  627. // of physical key position. This prevents remapped layouts (Dvorak, Colemak,
  628. // xremap, etc.) from causing false matches: both letters and symbols move
  629. // to different physical positions, so Ctrl+K could falsely match Ctrl+V
  630. // (letter remapping) and Ctrl+/ could falsely match Ctrl+[ (symbol remapping)
  631. // if the base layout key were always considered.
  632. if (parsed.baseLayoutKey !== undefined && parsed.baseLayoutKey === expectedCodepoint) {
  633. const cp = normalizedCodepoint;
  634. const isLatinLetter = cp >= 97 && cp <= 122; // a-z
  635. const isKnownSymbol = SYMBOL_KEYS.has(String.fromCharCode(cp));
  636. if (!isLatinLetter && !isKnownSymbol) return true;
  637. }
  638. return false;
  639. }
  640. function parseModifyOtherKeysSequence(data: string): ParsedModifyOtherKeysSequence | null {
  641. const match = data.match(/^\x1b\[27;(\d+);(\d+)~$/);
  642. if (!match) return null;
  643. const modValue = parseInt(match[1]!, 10);
  644. const codepoint = parseInt(match[2]!, 10);
  645. return { codepoint, modifier: modValue - 1 };
  646. }
  647. /**
  648. * Match xterm modifyOtherKeys format: CSI 27 ; modifiers ; keycode ~
  649. * This is used by terminals when Kitty protocol is not enabled.
  650. * Modifier values are 1-indexed: 2=shift, 3=alt, 5=ctrl, etc.
  651. */
  652. function matchesModifyOtherKeys(data: string, expectedKeycode: number, expectedModifier: number): boolean {
  653. const parsed = parseModifyOtherKeysSequence(data);
  654. if (!parsed) return false;
  655. return parsed.codepoint === expectedKeycode && parsed.modifier === expectedModifier;
  656. }
  657. function isWindowsTerminalSession(): boolean {
  658. return (
  659. Boolean(process.env.WT_SESSION) && !process.env.SSH_CONNECTION && !process.env.SSH_CLIENT && !process.env.SSH_TTY
  660. );
  661. }
  662. /**
  663. * Raw 0x08 (BS) is ambiguous in legacy terminals.
  664. *
  665. * - Windows Terminal uses it for Ctrl+Backspace.
  666. * - Some legacy terminals and tmux setups send it for plain Backspace.
  667. *
  668. * Prefer explicit Kitty / CSI-u / modifyOtherKeys sequences whenever they are
  669. * available. Fall back to a Windows Terminal heuristic only for raw BS bytes.
  670. */
  671. function matchesRawBackspace(data: string, expectedModifier: number): boolean {
  672. if (data === "\x7f") return expectedModifier === 0;
  673. if (data !== "\x08") return false;
  674. return isWindowsTerminalSession() ? expectedModifier === MODIFIERS.ctrl : expectedModifier === 0;
  675. }
  676. // =============================================================================
  677. // Generic Key Matching
  678. // =============================================================================
  679. /**
  680. * Get the control character for a key.
  681. * Uses the universal formula: code & 0x1f (mask to lower 5 bits)
  682. *
  683. * Works for:
  684. * - Letters a-z → 1-26
  685. * - Symbols [\]_ → 27, 28, 29, 31
  686. * - Also maps - to same as _ (same physical key on US keyboards)
  687. */
  688. function rawCtrlChar(key: string): string | null {
  689. const char = key.toLowerCase();
  690. const code = char.charCodeAt(0);
  691. if ((code >= 97 && code <= 122) || char === "[" || char === "\\" || char === "]" || char === "_") {
  692. return String.fromCharCode(code & 0x1f);
  693. }
  694. // Handle - as _ (same physical key on US keyboards)
  695. if (char === "-") {
  696. return String.fromCharCode(31); // Same as Ctrl+_
  697. }
  698. return null;
  699. }
  700. function isDigitKey(key: string): boolean {
  701. return key >= "0" && key <= "9";
  702. }
  703. function matchesPrintableModifyOtherKeys(data: string, expectedKeycode: number, expectedModifier: number): boolean {
  704. if (expectedModifier === 0) return false;
  705. const parsed = parseModifyOtherKeysSequence(data);
  706. if (!parsed || parsed.modifier !== expectedModifier) return false;
  707. return (
  708. normalizeShiftedLetterIdentityCodepoint(parsed.codepoint, parsed.modifier) ===
  709. normalizeShiftedLetterIdentityCodepoint(expectedKeycode, expectedModifier)
  710. );
  711. }
  712. function formatKeyNameWithModifiers(keyName: string, modifier: number): string | undefined {
  713. const mods: string[] = [];
  714. const effectiveMod = modifier & ~LOCK_MASK;
  715. const supportedModifierMask = MODIFIERS.shift | MODIFIERS.ctrl | MODIFIERS.alt | MODIFIERS.super;
  716. if ((effectiveMod & ~supportedModifierMask) !== 0) return undefined;
  717. if (effectiveMod & MODIFIERS.shift) mods.push("shift");
  718. if (effectiveMod & MODIFIERS.ctrl) mods.push("ctrl");
  719. if (effectiveMod & MODIFIERS.alt) mods.push("alt");
  720. if (effectiveMod & MODIFIERS.super) mods.push("super");
  721. return mods.length > 0 ? `${mods.join("+")}+${keyName}` : keyName;
  722. }
  723. function parseKeyId(
  724. keyId: string,
  725. ): { key: string; ctrl: boolean; shift: boolean; alt: boolean; super: boolean } | null {
  726. const parts = keyId.toLowerCase().split("+");
  727. const key = parts[parts.length - 1];
  728. if (!key) return null;
  729. return {
  730. key,
  731. ctrl: parts.includes("ctrl"),
  732. shift: parts.includes("shift"),
  733. alt: parts.includes("alt"),
  734. super: parts.includes("super"),
  735. };
  736. }
  737. /**
  738. * Match input data against a key identifier string.
  739. *
  740. * Supported key identifiers:
  741. * - Single keys: "escape", "tab", "enter", "backspace", "delete", "home", "end", "space"
  742. * - Arrow keys: "up", "down", "left", "right"
  743. * - Ctrl combinations: "ctrl+c", "ctrl+z", etc.
  744. * - Shift combinations: "shift+tab", "shift+enter"
  745. * - Alt combinations: "alt+enter", "alt+backspace"
  746. * - Super combinations: "super+k", "super+enter"
  747. * - Combined modifiers: "shift+ctrl+p", "ctrl+alt+x", "ctrl+super+k"
  748. *
  749. * Use the Key helper for autocomplete: Key.ctrl("c"), Key.escape, Key.ctrlShift("p"), Key.super("k")
  750. *
  751. * @param data - Raw input data from terminal
  752. * @param keyId - Key identifier (e.g., "ctrl+c", "escape", Key.ctrl("c"))
  753. */
  754. export function matchesKey(data: string, keyId: KeyId): boolean {
  755. const parsed = parseKeyId(keyId);
  756. if (!parsed) return false;
  757. const { key, ctrl, shift, alt, super: superModifier } = parsed;
  758. let modifier = 0;
  759. if (shift) modifier |= MODIFIERS.shift;
  760. if (alt) modifier |= MODIFIERS.alt;
  761. if (ctrl) modifier |= MODIFIERS.ctrl;
  762. if (superModifier) modifier |= MODIFIERS.super;
  763. switch (key) {
  764. case "escape":
  765. case "esc":
  766. if (modifier !== 0) return false;
  767. return (
  768. data === "\x1b" ||
  769. matchesKittySequence(data, CODEPOINTS.escape, 0) ||
  770. matchesModifyOtherKeys(data, CODEPOINTS.escape, 0)
  771. );
  772. case "space":
  773. if (!_kittyProtocolActive) {
  774. if (modifier === MODIFIERS.ctrl && data === "\x00") {
  775. return true;
  776. }
  777. if (modifier === MODIFIERS.alt && data === "\x1b ") {
  778. return true;
  779. }
  780. }
  781. if (modifier === 0) {
  782. return (
  783. data === " " ||
  784. matchesKittySequence(data, CODEPOINTS.space, 0) ||
  785. matchesModifyOtherKeys(data, CODEPOINTS.space, 0)
  786. );
  787. }
  788. return (
  789. matchesKittySequence(data, CODEPOINTS.space, modifier) ||
  790. matchesModifyOtherKeys(data, CODEPOINTS.space, modifier)
  791. );
  792. case "tab":
  793. if (modifier === MODIFIERS.shift) {
  794. return (
  795. data === "\x1b[Z" ||
  796. matchesKittySequence(data, CODEPOINTS.tab, MODIFIERS.shift) ||
  797. matchesModifyOtherKeys(data, CODEPOINTS.tab, MODIFIERS.shift)
  798. );
  799. }
  800. if (modifier === 0) {
  801. return data === "\t" || matchesKittySequence(data, CODEPOINTS.tab, 0);
  802. }
  803. return (
  804. matchesKittySequence(data, CODEPOINTS.tab, modifier) ||
  805. matchesModifyOtherKeys(data, CODEPOINTS.tab, modifier)
  806. );
  807. case "enter":
  808. case "return":
  809. if (modifier === MODIFIERS.shift) {
  810. // CSI u sequences (standard Kitty protocol)
  811. if (
  812. matchesKittySequence(data, CODEPOINTS.enter, MODIFIERS.shift) ||
  813. matchesKittySequence(data, CODEPOINTS.kpEnter, MODIFIERS.shift)
  814. ) {
  815. return true;
  816. }
  817. // xterm modifyOtherKeys format (fallback when Kitty protocol not enabled)
  818. if (matchesModifyOtherKeys(data, CODEPOINTS.enter, MODIFIERS.shift)) {
  819. return true;
  820. }
  821. // When Kitty protocol is active, legacy sequences are custom terminal mappings
  822. // \x1b\r = Kitty's "map shift+enter send_text all \e\r"
  823. // \n = Ghostty's "keybind = shift+enter=text:\n"
  824. if (_kittyProtocolActive) {
  825. return data === "\x1b\r" || data === "\n";
  826. }
  827. return false;
  828. }
  829. if (modifier === MODIFIERS.alt) {
  830. // CSI u sequences (standard Kitty protocol)
  831. if (
  832. matchesKittySequence(data, CODEPOINTS.enter, MODIFIERS.alt) ||
  833. matchesKittySequence(data, CODEPOINTS.kpEnter, MODIFIERS.alt)
  834. ) {
  835. return true;
  836. }
  837. // xterm modifyOtherKeys format (fallback when Kitty protocol not enabled)
  838. if (matchesModifyOtherKeys(data, CODEPOINTS.enter, MODIFIERS.alt)) {
  839. return true;
  840. }
  841. // \x1b\r is alt+enter only in legacy mode (no Kitty protocol)
  842. // When Kitty protocol is active, alt+enter comes as CSI u sequence
  843. if (!_kittyProtocolActive) {
  844. return data === "\x1b\r";
  845. }
  846. return false;
  847. }
  848. if (modifier === 0) {
  849. return (
  850. data === "\r" ||
  851. (!_kittyProtocolActive && data === "\n") ||
  852. data === "\x1bOM" || // SS3 M (numpad enter in some terminals)
  853. matchesKittySequence(data, CODEPOINTS.enter, 0) ||
  854. matchesKittySequence(data, CODEPOINTS.kpEnter, 0)
  855. );
  856. }
  857. return (
  858. matchesKittySequence(data, CODEPOINTS.enter, modifier) ||
  859. matchesKittySequence(data, CODEPOINTS.kpEnter, modifier) ||
  860. matchesModifyOtherKeys(data, CODEPOINTS.enter, modifier)
  861. );
  862. case "backspace":
  863. if (modifier === MODIFIERS.alt) {
  864. if (data === "\x1b\x7f" || data === "\x1b\b") {
  865. return true;
  866. }
  867. return (
  868. matchesKittySequence(data, CODEPOINTS.backspace, MODIFIERS.alt) ||
  869. matchesModifyOtherKeys(data, CODEPOINTS.backspace, MODIFIERS.alt)
  870. );
  871. }
  872. if (modifier === MODIFIERS.ctrl) {
  873. // Legacy raw 0x08 is ambiguous: it can be Ctrl+Backspace on Windows
  874. // Terminal or plain Backspace on other terminals, while also
  875. // overlapping with Ctrl+H.
  876. if (matchesRawBackspace(data, MODIFIERS.ctrl)) return true;
  877. return (
  878. matchesKittySequence(data, CODEPOINTS.backspace, MODIFIERS.ctrl) ||
  879. matchesModifyOtherKeys(data, CODEPOINTS.backspace, MODIFIERS.ctrl)
  880. );
  881. }
  882. if (modifier === 0) {
  883. return (
  884. matchesRawBackspace(data, 0) ||
  885. matchesKittySequence(data, CODEPOINTS.backspace, 0) ||
  886. matchesModifyOtherKeys(data, CODEPOINTS.backspace, 0)
  887. );
  888. }
  889. return (
  890. matchesKittySequence(data, CODEPOINTS.backspace, modifier) ||
  891. matchesModifyOtherKeys(data, CODEPOINTS.backspace, modifier)
  892. );
  893. case "insert":
  894. if (modifier === 0) {
  895. return (
  896. matchesLegacySequence(data, LEGACY_KEY_SEQUENCES.insert) ||
  897. matchesKittySequence(data, FUNCTIONAL_CODEPOINTS.insert, 0)
  898. );
  899. }
  900. if (matchesLegacyModifierSequence(data, "insert", modifier)) {
  901. return true;
  902. }
  903. return matchesKittySequence(data, FUNCTIONAL_CODEPOINTS.insert, modifier);
  904. case "delete":
  905. if (modifier === 0) {
  906. return (
  907. matchesLegacySequence(data, LEGACY_KEY_SEQUENCES.delete) ||
  908. matchesKittySequence(data, FUNCTIONAL_CODEPOINTS.delete, 0)
  909. );
  910. }
  911. if (matchesLegacyModifierSequence(data, "delete", modifier)) {
  912. return true;
  913. }
  914. return matchesKittySequence(data, FUNCTIONAL_CODEPOINTS.delete, modifier);
  915. case "clear":
  916. if (modifier === 0) {
  917. return matchesLegacySequence(data, LEGACY_KEY_SEQUENCES.clear);
  918. }
  919. return matchesLegacyModifierSequence(data, "clear", modifier);
  920. case "home":
  921. if (modifier === 0) {
  922. return (
  923. matchesLegacySequence(data, LEGACY_KEY_SEQUENCES.home) ||
  924. matchesKittySequence(data, FUNCTIONAL_CODEPOINTS.home, 0)
  925. );
  926. }
  927. if (matchesLegacyModifierSequence(data, "home", modifier)) {
  928. return true;
  929. }
  930. return matchesKittySequence(data, FUNCTIONAL_CODEPOINTS.home, modifier);
  931. case "end":
  932. if (modifier === 0) {
  933. return (
  934. matchesLegacySequence(data, LEGACY_KEY_SEQUENCES.end) ||
  935. matchesKittySequence(data, FUNCTIONAL_CODEPOINTS.end, 0)
  936. );
  937. }
  938. if (matchesLegacyModifierSequence(data, "end", modifier)) {
  939. return true;
  940. }
  941. return matchesKittySequence(data, FUNCTIONAL_CODEPOINTS.end, modifier);
  942. case "pageup":
  943. if (modifier === 0) {
  944. return (
  945. matchesLegacySequence(data, LEGACY_KEY_SEQUENCES.pageUp) ||
  946. matchesKittySequence(data, FUNCTIONAL_CODEPOINTS.pageUp, 0)
  947. );
  948. }
  949. if (matchesLegacyModifierSequence(data, "pageUp", modifier)) {
  950. return true;
  951. }
  952. return matchesKittySequence(data, FUNCTIONAL_CODEPOINTS.pageUp, modifier);
  953. case "pagedown":
  954. if (modifier === 0) {
  955. return (
  956. matchesLegacySequence(data, LEGACY_KEY_SEQUENCES.pageDown) ||
  957. matchesKittySequence(data, FUNCTIONAL_CODEPOINTS.pageDown, 0)
  958. );
  959. }
  960. if (matchesLegacyModifierSequence(data, "pageDown", modifier)) {
  961. return true;
  962. }
  963. return matchesKittySequence(data, FUNCTIONAL_CODEPOINTS.pageDown, modifier);
  964. case "up":
  965. if (modifier === MODIFIERS.alt) {
  966. return data === "\x1bp" || matchesKittySequence(data, ARROW_CODEPOINTS.up, MODIFIERS.alt);
  967. }
  968. if (modifier === 0) {
  969. return (
  970. matchesLegacySequence(data, LEGACY_KEY_SEQUENCES.up) ||
  971. matchesKittySequence(data, ARROW_CODEPOINTS.up, 0)
  972. );
  973. }
  974. if (matchesLegacyModifierSequence(data, "up", modifier)) {
  975. return true;
  976. }
  977. return matchesKittySequence(data, ARROW_CODEPOINTS.up, modifier);
  978. case "down":
  979. if (modifier === MODIFIERS.alt) {
  980. return data === "\x1bn" || matchesKittySequence(data, ARROW_CODEPOINTS.down, MODIFIERS.alt);
  981. }
  982. if (modifier === 0) {
  983. return (
  984. matchesLegacySequence(data, LEGACY_KEY_SEQUENCES.down) ||
  985. matchesKittySequence(data, ARROW_CODEPOINTS.down, 0)
  986. );
  987. }
  988. if (matchesLegacyModifierSequence(data, "down", modifier)) {
  989. return true;
  990. }
  991. return matchesKittySequence(data, ARROW_CODEPOINTS.down, modifier);
  992. case "left":
  993. if (modifier === MODIFIERS.alt) {
  994. return (
  995. data === "\x1b[1;3D" ||
  996. (!_kittyProtocolActive && data === "\x1bB") ||
  997. data === "\x1bb" ||
  998. matchesKittySequence(data, ARROW_CODEPOINTS.left, MODIFIERS.alt)
  999. );
  1000. }
  1001. if (modifier === MODIFIERS.ctrl) {
  1002. return (
  1003. data === "\x1b[1;5D" ||
  1004. matchesLegacyModifierSequence(data, "left", MODIFIERS.ctrl) ||
  1005. matchesKittySequence(data, ARROW_CODEPOINTS.left, MODIFIERS.ctrl)
  1006. );
  1007. }
  1008. if (modifier === 0) {
  1009. return (
  1010. matchesLegacySequence(data, LEGACY_KEY_SEQUENCES.left) ||
  1011. matchesKittySequence(data, ARROW_CODEPOINTS.left, 0)
  1012. );
  1013. }
  1014. if (matchesLegacyModifierSequence(data, "left", modifier)) {
  1015. return true;
  1016. }
  1017. return matchesKittySequence(data, ARROW_CODEPOINTS.left, modifier);
  1018. case "right":
  1019. if (modifier === MODIFIERS.alt) {
  1020. return (
  1021. data === "\x1b[1;3C" ||
  1022. (!_kittyProtocolActive && data === "\x1bF") ||
  1023. data === "\x1bf" ||
  1024. matchesKittySequence(data, ARROW_CODEPOINTS.right, MODIFIERS.alt)
  1025. );
  1026. }
  1027. if (modifier === MODIFIERS.ctrl) {
  1028. return (
  1029. data === "\x1b[1;5C" ||
  1030. matchesLegacyModifierSequence(data, "right", MODIFIERS.ctrl) ||
  1031. matchesKittySequence(data, ARROW_CODEPOINTS.right, MODIFIERS.ctrl)
  1032. );
  1033. }
  1034. if (modifier === 0) {
  1035. return (
  1036. matchesLegacySequence(data, LEGACY_KEY_SEQUENCES.right) ||
  1037. matchesKittySequence(data, ARROW_CODEPOINTS.right, 0)
  1038. );
  1039. }
  1040. if (matchesLegacyModifierSequence(data, "right", modifier)) {
  1041. return true;
  1042. }
  1043. return matchesKittySequence(data, ARROW_CODEPOINTS.right, modifier);
  1044. case "f1":
  1045. case "f2":
  1046. case "f3":
  1047. case "f4":
  1048. case "f5":
  1049. case "f6":
  1050. case "f7":
  1051. case "f8":
  1052. case "f9":
  1053. case "f10":
  1054. case "f11":
  1055. case "f12": {
  1056. if (modifier !== 0) {
  1057. return false;
  1058. }
  1059. const functionKey = key as keyof typeof LEGACY_KEY_SEQUENCES;
  1060. return matchesLegacySequence(data, LEGACY_KEY_SEQUENCES[functionKey]);
  1061. }
  1062. }
  1063. // Handle single letter/digit keys and symbols
  1064. if (key.length === 1 && ((key >= "a" && key <= "z") || isDigitKey(key) || SYMBOL_KEYS.has(key))) {
  1065. const codepoint = key.charCodeAt(0);
  1066. const rawCtrl = rawCtrlChar(key);
  1067. const isLetter = key >= "a" && key <= "z";
  1068. const isDigit = isDigitKey(key);
  1069. if (modifier === MODIFIERS.ctrl + MODIFIERS.alt && !_kittyProtocolActive && rawCtrl) {
  1070. // Legacy: ctrl+alt+key is ESC followed by the control character.
  1071. // If that legacy form does not match, continue so CSI-u and
  1072. // modifyOtherKeys sequences from tmux can still be recognized.
  1073. if (data === `\x1b${rawCtrl}`) return true;
  1074. }
  1075. if (modifier === MODIFIERS.alt && !_kittyProtocolActive && (isLetter || isDigit)) {
  1076. // Legacy: alt+letter/digit is ESC followed by the key
  1077. if (data === `\x1b${key}`) return true;
  1078. }
  1079. if (modifier === MODIFIERS.ctrl) {
  1080. // Legacy: ctrl+key sends the control character
  1081. if (rawCtrl && data === rawCtrl) return true;
  1082. return (
  1083. matchesKittySequence(data, codepoint, MODIFIERS.ctrl) ||
  1084. matchesPrintableModifyOtherKeys(data, codepoint, MODIFIERS.ctrl)
  1085. );
  1086. }
  1087. if (modifier === MODIFIERS.shift + MODIFIERS.ctrl) {
  1088. return (
  1089. matchesKittySequence(data, codepoint, MODIFIERS.shift + MODIFIERS.ctrl) ||
  1090. matchesPrintableModifyOtherKeys(data, codepoint, MODIFIERS.shift + MODIFIERS.ctrl)
  1091. );
  1092. }
  1093. if (modifier === MODIFIERS.shift) {
  1094. // Legacy: shift+letter produces uppercase
  1095. if (isLetter && data === key.toUpperCase()) return true;
  1096. return (
  1097. matchesKittySequence(data, codepoint, MODIFIERS.shift) ||
  1098. matchesPrintableModifyOtherKeys(data, codepoint, MODIFIERS.shift)
  1099. );
  1100. }
  1101. if (modifier !== 0) {
  1102. return (
  1103. matchesKittySequence(data, codepoint, modifier) ||
  1104. matchesPrintableModifyOtherKeys(data, codepoint, modifier)
  1105. );
  1106. }
  1107. // Check both raw char and Kitty sequence (needed for release events)
  1108. return data === key || matchesKittySequence(data, codepoint, 0);
  1109. }
  1110. return false;
  1111. }
  1112. /**
  1113. * Parse input data and return the key identifier if recognized.
  1114. *
  1115. * @param data - Raw input data from terminal
  1116. * @returns Key identifier string (e.g., "ctrl+c") or undefined
  1117. */
  1118. function formatParsedKey(codepoint: number, modifier: number, baseLayoutKey?: number): string | undefined {
  1119. const normalizedCodepoint = normalizeKittyFunctionalCodepoint(codepoint);
  1120. const identityCodepoint = normalizeShiftedLetterIdentityCodepoint(normalizedCodepoint, modifier);
  1121. // Use base layout key only when codepoint is not a recognized Latin
  1122. // letter (a-z), digit (0-9), or symbol (/, -, [, ;, etc.). For those,
  1123. // the codepoint is authoritative regardless of physical key position.
  1124. // This prevents remapped layouts (Dvorak, Colemak, xremap, etc.) from
  1125. // reporting the wrong key name based on the QWERTY physical position.
  1126. const isLatinLetter = identityCodepoint >= 97 && identityCodepoint <= 122; // a-z
  1127. const isDigit = identityCodepoint >= 48 && identityCodepoint <= 57; // 0-9
  1128. const isKnownSymbol = SYMBOL_KEYS.has(String.fromCharCode(identityCodepoint));
  1129. const effectiveCodepoint =
  1130. isLatinLetter || isDigit || isKnownSymbol ? identityCodepoint : (baseLayoutKey ?? identityCodepoint);
  1131. let keyName: string | undefined;
  1132. if (effectiveCodepoint === CODEPOINTS.escape) keyName = "escape";
  1133. else if (effectiveCodepoint === CODEPOINTS.tab) keyName = "tab";
  1134. else if (effectiveCodepoint === CODEPOINTS.enter || effectiveCodepoint === CODEPOINTS.kpEnter) keyName = "enter";
  1135. else if (effectiveCodepoint === CODEPOINTS.space) keyName = "space";
  1136. else if (effectiveCodepoint === CODEPOINTS.backspace) keyName = "backspace";
  1137. else if (effectiveCodepoint === FUNCTIONAL_CODEPOINTS.delete) keyName = "delete";
  1138. else if (effectiveCodepoint === FUNCTIONAL_CODEPOINTS.insert) keyName = "insert";
  1139. else if (effectiveCodepoint === FUNCTIONAL_CODEPOINTS.home) keyName = "home";
  1140. else if (effectiveCodepoint === FUNCTIONAL_CODEPOINTS.end) keyName = "end";
  1141. else if (effectiveCodepoint === FUNCTIONAL_CODEPOINTS.pageUp) keyName = "pageUp";
  1142. else if (effectiveCodepoint === FUNCTIONAL_CODEPOINTS.pageDown) keyName = "pageDown";
  1143. else if (effectiveCodepoint === ARROW_CODEPOINTS.up) keyName = "up";
  1144. else if (effectiveCodepoint === ARROW_CODEPOINTS.down) keyName = "down";
  1145. else if (effectiveCodepoint === ARROW_CODEPOINTS.left) keyName = "left";
  1146. else if (effectiveCodepoint === ARROW_CODEPOINTS.right) keyName = "right";
  1147. else if (effectiveCodepoint >= 48 && effectiveCodepoint <= 57) keyName = String.fromCharCode(effectiveCodepoint);
  1148. else if (effectiveCodepoint >= 97 && effectiveCodepoint <= 122) keyName = String.fromCharCode(effectiveCodepoint);
  1149. else if (SYMBOL_KEYS.has(String.fromCharCode(effectiveCodepoint))) keyName = String.fromCharCode(effectiveCodepoint);
  1150. if (!keyName) return undefined;
  1151. return formatKeyNameWithModifiers(keyName, modifier);
  1152. }
  1153. export function parseKey(data: string): string | undefined {
  1154. const kitty = parseKittySequence(data);
  1155. if (kitty) {
  1156. return formatParsedKey(kitty.codepoint, kitty.modifier, kitty.baseLayoutKey);
  1157. }
  1158. const modifyOtherKeys = parseModifyOtherKeysSequence(data);
  1159. if (modifyOtherKeys) {
  1160. return formatParsedKey(modifyOtherKeys.codepoint, modifyOtherKeys.modifier);
  1161. }
  1162. // Mode-aware legacy sequences
  1163. // When Kitty protocol is active, ambiguous sequences are interpreted as custom terminal mappings:
  1164. // - \x1b\r = shift+enter (Kitty mapping), not alt+enter
  1165. // - \n = shift+enter (Ghostty mapping)
  1166. if (_kittyProtocolActive) {
  1167. if (data === "\x1b\r" || data === "\n") return "shift+enter";
  1168. }
  1169. const legacySequenceKeyId = LEGACY_SEQUENCE_KEY_IDS[data];
  1170. if (legacySequenceKeyId) return legacySequenceKeyId;
  1171. // Legacy sequences (used when Kitty protocol is not active, or for unambiguous sequences)
  1172. if (data === "\x1b") return "escape";
  1173. if (data === "\x1c") return "ctrl+\\";
  1174. if (data === "\x1d") return "ctrl+]";
  1175. if (data === "\x1f") return "ctrl+-";
  1176. if (data === "\x1b\x1b") return "ctrl+alt+[";
  1177. if (data === "\x1b\x1c") return "ctrl+alt+\\";
  1178. if (data === "\x1b\x1d") return "ctrl+alt+]";
  1179. if (data === "\x1b\x1f") return "ctrl+alt+-";
  1180. if (data === "\t") return "tab";
  1181. if (data === "\r" || (!_kittyProtocolActive && data === "\n") || data === "\x1bOM") return "enter";
  1182. if (data === "\x00") return "ctrl+space";
  1183. if (data === " ") return "space";
  1184. if (data === "\x7f") return "backspace";
  1185. if (data === "\x08") return isWindowsTerminalSession() ? "ctrl+backspace" : "backspace";
  1186. if (data === "\x1b[Z") return "shift+tab";
  1187. if (!_kittyProtocolActive && data === "\x1b\r") return "alt+enter";
  1188. if (!_kittyProtocolActive && data === "\x1b ") return "alt+space";
  1189. if (data === "\x1b\x7f" || data === "\x1b\b") return "alt+backspace";
  1190. if (!_kittyProtocolActive && data === "\x1bB") return "alt+left";
  1191. if (!_kittyProtocolActive && data === "\x1bF") return "alt+right";
  1192. if (!_kittyProtocolActive && data.length === 2 && data[0] === "\x1b") {
  1193. const code = data.charCodeAt(1);
  1194. if (code >= 1 && code <= 26) {
  1195. return `ctrl+alt+${String.fromCharCode(code + 96)}`;
  1196. }
  1197. // Legacy alt+letter/digit (ESC followed by the key)
  1198. if ((code >= 97 && code <= 122) || (code >= 48 && code <= 57)) {
  1199. return `alt+${String.fromCharCode(code)}`;
  1200. }
  1201. }
  1202. if (data === "\x1b[A") return "up";
  1203. if (data === "\x1b[B") return "down";
  1204. if (data === "\x1b[C") return "right";
  1205. if (data === "\x1b[D") return "left";
  1206. if (data === "\x1b[H" || data === "\x1bOH") return "home";
  1207. if (data === "\x1b[F" || data === "\x1bOF") return "end";
  1208. if (data === "\x1b[3~") return "delete";
  1209. if (data === "\x1b[5~") return "pageUp";
  1210. if (data === "\x1b[6~") return "pageDown";
  1211. // Raw Ctrl+letter
  1212. if (data.length === 1) {
  1213. const code = data.charCodeAt(0);
  1214. if (code >= 1 && code <= 26) {
  1215. return `ctrl+${String.fromCharCode(code + 96)}`;
  1216. }
  1217. if (code >= 32 && code <= 126) {
  1218. return data;
  1219. }
  1220. }
  1221. return undefined;
  1222. }
  1223. // =============================================================================
  1224. // Kitty CSI-u Printable Decoding
  1225. // =============================================================================
  1226. const KITTY_CSI_U_REGEX = /^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/;
  1227. const KITTY_PRINTABLE_ALLOWED_MODIFIERS = MODIFIERS.shift | LOCK_MASK;
  1228. /**
  1229. * Decode a Kitty CSI-u sequence into a printable character, if applicable.
  1230. *
  1231. * When Kitty keyboard protocol flag 1 (disambiguate) is active, terminals send
  1232. * CSI-u sequences for all keys, including plain printable characters. This
  1233. * function extracts the printable character from such sequences.
  1234. *
  1235. * Only accepts plain or Shift-modified keys. Rejects Ctrl, Alt, and unsupported
  1236. * modifier combinations (those are handled by keybinding matching instead).
  1237. * Prefers the shifted keycode when Shift is held and a shifted key is reported.
  1238. *
  1239. * @param data - Raw input data from terminal
  1240. * @returns The printable character, or undefined if not a printable CSI-u sequence
  1241. */
  1242. export function decodeKittyPrintable(data: string): string | undefined {
  1243. const match = data.match(KITTY_CSI_U_REGEX);
  1244. if (!match) return undefined;
  1245. // CSI-u groups: <codepoint>[:<shifted>[:<base>]];<mod>[:<event>]u
  1246. const codepoint = Number.parseInt(match[1] ?? "", 10);
  1247. if (!Number.isFinite(codepoint)) return undefined;
  1248. const shiftedKey = match[2] && match[2].length > 0 ? Number.parseInt(match[2], 10) : undefined;
  1249. const modValue = match[4] ? Number.parseInt(match[4], 10) : 1;
  1250. // Modifiers are 1-indexed in CSI-u; normalize to our bitmask.
  1251. const modifier = Number.isFinite(modValue) ? modValue - 1 : 0;
  1252. // Only accept printable CSI-u input for plain or Shift-modified text keys.
  1253. // Reject unsupported modifier bits (e.g. Super/Meta) to avoid inserting
  1254. // characters from modifier-only terminal events.
  1255. if ((modifier & ~KITTY_PRINTABLE_ALLOWED_MODIFIERS) !== 0) return undefined;
  1256. if (modifier & (MODIFIERS.alt | MODIFIERS.ctrl)) return undefined;
  1257. // Prefer the shifted keycode when Shift is held.
  1258. let effectiveCodepoint = codepoint;
  1259. if (modifier & MODIFIERS.shift && typeof shiftedKey === "number") {
  1260. effectiveCodepoint = shiftedKey;
  1261. }
  1262. effectiveCodepoint = normalizeKittyFunctionalCodepoint(effectiveCodepoint);
  1263. // Drop control characters or invalid codepoints.
  1264. if (!Number.isFinite(effectiveCodepoint) || effectiveCodepoint < 32) return undefined;
  1265. try {
  1266. return String.fromCodePoint(effectiveCodepoint);
  1267. } catch {
  1268. return undefined;
  1269. }
  1270. }
  1271. function decodeModifyOtherKeysPrintable(data: string): string | undefined {
  1272. const parsed = parseModifyOtherKeysSequence(data);
  1273. if (!parsed) return undefined;
  1274. const modifier = parsed.modifier & ~LOCK_MASK;
  1275. if ((modifier & ~MODIFIERS.shift) !== 0) return undefined;
  1276. if (!Number.isFinite(parsed.codepoint) || parsed.codepoint < 32) return undefined;
  1277. try {
  1278. return String.fromCodePoint(parsed.codepoint);
  1279. } catch {
  1280. return undefined;
  1281. }
  1282. }
  1283. export function decodePrintableKey(data: string): string | undefined {
  1284. return decodeKittyPrintable(data) ?? decodeModifyOtherKeysPrintable(data);
  1285. }