editor.test.ts 141 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046
  1. import assert from "node:assert";
  2. import { describe, it } from "node:test";
  3. import { stripVTControlCharacters } from "node:util";
  4. import { type AutocompleteProvider, CombinedAutocompleteProvider } from "../src/autocomplete.ts";
  5. import { Editor, wordWrapLine } from "../src/components/editor.ts";
  6. import { TUI } from "../src/tui.ts";
  7. import { visibleWidth } from "../src/utils.ts";
  8. import { defaultEditorTheme } from "./test-themes.ts";
  9. import { VirtualTerminal } from "./virtual-terminal.ts";
  10. /** Create a TUI with a virtual terminal for testing */
  11. function createTestTUI(cols = 80, rows = 24): TUI {
  12. return new TUI(new VirtualTerminal(cols, rows));
  13. }
  14. /** Standard applyCompletion that replaces prefix with item.value */
  15. function applyCompletion(
  16. lines: string[],
  17. cursorLine: number,
  18. cursorCol: number,
  19. item: { value: string },
  20. prefix: string,
  21. ): { lines: string[]; cursorLine: number; cursorCol: number } {
  22. const line = lines[cursorLine] || "";
  23. const before = line.slice(0, cursorCol - prefix.length);
  24. const after = line.slice(cursorCol);
  25. const newLines = [...lines];
  26. newLines[cursorLine] = before + item.value + after;
  27. return {
  28. lines: newLines,
  29. cursorLine,
  30. cursorCol: cursorCol - prefix.length + item.value.length,
  31. };
  32. }
  33. async function flushAutocomplete(): Promise<void> {
  34. await Promise.resolve();
  35. await new Promise((resolve) => setImmediate(resolve));
  36. }
  37. describe("Editor component", () => {
  38. describe("Prompt history navigation", () => {
  39. it("does nothing on Up arrow when history is empty", () => {
  40. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  41. editor.handleInput("\x1b[A"); // Up arrow
  42. assert.strictEqual(editor.getText(), "");
  43. });
  44. it("shows most recent history entry on Up arrow when editor is empty", () => {
  45. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  46. editor.addToHistory("first prompt");
  47. editor.addToHistory("second prompt");
  48. editor.handleInput("\x1b[A"); // Up arrow
  49. assert.strictEqual(editor.getText(), "second prompt");
  50. });
  51. it("cycles through history entries on repeated Up arrow", () => {
  52. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  53. editor.addToHistory("first");
  54. editor.addToHistory("second");
  55. editor.addToHistory("third");
  56. editor.handleInput("\x1b[A"); // Up - shows "third"
  57. assert.strictEqual(editor.getText(), "third");
  58. editor.handleInput("\x1b[A"); // Up - shows "second"
  59. assert.strictEqual(editor.getText(), "second");
  60. editor.handleInput("\x1b[A"); // Up - shows "first"
  61. assert.strictEqual(editor.getText(), "first");
  62. editor.handleInput("\x1b[A"); // Up - stays at "first" (oldest)
  63. assert.strictEqual(editor.getText(), "first");
  64. });
  65. it("restores draft on Down arrow after browsing history", () => {
  66. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  67. editor.addToHistory("prompt");
  68. editor.setText("draft");
  69. editor.handleInput("\x1b[D");
  70. editor.handleInput("\x1b[D");
  71. editor.handleInput("\x1b[A"); // Up - shows "prompt"
  72. assert.strictEqual(editor.getText(), "prompt");
  73. editor.handleInput("\x1b[B"); // Down - restores draft
  74. assert.strictEqual(editor.getText(), "draft");
  75. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 3 });
  76. });
  77. it("navigates forward through history with Down arrow", () => {
  78. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  79. editor.addToHistory("first");
  80. editor.addToHistory("second");
  81. editor.addToHistory("third");
  82. editor.setText("draft");
  83. // Go to oldest
  84. editor.handleInput("\x1b[A"); // third
  85. editor.handleInput("\x1b[A"); // second
  86. editor.handleInput("\x1b[A"); // first
  87. // Navigate back
  88. editor.handleInput("\x1b[B"); // second
  89. assert.strictEqual(editor.getText(), "second");
  90. editor.handleInput("\x1b[B"); // third
  91. assert.strictEqual(editor.getText(), "third");
  92. editor.handleInput("\x1b[B"); // draft
  93. assert.strictEqual(editor.getText(), "draft");
  94. });
  95. it("exits history mode when typing a character", () => {
  96. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  97. editor.addToHistory("old prompt");
  98. editor.handleInput("\x1b[A"); // Up - shows "old prompt"
  99. editor.handleInput("x"); // Type a character - exits history mode
  100. assert.strictEqual(editor.getText(), "xold prompt");
  101. });
  102. it("exits history mode on setText", () => {
  103. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  104. editor.addToHistory("first");
  105. editor.addToHistory("second");
  106. editor.handleInput("\x1b[A"); // Up - shows "second"
  107. editor.setText(""); // External clear
  108. // Up should start fresh from most recent
  109. editor.handleInput("\x1b[A");
  110. assert.strictEqual(editor.getText(), "second");
  111. });
  112. it("does not add empty strings to history", () => {
  113. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  114. editor.addToHistory("");
  115. editor.addToHistory(" ");
  116. editor.addToHistory("valid");
  117. editor.handleInput("\x1b[A");
  118. assert.strictEqual(editor.getText(), "valid");
  119. // Should not have more entries
  120. editor.handleInput("\x1b[A");
  121. assert.strictEqual(editor.getText(), "valid");
  122. });
  123. it("does not add consecutive duplicates to history", () => {
  124. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  125. editor.addToHistory("same");
  126. editor.addToHistory("same");
  127. editor.addToHistory("same");
  128. editor.handleInput("\x1b[A"); // "same"
  129. assert.strictEqual(editor.getText(), "same");
  130. editor.handleInput("\x1b[A"); // stays at "same" (only one entry)
  131. assert.strictEqual(editor.getText(), "same");
  132. });
  133. it("allows non-consecutive duplicates in history", () => {
  134. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  135. editor.addToHistory("first");
  136. editor.addToHistory("second");
  137. editor.addToHistory("first"); // Not consecutive, should be added
  138. editor.handleInput("\x1b[A"); // "first"
  139. assert.strictEqual(editor.getText(), "first");
  140. editor.handleInput("\x1b[A"); // "second"
  141. assert.strictEqual(editor.getText(), "second");
  142. editor.handleInput("\x1b[A"); // "first" (older one)
  143. assert.strictEqual(editor.getText(), "first");
  144. });
  145. it("uses cursor movement instead of history when editor has content", () => {
  146. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  147. editor.addToHistory("history item");
  148. editor.setText("line1\nline2");
  149. // Cursor is at end of line2, Up should move to line1
  150. editor.handleInput("\x1b[A"); // Up - cursor movement
  151. // Insert character to verify cursor position
  152. editor.handleInput("X");
  153. // X should be inserted in line1, not replace with history
  154. assert.strictEqual(editor.getText(), "line1X\nline2");
  155. });
  156. it("limits history to 100 entries", () => {
  157. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  158. // Add 105 entries
  159. for (let i = 0; i < 105; i++) {
  160. editor.addToHistory(`prompt ${i}`);
  161. }
  162. // Navigate to oldest
  163. for (let i = 0; i < 100; i++) {
  164. editor.handleInput("\x1b[A");
  165. }
  166. // Should be at entry 5 (oldest kept), not entry 0
  167. assert.strictEqual(editor.getText(), "prompt 5");
  168. // One more Up should not change anything
  169. editor.handleInput("\x1b[A");
  170. assert.strictEqual(editor.getText(), "prompt 5");
  171. });
  172. it("places cursor at start after browsing history upward", () => {
  173. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  174. editor.addToHistory("older entry");
  175. editor.addToHistory("line1\nline2\nline3");
  176. editor.handleInput("\x1b[A"); // Up - shows multi-line entry at start
  177. assert.strictEqual(editor.getText(), "line1\nline2\nline3");
  178. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
  179. editor.handleInput("\x1b[A"); // Up again - immediately navigates to older entry
  180. assert.strictEqual(editor.getText(), "older entry");
  181. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
  182. });
  183. it("places cursor at end after browsing history downward", () => {
  184. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  185. editor.addToHistory("older entry");
  186. editor.addToHistory("line1\nline2\nline3");
  187. editor.addToHistory("newer entry");
  188. editor.handleInput("\x1b[A"); // newer entry
  189. editor.handleInput("\x1b[A"); // multi-line entry
  190. editor.handleInput("\x1b[A"); // older entry
  191. editor.handleInput("\x1b[B"); // Down - shows multi-line entry at end
  192. assert.strictEqual(editor.getText(), "line1\nline2\nline3");
  193. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 5 });
  194. editor.handleInput("\x1b[B"); // Down again - immediately navigates to newer entry
  195. assert.strictEqual(editor.getText(), "newer entry");
  196. });
  197. it("allows opposite-direction cursor movement within multi-line history entry", () => {
  198. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  199. editor.addToHistory("line1\nline2\nline3");
  200. editor.handleInput("\x1b[A"); // Up - shows entry at start
  201. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
  202. editor.handleInput("\x1b[B"); // Down - cursor moves to line2
  203. assert.strictEqual(editor.getText(), "line1\nline2\nline3");
  204. assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 0 });
  205. editor.handleInput("\x1b[A"); // Up - cursor moves back to line1
  206. assert.strictEqual(editor.getText(), "line1\nline2\nline3");
  207. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
  208. });
  209. });
  210. describe("public state accessors", () => {
  211. it("returns cursor position", () => {
  212. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  213. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
  214. editor.handleInput("a");
  215. editor.handleInput("b");
  216. editor.handleInput("c");
  217. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 3 });
  218. editor.handleInput("\x1b[D"); // Left
  219. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 2 });
  220. });
  221. it("returns lines as a defensive copy", () => {
  222. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  223. editor.setText("a\nb");
  224. const lines = editor.getLines();
  225. assert.deepStrictEqual(lines, ["a", "b"]);
  226. lines[0] = "mutated";
  227. assert.deepStrictEqual(editor.getLines(), ["a", "b"]);
  228. });
  229. });
  230. describe("Backslash+Enter newline workaround", () => {
  231. it("inserts backslash immediately (no buffering)", () => {
  232. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  233. editor.handleInput("\\");
  234. // Backslash should be visible immediately, not buffered
  235. assert.strictEqual(editor.getText(), "\\");
  236. });
  237. it("converts standalone backslash to newline on Enter", () => {
  238. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  239. editor.handleInput("\\");
  240. editor.handleInput("\r");
  241. assert.strictEqual(editor.getText(), "\n");
  242. });
  243. it("inserts backslash normally when followed by other characters", () => {
  244. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  245. editor.handleInput("\\");
  246. editor.handleInput("x");
  247. assert.strictEqual(editor.getText(), "\\x");
  248. });
  249. it("does not trigger newline when backslash is not immediately before cursor", () => {
  250. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  251. let submitted = false;
  252. editor.onSubmit = () => {
  253. submitted = true;
  254. };
  255. editor.handleInput("\\");
  256. editor.handleInput("x");
  257. editor.handleInput("\r");
  258. // Should submit, not insert newline (backslash not at cursor)
  259. assert.strictEqual(submitted, true);
  260. });
  261. it("only removes one backslash when multiple are present", () => {
  262. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  263. editor.handleInput("\\");
  264. editor.handleInput("\\");
  265. editor.handleInput("\\");
  266. assert.strictEqual(editor.getText(), "\\\\\\");
  267. editor.handleInput("\r");
  268. // Only the last backslash is removed, newline inserted
  269. assert.strictEqual(editor.getText(), "\\\\\n");
  270. });
  271. });
  272. describe("Kitty CSI-u handling", () => {
  273. it("ignores printable CSI-u sequences with unsupported modifiers", () => {
  274. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  275. editor.handleInput("\x1b[99;9u");
  276. assert.strictEqual(editor.getText(), "");
  277. });
  278. it("inserts shifted CSI-u letters as text", () => {
  279. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  280. editor.handleInput("\x1b[69;2u");
  281. assert.strictEqual(editor.getText(), "E");
  282. });
  283. it("inserts shifted xterm modifyOtherKeys letters as text", () => {
  284. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  285. editor.handleInput("\x1b[27;2;69~");
  286. assert.strictEqual(editor.getText(), "E");
  287. });
  288. });
  289. describe("Unicode text editing behavior", () => {
  290. it("inserts mixed ASCII, umlauts, and emojis as literal text", () => {
  291. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  292. editor.handleInput("H");
  293. editor.handleInput("e");
  294. editor.handleInput("l");
  295. editor.handleInput("l");
  296. editor.handleInput("o");
  297. editor.handleInput(" ");
  298. editor.handleInput("ä");
  299. editor.handleInput("ö");
  300. editor.handleInput("ü");
  301. editor.handleInput(" ");
  302. editor.handleInput("😀");
  303. const text = editor.getText();
  304. assert.strictEqual(text, "Hello äöü 😀");
  305. });
  306. it("deletes single-code-unit unicode characters (umlauts) with Backspace", () => {
  307. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  308. editor.handleInput("ä");
  309. editor.handleInput("ö");
  310. editor.handleInput("ü");
  311. // Delete the last character (ü)
  312. editor.handleInput("\x7f"); // Backspace
  313. const text = editor.getText();
  314. assert.strictEqual(text, "äö");
  315. });
  316. it("deletes multi-code-unit emojis with single Backspace", () => {
  317. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  318. editor.handleInput("😀");
  319. editor.handleInput("👍");
  320. // Delete the last emoji (👍) - single backspace deletes whole grapheme cluster
  321. editor.handleInput("\x7f"); // Backspace
  322. const text = editor.getText();
  323. assert.strictEqual(text, "😀");
  324. });
  325. it("inserts characters at the correct position after cursor movement over umlauts", () => {
  326. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  327. editor.handleInput("ä");
  328. editor.handleInput("ö");
  329. editor.handleInput("ü");
  330. // Move cursor left twice
  331. editor.handleInput("\x1b[D"); // Left arrow
  332. editor.handleInput("\x1b[D"); // Left arrow
  333. // Insert 'x' in the middle
  334. editor.handleInput("x");
  335. const text = editor.getText();
  336. assert.strictEqual(text, "äxöü");
  337. });
  338. it("moves cursor across multi-code-unit emojis with single arrow key", () => {
  339. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  340. editor.handleInput("😀");
  341. editor.handleInput("👍");
  342. editor.handleInput("🎉");
  343. // Move cursor left over last emoji (🎉) - single arrow moves over whole grapheme
  344. editor.handleInput("\x1b[D"); // Left arrow
  345. // Move cursor left over second emoji (👍)
  346. editor.handleInput("\x1b[D");
  347. // Insert 'x' between first and second emoji
  348. editor.handleInput("x");
  349. const text = editor.getText();
  350. assert.strictEqual(text, "😀x👍🎉");
  351. });
  352. it("preserves umlauts across line breaks", () => {
  353. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  354. editor.handleInput("ä");
  355. editor.handleInput("ö");
  356. editor.handleInput("ü");
  357. editor.handleInput("\n"); // new line
  358. editor.handleInput("Ä");
  359. editor.handleInput("Ö");
  360. editor.handleInput("Ü");
  361. const text = editor.getText();
  362. assert.strictEqual(text, "äöü\nÄÖÜ");
  363. });
  364. it("replaces the entire document with unicode text via setText (paste simulation)", () => {
  365. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  366. // Simulate bracketed paste / programmatic replacement
  367. editor.setText("Hällö Wörld! 😀 äöüÄÖÜß");
  368. const text = editor.getText();
  369. assert.strictEqual(text, "Hällö Wörld! 😀 äöüÄÖÜß");
  370. });
  371. it("moves cursor to document start on Ctrl+A and inserts at the beginning", () => {
  372. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  373. editor.handleInput("a");
  374. editor.handleInput("b");
  375. editor.handleInput("\x01"); // Ctrl+A (move to start)
  376. editor.handleInput("x"); // Insert at start
  377. const text = editor.getText();
  378. assert.strictEqual(text, "xab");
  379. });
  380. it("deletes words correctly with Ctrl+W and Alt+Backspace", () => {
  381. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  382. // Basic word deletion
  383. editor.setText("foo bar baz");
  384. editor.handleInput("\x17"); // Ctrl+W
  385. assert.strictEqual(editor.getText(), "foo bar ");
  386. // Trailing whitespace
  387. editor.setText("foo bar ");
  388. editor.handleInput("\x17");
  389. assert.strictEqual(editor.getText(), "foo ");
  390. // Punctuation run
  391. editor.setText("foo bar...");
  392. editor.handleInput("\x17");
  393. assert.strictEqual(editor.getText(), "foo bar");
  394. // ASCII punctuation inside Intl word-like segments preserves old boundaries
  395. editor.setText("foo.bar");
  396. editor.handleInput("\x17");
  397. assert.strictEqual(editor.getText(), "foo.");
  398. editor.setText("foo:bar");
  399. editor.handleInput("\x17");
  400. assert.strictEqual(editor.getText(), "foo:");
  401. // Delete across multiple lines
  402. editor.setText("line one\nline two");
  403. editor.handleInput("\x17");
  404. assert.strictEqual(editor.getText(), "line one\nline ");
  405. // Delete empty line (merge)
  406. editor.setText("line one\n");
  407. editor.handleInput("\x17");
  408. assert.strictEqual(editor.getText(), "line one");
  409. // Grapheme safety (emoji as a word)
  410. editor.setText("foo 😀😀 bar");
  411. editor.handleInput("\x17");
  412. assert.strictEqual(editor.getText(), "foo 😀😀 ");
  413. editor.handleInput("\x17");
  414. assert.strictEqual(editor.getText(), "foo ");
  415. // Alt+Backspace
  416. editor.setText("foo bar");
  417. editor.handleInput("\x1b\x7f"); // Alt+Backspace (legacy)
  418. assert.strictEqual(editor.getText(), "foo ");
  419. });
  420. it("navigates words correctly with Ctrl+Left/Right", () => {
  421. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  422. editor.setText("foo bar... baz");
  423. // Cursor at end
  424. // Move left over baz
  425. editor.handleInput("\x1b[1;5D"); // Ctrl+Left
  426. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 11 }); // after '...'
  427. // Move left over punctuation
  428. editor.handleInput("\x1b[1;5D"); // Ctrl+Left
  429. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 7 }); // after 'bar'
  430. // Move left over bar
  431. editor.handleInput("\x1b[1;5D"); // Ctrl+Left
  432. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 4 }); // after 'foo '
  433. // Move right over bar
  434. editor.handleInput("\x1b[1;5C"); // Ctrl+Right
  435. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 7 }); // at end of 'bar'
  436. // Move right over punctuation run
  437. editor.handleInput("\x1b[1;5C"); // Ctrl+Right
  438. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 10 }); // after '...'
  439. // Move right skips space and lands after baz
  440. editor.handleInput("\x1b[1;5C"); // Ctrl+Right
  441. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 14 }); // end of line
  442. // Test forward from start with leading whitespace
  443. editor.setText(" foo bar");
  444. editor.handleInput("\x01"); // Ctrl+A to go to start
  445. editor.handleInput("\x1b[1;5C"); // Ctrl+Right
  446. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 6 }); // after 'foo'
  447. // ASCII punctuation inside Intl word-like segments preserves old boundaries
  448. editor.setText("foo.bar baz");
  449. editor.handleInput("\x1b[1;5D"); // Ctrl+Left over baz
  450. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 8 });
  451. editor.handleInput("\x1b[1;5D"); // Ctrl+Left over bar
  452. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 4 });
  453. editor.handleInput("\x1b[1;5D"); // Ctrl+Left over .
  454. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 3 });
  455. editor.handleInput("\x01"); // Ctrl+A
  456. editor.handleInput("\x1b[1;5C"); // Ctrl+Right over foo
  457. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 3 });
  458. editor.handleInput("\x1b[1;5C"); // Ctrl+Right over .
  459. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 4 });
  460. editor.handleInput("\x1b[1;5C"); // Ctrl+Right over bar
  461. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 7 });
  462. });
  463. it("stops at fullwidth Chinese punctuation (issue #4972)", () => {
  464. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  465. // 你好,世界 = 你好(0-2) ,(2-3) 世界(3-5)
  466. editor.setText("你好,世界");
  467. // Cursor at end (col 5)
  468. // Move left over 世界
  469. editor.handleInput("\x1b[1;5D"); // Ctrl+Left
  470. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 3 }); // after ,
  471. // Move left over ,
  472. editor.handleInput("\x1b[1;5D"); // Ctrl+Left
  473. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 2 }); // after 你好
  474. // Move left over 你好
  475. editor.handleInput("\x1b[1;5D"); // Ctrl+Left
  476. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 }); // start
  477. // Move right over 你好
  478. editor.handleInput("\x1b[1;5C"); // Ctrl+Right
  479. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 2 }); // after 你好
  480. // Move right over ,
  481. editor.handleInput("\x1b[1;5C"); // Ctrl+Right
  482. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 3 }); // after ,
  483. // Move right over 世界
  484. editor.handleInput("\x1b[1;5C"); // Ctrl+Right
  485. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 5 }); // end
  486. });
  487. it("handles mixed CJK and ASCII word movement", () => {
  488. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  489. // "hello你好,world世界" = hello(0-5) 你好(5-7) ,(7-8) world(8-13) 世界(13-15)
  490. editor.setText("hello你好,world世界");
  491. // Cursor at end (col 15)
  492. // Move left over 世界
  493. editor.handleInput("\x1b[1;5D"); // Ctrl+Left
  494. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 13 }); // after 'world'
  495. // Move left over world
  496. editor.handleInput("\x1b[1;5D"); // Ctrl+Left
  497. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 8 }); // after ,
  498. // Move left over ,
  499. editor.handleInput("\x1b[1;5D"); // Ctrl+Left
  500. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 7 }); // after 你好
  501. // Move left over 你好
  502. editor.handleInput("\x1b[1;5D"); // Ctrl+Left
  503. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 5 }); // after 'hello'
  504. // Move left over hello
  505. editor.handleInput("\x1b[1;5D"); // Ctrl+Left
  506. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 }); // start
  507. // Forward from start
  508. editor.handleInput("\x1b[1;5C"); // Ctrl+Right
  509. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 5 }); // after 'hello'
  510. editor.handleInput("\x1b[1;5C"); // Ctrl+Right
  511. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 7 }); // after 你好
  512. editor.handleInput("\x1b[1;5C"); // Ctrl+Right
  513. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 8 }); // after ,
  514. editor.handleInput("\x1b[1;5C"); // Ctrl+Right
  515. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 13 }); // after 'world'
  516. editor.handleInput("\x1b[1;5C"); // Ctrl+Right
  517. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 15 }); // end
  518. });
  519. });
  520. describe("Grapheme-aware text wrapping", () => {
  521. it("wraps lines correctly when text contains wide emojis", () => {
  522. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  523. const width = 20;
  524. // ✅ is 2 columns wide, so "Hello ✅ World" is 14 columns
  525. editor.setText("Hello ✅ World");
  526. const lines = editor.render(width);
  527. // All content lines (between borders) should fit within width
  528. for (let i = 1; i < lines.length - 1; i++) {
  529. const lineWidth = visibleWidth(lines[i]!);
  530. assert.strictEqual(lineWidth, width, `Line ${i} has width ${lineWidth}, expected ${width}`);
  531. }
  532. });
  533. it("wraps long text with emojis at correct positions", () => {
  534. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  535. const width = 10;
  536. // Each ✅ is 2 columns. "✅✅✅✅✅" = 10 columns, fits exactly
  537. // "✅✅✅✅✅✅" = 12 columns, needs wrap
  538. editor.setText("✅✅✅✅✅✅");
  539. const lines = editor.render(width);
  540. // Should have 2 content lines (plus 2 border lines)
  541. // First line: 5 emojis (10 cols), second line: 1 emoji (2 cols) + padding
  542. for (let i = 1; i < lines.length - 1; i++) {
  543. const lineWidth = visibleWidth(lines[i]!);
  544. assert.strictEqual(lineWidth, width, `Line ${i} has width ${lineWidth}, expected ${width}`);
  545. }
  546. });
  547. it("renders isolated Thai and Lao AM clusters without width drift", () => {
  548. for (const text of ["ำabc", "ຳabc"]) {
  549. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  550. const width = 8;
  551. editor.setText(text);
  552. for (const line of editor.render(width)) {
  553. assert.strictEqual(visibleWidth(line), width, `line width drift for ${JSON.stringify(text)}: ${line}`);
  554. }
  555. }
  556. });
  557. it("wraps CJK characters correctly (each is 2 columns wide)", () => {
  558. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  559. const width = 10 + 1; // +1 col reserved for cursor
  560. // Each CJK char is 2 columns. "日本語テスト" = 6 chars = 12 columns
  561. editor.setText("日本語テスト");
  562. const lines = editor.render(width);
  563. for (let i = 1; i < lines.length - 1; i++) {
  564. const lineWidth = visibleWidth(lines[i]!);
  565. assert.strictEqual(lineWidth, width, `Line ${i} has width ${lineWidth}, expected ${width}`);
  566. }
  567. // Verify content split correctly
  568. const contentLines = lines.slice(1, -1).map((l) => stripVTControlCharacters(l).trim());
  569. assert.strictEqual(contentLines.length, 2);
  570. assert.strictEqual(contentLines[0], "日本語テス"); // 5 chars = 10 columns
  571. assert.strictEqual(contentLines[1], "ト"); // 1 char = 2 columns (+ padding)
  572. });
  573. it("handles mixed ASCII and wide characters in wrapping", () => {
  574. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  575. const width = 15 + 1; // +1 col reserved for cursor
  576. // "Test ✅ OK 日本" = 4 + 1 + 2 + 1 + 2 + 1 + 4 = 15 columns (fits in width-1=15)
  577. editor.setText("Test ✅ OK 日本");
  578. const lines = editor.render(width);
  579. // Should fit in one content line
  580. const contentLines = lines.slice(1, -1);
  581. assert.strictEqual(contentLines.length, 1);
  582. const lineWidth = visibleWidth(contentLines[0]!);
  583. assert.strictEqual(lineWidth, width);
  584. });
  585. it("renders cursor correctly on wide characters", () => {
  586. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  587. const width = 20;
  588. editor.setText("A✅B");
  589. // Cursor should be at end (after B)
  590. const lines = editor.render(width);
  591. // The cursor (reverse video space) should be visible
  592. const contentLine = lines[1]!;
  593. assert.ok(contentLine.includes("\x1b[7m"), "Should have reverse video cursor");
  594. // Line should still be correct width
  595. assert.strictEqual(visibleWidth(contentLine), width);
  596. });
  597. it("does not exceed terminal width with emoji at wrap boundary", () => {
  598. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  599. const width = 11;
  600. // "0123456789✅" = 10 ASCII + 2-wide emoji = 12 columns
  601. // Should wrap before the emoji since it would exceed width
  602. editor.setText("0123456789✅");
  603. const lines = editor.render(width);
  604. for (let i = 1; i < lines.length - 1; i++) {
  605. const lineWidth = visibleWidth(lines[i]!);
  606. assert.ok(lineWidth <= width, `Line ${i} has width ${lineWidth}, exceeds max ${width}`);
  607. }
  608. });
  609. it("shows cursor at end of line before wrap, wraps on next char", () => {
  610. const width = 10;
  611. for (const paddingX of [0, 1]) {
  612. const editor = new Editor(createTestTUI(width + paddingX), defaultEditorTheme, { paddingX });
  613. // Type 9 chars → fills layoutWidth exactly, cursor at end on same line
  614. for (const ch of "aaaaaaaaa") editor.handleInput(ch);
  615. let lines = editor.render(width + paddingX);
  616. let contentLines = lines.slice(1, -1);
  617. assert.strictEqual(contentLines.length, 1, "Should be 1 content line before wrap");
  618. assert.ok(contentLines[0]!.endsWith("\x1b[7m \x1b[0m"), "Cursor should be at end of line");
  619. // Type 1 more → text wraps to second line
  620. editor.handleInput("a");
  621. lines = editor.render(width + paddingX);
  622. contentLines = lines.slice(1, -1);
  623. assert.strictEqual(contentLines.length, 2, "Should wrap to 2 content lines");
  624. }
  625. });
  626. });
  627. describe("Word wrapping", () => {
  628. it("wraps at word boundaries instead of mid-word", () => {
  629. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  630. const width = 40;
  631. editor.setText("Hello world this is a test of word wrapping functionality");
  632. const lines = editor.render(width);
  633. // Get content lines (between borders)
  634. const contentLines = lines.slice(1, -1).map((l) => stripVTControlCharacters(l).trim());
  635. // Should NOT break mid-word
  636. // Line 1 should end with a complete word
  637. assert.ok(!contentLines[0]!.endsWith("-"), "Line should not end with hyphen (mid-word break)");
  638. // Each content line should be complete words
  639. for (const line of contentLines) {
  640. // Words at end of line should be complete (no partial words)
  641. const lastChar = line.trimEnd().slice(-1);
  642. assert.ok(lastChar === "" || /[\w.,!?;:]/.test(lastChar), `Line ends unexpectedly with: "${lastChar}"`);
  643. }
  644. });
  645. it("does not start lines with leading whitespace after word wrap", () => {
  646. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  647. const width = 20;
  648. editor.setText("Word1 Word2 Word3 Word4 Word5 Word6");
  649. const lines = editor.render(width);
  650. // Get content lines (between borders)
  651. const contentLines = lines.slice(1, -1);
  652. // No line should start with whitespace (except for padding at the end)
  653. for (let i = 0; i < contentLines.length; i++) {
  654. const line = stripVTControlCharacters(contentLines[i]!);
  655. const trimmedStart = line.trimStart();
  656. // The line should either be all padding or start with a word character
  657. if (trimmedStart.length > 0) {
  658. assert.ok(!/^\s+\S/.test(line.trimEnd()), `Line ${i} starts with unexpected whitespace before content`);
  659. }
  660. }
  661. });
  662. it("breaks long words (URLs) at character level", () => {
  663. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  664. const width = 30;
  665. editor.setText("Check https://example.com/very/long/path/that/exceeds/width here");
  666. const lines = editor.render(width);
  667. // All lines should fit within width
  668. for (let i = 1; i < lines.length - 1; i++) {
  669. const lineWidth = visibleWidth(lines[i]!);
  670. assert.strictEqual(lineWidth, width, `Line ${i} has width ${lineWidth}, expected ${width}`);
  671. }
  672. });
  673. it("preserves multiple spaces within words on same line", () => {
  674. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  675. const width = 50;
  676. editor.setText("Word1 Word2 Word3");
  677. const lines = editor.render(width);
  678. const contentLine = stripVTControlCharacters(lines[1]!).trim();
  679. // Multiple spaces should be preserved
  680. assert.ok(contentLine.includes("Word1 Word2"), "Multiple spaces should be preserved");
  681. });
  682. it("handles empty string", () => {
  683. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  684. const width = 40;
  685. editor.setText("");
  686. const lines = editor.render(width);
  687. // Should have border + empty content + border
  688. assert.strictEqual(lines.length, 3);
  689. });
  690. it("handles single word that fits exactly", () => {
  691. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  692. const width = 10 + 1; // +1 col reserved for cursor
  693. editor.setText("1234567890");
  694. const lines = editor.render(width);
  695. // Should have exactly 3 lines (top border, content, bottom border)
  696. assert.strictEqual(lines.length, 3);
  697. const contentLine = stripVTControlCharacters(lines[1]!);
  698. assert.ok(contentLine.includes("1234567890"), "Content should contain the word");
  699. });
  700. it("wraps word to next line when it ends exactly at terminal width", () => {
  701. // "hello " (6) + "world" (5) = 11, but "world" is non-whitespace ending at width.
  702. // Thus, wrap it to next line. The trailing space stays with "hello" on line 1
  703. const chunks = wordWrapLine("hello world test", 11);
  704. assert.strictEqual(chunks.length, 2);
  705. assert.strictEqual(chunks[0]!.text, "hello ");
  706. assert.strictEqual(chunks[1]!.text, "world test");
  707. });
  708. it("keeps whitespace at terminal width boundary on same line", () => {
  709. // "hello world " is exactly 12 chars (including trailing space)
  710. // The space at position 12 should stay on the first line
  711. const chunks = wordWrapLine("hello world test", 12);
  712. assert.strictEqual(chunks.length, 2);
  713. assert.strictEqual(chunks[0]!.text, "hello world ");
  714. assert.strictEqual(chunks[1]!.text, "test");
  715. });
  716. it("handles unbreakable word filling width exactly followed by space", () => {
  717. const chunks = wordWrapLine("aaaaaaaaaaaa aaaa", 12);
  718. assert.strictEqual(chunks.length, 2);
  719. assert.strictEqual(chunks[0]!.text, "aaaaaaaaaaaa");
  720. assert.strictEqual(chunks[1]!.text, " aaaa");
  721. });
  722. it("wraps word to next line when it fits width but not remaining space", () => {
  723. const chunks = wordWrapLine(" aaaaaaaaaaaa", 12);
  724. assert.strictEqual(chunks.length, 2);
  725. assert.strictEqual(chunks[0]!.text, " ");
  726. assert.strictEqual(chunks[1]!.text, "aaaaaaaaaaaa");
  727. });
  728. it("keeps word with multi-space and following word together when they fit", () => {
  729. const chunks = wordWrapLine("Lorem ipsum dolor sit amet, consectetur", 30);
  730. assert.strictEqual(chunks.length, 2);
  731. assert.strictEqual(chunks[0]!.text, "Lorem ipsum dolor sit ");
  732. assert.strictEqual(chunks[1]!.text, "amet, consectetur");
  733. });
  734. it("keeps word with multi-space and following word when they fill width exactly", () => {
  735. const chunks = wordWrapLine("Lorem ipsum dolor sit amet, consectetur", 30);
  736. assert.strictEqual(chunks.length, 2);
  737. assert.strictEqual(chunks[0]!.text, "Lorem ipsum dolor sit ");
  738. assert.strictEqual(chunks[1]!.text, "amet, consectetur");
  739. });
  740. it("splits when word plus multi-space plus word exceeds width", () => {
  741. const chunks = wordWrapLine("Lorem ipsum dolor sit amet, consectetur", 30);
  742. assert.strictEqual(chunks.length, 3);
  743. assert.strictEqual(chunks[0]!.text, "Lorem ipsum dolor sit ");
  744. assert.strictEqual(chunks[1]!.text, "amet, ");
  745. assert.strictEqual(chunks[2]!.text, "consectetur");
  746. });
  747. it("breaks long whitespace at line boundary", () => {
  748. const chunks = wordWrapLine("Lorem ipsum dolor sit amet, consectetur", 30);
  749. assert.strictEqual(chunks.length, 3);
  750. assert.strictEqual(chunks[0]!.text, "Lorem ipsum dolor sit ");
  751. assert.strictEqual(chunks[1]!.text, "amet, ");
  752. assert.strictEqual(chunks[2]!.text, "consectetur");
  753. });
  754. it("breaks long whitespace at line boundary 2", () => {
  755. const chunks = wordWrapLine("Lorem ipsum dolor sit amet, consectetur", 30);
  756. assert.strictEqual(chunks.length, 3);
  757. assert.strictEqual(chunks[0]!.text, "Lorem ipsum dolor sit ");
  758. assert.strictEqual(chunks[1]!.text, "amet, ");
  759. assert.strictEqual(chunks[2]!.text, " consectetur");
  760. });
  761. it("breaks whitespace spanning full lines", () => {
  762. const chunks = wordWrapLine("Lorem ipsum dolor sit amet, consectetur", 30);
  763. assert.strictEqual(chunks.length, 3);
  764. assert.strictEqual(chunks[0]!.text, "Lorem ipsum dolor sit ");
  765. assert.strictEqual(chunks[1]!.text, "amet, ");
  766. assert.strictEqual(chunks[2]!.text, " consectetur");
  767. });
  768. it("force-breaks when wide char after word boundary wrap still overflows", () => {
  769. // " " (1) + "a"*186 (186) + "你" (2) = 189 visible width
  770. // maxWidth = 187: backtracking to the space would leave 186 + 2 = 188 > 187,
  771. // so the algorithm must force-break before the wide char instead.
  772. const line = ` ${"a".repeat(186)}你`;
  773. const chunks = wordWrapLine(line, 187);
  774. for (const chunk of chunks) {
  775. assert.ok(
  776. visibleWidth(chunk.text) <= 187,
  777. `chunk "${chunk.text.slice(0, 20)}..." has visible width ${visibleWidth(chunk.text)}, expected <= 187`,
  778. );
  779. }
  780. // Verify no content is lost
  781. const reconstructed = chunks.map((c) => line.slice(c.startIndex, c.endIndex)).join("");
  782. assert.strictEqual(reconstructed, line);
  783. });
  784. it("splits oversized atomic segment across multiple chunks", () => {
  785. // Simulate a paste marker wider than maxWidth by passing pre-segmented data
  786. const marker = "[paste #1 +20 lines]"; // 21 chars
  787. const line = `A${marker}B`;
  788. const segments: Intl.SegmentData[] = [
  789. { segment: "A", index: 0, input: line },
  790. { segment: marker, index: 1, input: line },
  791. { segment: "B", index: 1 + marker.length, input: line },
  792. ];
  793. const chunks = wordWrapLine(line, 10, segments);
  794. // Every chunk must fit within maxWidth
  795. for (const chunk of chunks) {
  796. assert.ok(
  797. visibleWidth(chunk.text) <= 10,
  798. `chunk "${chunk.text}" has visible width ${visibleWidth(chunk.text)}, expected <= 10`,
  799. );
  800. }
  801. // Verify no content is lost
  802. const reconstructed = chunks.map((c) => line.slice(c.startIndex, c.endIndex)).join("");
  803. assert.strictEqual(reconstructed, line);
  804. });
  805. it("splits oversized atomic segment at start of line", () => {
  806. const marker = "[paste #1 +20 lines]"; // 21 chars
  807. const line = `${marker}B`;
  808. const segments: Intl.SegmentData[] = [
  809. { segment: marker, index: 0, input: line },
  810. { segment: "B", index: marker.length, input: line },
  811. ];
  812. const chunks = wordWrapLine(line, 10, segments);
  813. for (const chunk of chunks) {
  814. assert.ok(visibleWidth(chunk.text) <= 10);
  815. }
  816. // "B" ends up on the last line (either alone or with the marker tail)
  817. assert.strictEqual(chunks[chunks.length - 1]!.text.includes("B"), true);
  818. const reconstructed = chunks.map((c) => line.slice(c.startIndex, c.endIndex)).join("");
  819. assert.strictEqual(reconstructed, line);
  820. });
  821. it("splits oversized atomic segment at end of line", () => {
  822. const marker = "[paste #1 +20 lines]"; // 21 chars
  823. const line = `A${marker}`;
  824. const segments: Intl.SegmentData[] = [
  825. { segment: "A", index: 0, input: line },
  826. { segment: marker, index: 1, input: line },
  827. ];
  828. const chunks = wordWrapLine(line, 10, segments);
  829. for (const chunk of chunks) {
  830. assert.ok(visibleWidth(chunk.text) <= 10);
  831. }
  832. assert.strictEqual(chunks[0]!.text, "A");
  833. const reconstructed = chunks.map((c) => line.slice(c.startIndex, c.endIndex)).join("");
  834. assert.strictEqual(reconstructed, line);
  835. });
  836. it("splits consecutive oversized atomic segments", () => {
  837. const m1 = "[paste #1 +20 lines]"; // 21 chars
  838. const m2 = "[paste #2 +30 lines]"; // 21 chars
  839. const line = `${m1}${m2}`;
  840. const segments: Intl.SegmentData[] = [
  841. { segment: m1, index: 0, input: line },
  842. { segment: m2, index: m1.length, input: line },
  843. ];
  844. const chunks = wordWrapLine(line, 10, segments);
  845. for (const chunk of chunks) {
  846. assert.ok(
  847. visibleWidth(chunk.text) <= 10,
  848. `chunk "${chunk.text}" has visible width ${visibleWidth(chunk.text)}, expected <= 10`,
  849. );
  850. }
  851. const reconstructed = chunks.map((c) => line.slice(c.startIndex, c.endIndex)).join("");
  852. assert.strictEqual(reconstructed, line);
  853. });
  854. it("wraps normally after oversized atomic segment", () => {
  855. const marker = "[paste #1 +20 lines]"; // 21 chars
  856. const line = `${marker} hello world`;
  857. const segments: Intl.SegmentData[] = [
  858. { segment: marker, index: 0, input: line },
  859. { segment: " ", index: marker.length, input: line },
  860. { segment: "h", index: marker.length + 1, input: line },
  861. { segment: "e", index: marker.length + 2, input: line },
  862. { segment: "l", index: marker.length + 3, input: line },
  863. { segment: "l", index: marker.length + 4, input: line },
  864. { segment: "o", index: marker.length + 5, input: line },
  865. { segment: " ", index: marker.length + 6, input: line },
  866. { segment: "w", index: marker.length + 7, input: line },
  867. { segment: "o", index: marker.length + 8, input: line },
  868. { segment: "r", index: marker.length + 9, input: line },
  869. { segment: "l", index: marker.length + 10, input: line },
  870. { segment: "d", index: marker.length + 11, input: line },
  871. ];
  872. const chunks = wordWrapLine(line, 10, segments);
  873. // All chunks must fit
  874. for (const chunk of chunks) {
  875. assert.ok(
  876. visibleWidth(chunk.text) <= 10,
  877. `chunk "${chunk.text}" has visible width ${visibleWidth(chunk.text)}, expected <= 10`,
  878. );
  879. }
  880. // Last chunk should contain "world" (normal wrapping resumes)
  881. assert.strictEqual(chunks[chunks.length - 1]!.text, "world");
  882. const reconstructed = chunks.map((c) => line.slice(c.startIndex, c.endIndex)).join("");
  883. assert.strictEqual(reconstructed, line);
  884. });
  885. });
  886. describe("Kill ring", () => {
  887. it("Ctrl+W saves deleted text to kill ring and Ctrl+Y yanks it", () => {
  888. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  889. editor.setText("foo bar baz");
  890. editor.handleInput("\x17"); // Ctrl+W - deletes "baz"
  891. assert.strictEqual(editor.getText(), "foo bar ");
  892. // Move to beginning and yank
  893. editor.handleInput("\x01"); // Ctrl+A
  894. editor.handleInput("\x19"); // Ctrl+Y
  895. assert.strictEqual(editor.getText(), "bazfoo bar ");
  896. });
  897. it("Ctrl+U saves deleted text to kill ring", () => {
  898. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  899. editor.setText("hello world");
  900. // Move cursor to middle
  901. editor.handleInput("\x01"); // Ctrl+A (start)
  902. editor.handleInput("\x1b[C"); // Right 5 times
  903. editor.handleInput("\x1b[C");
  904. editor.handleInput("\x1b[C");
  905. editor.handleInput("\x1b[C");
  906. editor.handleInput("\x1b[C");
  907. editor.handleInput("\x1b[C"); // After "hello "
  908. editor.handleInput("\x15"); // Ctrl+U - deletes "hello "
  909. assert.strictEqual(editor.getText(), "world");
  910. editor.handleInput("\x19"); // Ctrl+Y
  911. assert.strictEqual(editor.getText(), "hello world");
  912. });
  913. it("Ctrl+K saves deleted text to kill ring", () => {
  914. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  915. editor.setText("hello world");
  916. editor.handleInput("\x01"); // Ctrl+A (start)
  917. editor.handleInput("\x0b"); // Ctrl+K - deletes "hello world"
  918. assert.strictEqual(editor.getText(), "");
  919. editor.handleInput("\x19"); // Ctrl+Y
  920. assert.strictEqual(editor.getText(), "hello world");
  921. });
  922. it("Ctrl+Y does nothing when kill ring is empty", () => {
  923. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  924. editor.setText("test");
  925. editor.handleInput("\x19"); // Ctrl+Y
  926. assert.strictEqual(editor.getText(), "test");
  927. });
  928. it("Alt+Y cycles through kill ring after Ctrl+Y", () => {
  929. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  930. // Create kill ring with multiple entries
  931. editor.setText("first");
  932. editor.handleInput("\x17"); // Ctrl+W - deletes "first"
  933. editor.setText("second");
  934. editor.handleInput("\x17"); // Ctrl+W - deletes "second"
  935. editor.setText("third");
  936. editor.handleInput("\x17"); // Ctrl+W - deletes "third"
  937. // Kill ring now has: [first, second, third]
  938. assert.strictEqual(editor.getText(), "");
  939. editor.handleInput("\x19"); // Ctrl+Y - yanks "third" (most recent)
  940. assert.strictEqual(editor.getText(), "third");
  941. editor.handleInput("\x1by"); // Alt+Y - cycles to "second"
  942. assert.strictEqual(editor.getText(), "second");
  943. editor.handleInput("\x1by"); // Alt+Y - cycles to "first"
  944. assert.strictEqual(editor.getText(), "first");
  945. editor.handleInput("\x1by"); // Alt+Y - cycles back to "third"
  946. assert.strictEqual(editor.getText(), "third");
  947. });
  948. it("Alt+Y does nothing if not preceded by yank", () => {
  949. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  950. editor.setText("test");
  951. editor.handleInput("\x17"); // Ctrl+W - deletes "test"
  952. editor.setText("other");
  953. // Type something to break the yank chain
  954. editor.handleInput("x");
  955. assert.strictEqual(editor.getText(), "otherx");
  956. // Alt+Y should do nothing
  957. editor.handleInput("\x1by"); // Alt+Y
  958. assert.strictEqual(editor.getText(), "otherx");
  959. });
  960. it("Alt+Y does nothing if kill ring has ≤1 entry", () => {
  961. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  962. editor.setText("only");
  963. editor.handleInput("\x17"); // Ctrl+W - deletes "only"
  964. editor.handleInput("\x19"); // Ctrl+Y - yanks "only"
  965. assert.strictEqual(editor.getText(), "only");
  966. editor.handleInput("\x1by"); // Alt+Y - should do nothing (only 1 entry)
  967. assert.strictEqual(editor.getText(), "only");
  968. });
  969. it("consecutive Ctrl+W accumulates into one kill ring entry", () => {
  970. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  971. editor.setText("one two three");
  972. editor.handleInput("\x17"); // Ctrl+W - deletes "three"
  973. editor.handleInput("\x17"); // Ctrl+W - deletes "two " (prepended)
  974. editor.handleInput("\x17"); // Ctrl+W - deletes "one " (prepended)
  975. assert.strictEqual(editor.getText(), "");
  976. // Should be one combined entry
  977. editor.handleInput("\x19"); // Ctrl+Y
  978. assert.strictEqual(editor.getText(), "one two three");
  979. });
  980. it("Ctrl+U accumulates multiline deletes including newlines", () => {
  981. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  982. // Start with multiline text, cursor at end
  983. editor.setText("line1\nline2\nline3");
  984. // Cursor is at end of line3 (line 2, col 5)
  985. // Delete "line3"
  986. editor.handleInput("\x15"); // Ctrl+U
  987. assert.strictEqual(editor.getText(), "line1\nline2\n");
  988. // Delete newline (at start of empty line 2, merges with line1)
  989. editor.handleInput("\x15"); // Ctrl+U
  990. assert.strictEqual(editor.getText(), "line1\nline2");
  991. // Delete "line2"
  992. editor.handleInput("\x15"); // Ctrl+U
  993. assert.strictEqual(editor.getText(), "line1\n");
  994. // Delete newline
  995. editor.handleInput("\x15"); // Ctrl+U
  996. assert.strictEqual(editor.getText(), "line1");
  997. // Delete "line1"
  998. editor.handleInput("\x15"); // Ctrl+U
  999. assert.strictEqual(editor.getText(), "");
  1000. // All deletions accumulated into one entry: "line1\nline2\nline3"
  1001. editor.handleInput("\x19"); // Ctrl+Y
  1002. assert.strictEqual(editor.getText(), "line1\nline2\nline3");
  1003. });
  1004. it("backward deletions prepend, forward deletions append during accumulation", () => {
  1005. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1006. editor.setText("prefix|suffix");
  1007. // Position cursor at |
  1008. editor.handleInput("\x01"); // Ctrl+A
  1009. for (let i = 0; i < 6; i++) editor.handleInput("\x1b[C"); // Move right 6 times
  1010. editor.handleInput("\x0b"); // Ctrl+K - deletes "suffix" (forward)
  1011. editor.handleInput("\x0b"); // Ctrl+K - deletes "|" (forward, appended)
  1012. assert.strictEqual(editor.getText(), "prefix");
  1013. editor.handleInput("\x19"); // Ctrl+Y
  1014. assert.strictEqual(editor.getText(), "prefix|suffix");
  1015. });
  1016. it("non-delete actions break kill accumulation", () => {
  1017. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1018. // Delete "baz", then type "x" to break accumulation, then delete "x"
  1019. editor.setText("foo bar baz");
  1020. editor.handleInput("\x17"); // Ctrl+W - deletes "baz"
  1021. assert.strictEqual(editor.getText(), "foo bar ");
  1022. editor.handleInput("x"); // Typing breaks accumulation
  1023. assert.strictEqual(editor.getText(), "foo bar x");
  1024. editor.handleInput("\x17"); // Ctrl+W - deletes "x" (separate entry, not accumulated)
  1025. assert.strictEqual(editor.getText(), "foo bar ");
  1026. // Yank most recent - should be "x", not "xbaz"
  1027. editor.handleInput("\x19"); // Ctrl+Y
  1028. assert.strictEqual(editor.getText(), "foo bar x");
  1029. // Cycle to previous - should be "baz" (separate entry)
  1030. editor.handleInput("\x1by"); // Alt+Y
  1031. assert.strictEqual(editor.getText(), "foo bar baz");
  1032. });
  1033. it("non-yank actions break Alt+Y chain", () => {
  1034. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1035. editor.setText("first");
  1036. editor.handleInput("\x17"); // Ctrl+W
  1037. editor.setText("second");
  1038. editor.handleInput("\x17"); // Ctrl+W
  1039. editor.setText("");
  1040. editor.handleInput("\x19"); // Ctrl+Y - yanks "second"
  1041. assert.strictEqual(editor.getText(), "second");
  1042. editor.handleInput("x"); // Type breaks yank chain
  1043. assert.strictEqual(editor.getText(), "secondx");
  1044. editor.handleInput("\x1by"); // Alt+Y - should do nothing
  1045. assert.strictEqual(editor.getText(), "secondx");
  1046. });
  1047. it("kill ring rotation persists after cycling", () => {
  1048. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1049. editor.setText("first");
  1050. editor.handleInput("\x17"); // deletes "first"
  1051. editor.setText("second");
  1052. editor.handleInput("\x17"); // deletes "second"
  1053. editor.setText("third");
  1054. editor.handleInput("\x17"); // deletes "third"
  1055. editor.setText("");
  1056. // Ring: [first, second, third]
  1057. editor.handleInput("\x19"); // Ctrl+Y - yanks "third"
  1058. editor.handleInput("\x1by"); // Alt+Y - cycles to "second", ring rotates
  1059. // Now ring is: [third, first, second]
  1060. assert.strictEqual(editor.getText(), "second");
  1061. // Do something else
  1062. editor.handleInput("x");
  1063. editor.setText("");
  1064. // New yank should get "second" (now at end after rotation)
  1065. editor.handleInput("\x19"); // Ctrl+Y
  1066. assert.strictEqual(editor.getText(), "second");
  1067. });
  1068. it("consecutive deletions across lines coalesce into one entry", () => {
  1069. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1070. // "1\n2\n3" with cursor at end, delete everything with Ctrl+W
  1071. editor.setText("1\n2\n3");
  1072. editor.handleInput("\x17"); // Ctrl+W - deletes "3"
  1073. assert.strictEqual(editor.getText(), "1\n2\n");
  1074. editor.handleInput("\x17"); // Ctrl+W - deletes newline (merge with prev line)
  1075. assert.strictEqual(editor.getText(), "1\n2");
  1076. editor.handleInput("\x17"); // Ctrl+W - deletes "2"
  1077. assert.strictEqual(editor.getText(), "1\n");
  1078. editor.handleInput("\x17"); // Ctrl+W - deletes newline
  1079. assert.strictEqual(editor.getText(), "1");
  1080. editor.handleInput("\x17"); // Ctrl+W - deletes "1"
  1081. assert.strictEqual(editor.getText(), "");
  1082. // All deletions should have accumulated into one entry
  1083. editor.handleInput("\x19"); // Ctrl+Y
  1084. assert.strictEqual(editor.getText(), "1\n2\n3");
  1085. });
  1086. it("Ctrl+K at line end deletes newline and coalesces", () => {
  1087. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1088. // "ab" on line 1, "cd" on line 2, cursor at end of line 1
  1089. editor.setText("");
  1090. editor.handleInput("a");
  1091. editor.handleInput("b");
  1092. editor.handleInput("\n");
  1093. editor.handleInput("c");
  1094. editor.handleInput("d");
  1095. // Move to end of first line
  1096. editor.handleInput("\x1b[A"); // Up arrow
  1097. editor.handleInput("\x05"); // Ctrl+E - end of line
  1098. // Now at end of "ab", Ctrl+K should delete newline (merge with "cd")
  1099. editor.handleInput("\x0b"); // Ctrl+K - deletes newline
  1100. assert.strictEqual(editor.getText(), "abcd");
  1101. // Continue deleting
  1102. editor.handleInput("\x0b"); // Ctrl+K - deletes "cd"
  1103. assert.strictEqual(editor.getText(), "ab");
  1104. // Both deletions should accumulate
  1105. editor.handleInput("\x19"); // Ctrl+Y
  1106. assert.strictEqual(editor.getText(), "ab\ncd");
  1107. });
  1108. it("handles yank in middle of text", () => {
  1109. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1110. editor.setText("word");
  1111. editor.handleInput("\x17"); // Ctrl+W - deletes "word"
  1112. editor.setText("hello world");
  1113. // Move to middle (after "hello ")
  1114. editor.handleInput("\x01"); // Ctrl+A
  1115. for (let i = 0; i < 6; i++) editor.handleInput("\x1b[C");
  1116. editor.handleInput("\x19"); // Ctrl+Y
  1117. assert.strictEqual(editor.getText(), "hello wordworld");
  1118. });
  1119. it("handles yank-pop in middle of text", () => {
  1120. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1121. // Create two kill ring entries
  1122. editor.setText("FIRST");
  1123. editor.handleInput("\x17"); // Ctrl+W - deletes "FIRST"
  1124. editor.setText("SECOND");
  1125. editor.handleInput("\x17"); // Ctrl+W - deletes "SECOND"
  1126. // Ring: ["FIRST", "SECOND"]
  1127. // Set up "hello world" and position cursor after "hello "
  1128. editor.setText("hello world");
  1129. editor.handleInput("\x01"); // Ctrl+A - go to start of line
  1130. for (let i = 0; i < 6; i++) editor.handleInput("\x1b[C"); // Move right 6
  1131. // Yank "SECOND" in the middle
  1132. editor.handleInput("\x19"); // Ctrl+Y
  1133. assert.strictEqual(editor.getText(), "hello SECONDworld");
  1134. // Yank-pop replaces "SECOND" with "FIRST"
  1135. editor.handleInput("\x1by"); // Alt+Y
  1136. assert.strictEqual(editor.getText(), "hello FIRSTworld");
  1137. });
  1138. it("multiline yank and yank-pop in middle of text", () => {
  1139. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1140. // Create single-line entry
  1141. editor.setText("SINGLE");
  1142. editor.handleInput("\x17"); // Ctrl+W - deletes "SINGLE"
  1143. // Create multiline entry via consecutive Ctrl+U
  1144. editor.setText("A\nB");
  1145. editor.handleInput("\x15"); // Ctrl+U - deletes "B"
  1146. editor.handleInput("\x15"); // Ctrl+U - deletes newline
  1147. editor.handleInput("\x15"); // Ctrl+U - deletes "A"
  1148. // Ring: ["SINGLE", "A\nB"]
  1149. // Insert in middle of "hello world"
  1150. editor.setText("hello world");
  1151. editor.handleInput("\x01"); // Ctrl+A
  1152. for (let i = 0; i < 6; i++) editor.handleInput("\x1b[C");
  1153. // Yank multiline "A\nB"
  1154. editor.handleInput("\x19"); // Ctrl+Y
  1155. assert.strictEqual(editor.getText(), "hello A\nBworld");
  1156. // Yank-pop replaces with "SINGLE"
  1157. editor.handleInput("\x1by"); // Alt+Y
  1158. assert.strictEqual(editor.getText(), "hello SINGLEworld");
  1159. });
  1160. it("Alt+D deletes word forward and saves to kill ring", () => {
  1161. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1162. editor.setText("hello world test");
  1163. editor.handleInput("\x01"); // Ctrl+A - go to start
  1164. editor.handleInput("\x1bd"); // Alt+D - deletes "hello"
  1165. assert.strictEqual(editor.getText(), " world test");
  1166. editor.handleInput("\x1bd"); // Alt+D - deletes " world" (skips whitespace, then word)
  1167. assert.strictEqual(editor.getText(), " test");
  1168. // Yank should get accumulated text
  1169. editor.handleInput("\x19"); // Ctrl+Y
  1170. assert.strictEqual(editor.getText(), "hello world test");
  1171. });
  1172. it("Alt+D at end of line deletes newline", () => {
  1173. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1174. editor.setText("line1\nline2");
  1175. // Move to start of document, then to end of first line
  1176. editor.handleInput("\x1b[A"); // Up arrow - go to first line
  1177. editor.handleInput("\x05"); // Ctrl+E - end of line
  1178. editor.handleInput("\x1bd"); // Alt+D - deletes newline (merges lines)
  1179. assert.strictEqual(editor.getText(), "line1line2");
  1180. editor.handleInput("\x19"); // Ctrl+Y
  1181. assert.strictEqual(editor.getText(), "line1\nline2");
  1182. });
  1183. });
  1184. describe("Undo", () => {
  1185. it("does nothing when undo stack is empty", () => {
  1186. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1187. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1188. assert.strictEqual(editor.getText(), "");
  1189. });
  1190. it("coalesces consecutive word characters into one undo unit", () => {
  1191. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1192. editor.handleInput("h");
  1193. editor.handleInput("e");
  1194. editor.handleInput("l");
  1195. editor.handleInput("l");
  1196. editor.handleInput("o");
  1197. editor.handleInput(" ");
  1198. editor.handleInput("w");
  1199. editor.handleInput("o");
  1200. editor.handleInput("r");
  1201. editor.handleInput("l");
  1202. editor.handleInput("d");
  1203. assert.strictEqual(editor.getText(), "hello world");
  1204. // Undo removes " world" (space captured state before it, so we restore to "hello")
  1205. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1206. assert.strictEqual(editor.getText(), "hello");
  1207. // Undo removes "hello"
  1208. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1209. assert.strictEqual(editor.getText(), "");
  1210. });
  1211. it("undoes spaces one at a time", () => {
  1212. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1213. editor.handleInput("h");
  1214. editor.handleInput("e");
  1215. editor.handleInput("l");
  1216. editor.handleInput("l");
  1217. editor.handleInput("o");
  1218. editor.handleInput(" ");
  1219. editor.handleInput(" ");
  1220. assert.strictEqual(editor.getText(), "hello ");
  1221. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo) - removes second " "
  1222. assert.strictEqual(editor.getText(), "hello ");
  1223. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo) - removes first " "
  1224. assert.strictEqual(editor.getText(), "hello");
  1225. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo) - removes "hello"
  1226. assert.strictEqual(editor.getText(), "");
  1227. });
  1228. it("undoes newlines and signals next word to capture state", () => {
  1229. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1230. editor.handleInput("h");
  1231. editor.handleInput("e");
  1232. editor.handleInput("l");
  1233. editor.handleInput("l");
  1234. editor.handleInput("o");
  1235. editor.handleInput("\n");
  1236. editor.handleInput("w");
  1237. editor.handleInput("o");
  1238. editor.handleInput("r");
  1239. editor.handleInput("l");
  1240. editor.handleInput("d");
  1241. assert.strictEqual(editor.getText(), "hello\nworld");
  1242. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1243. assert.strictEqual(editor.getText(), "hello\n");
  1244. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1245. assert.strictEqual(editor.getText(), "hello");
  1246. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1247. assert.strictEqual(editor.getText(), "");
  1248. });
  1249. it("undoes backspace", () => {
  1250. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1251. editor.handleInput("h");
  1252. editor.handleInput("e");
  1253. editor.handleInput("l");
  1254. editor.handleInput("l");
  1255. editor.handleInput("o");
  1256. editor.handleInput("\x7f"); // Backspace
  1257. assert.strictEqual(editor.getText(), "hell");
  1258. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1259. assert.strictEqual(editor.getText(), "hello");
  1260. });
  1261. it("undoes forward delete", () => {
  1262. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1263. editor.handleInput("h");
  1264. editor.handleInput("e");
  1265. editor.handleInput("l");
  1266. editor.handleInput("l");
  1267. editor.handleInput("o");
  1268. editor.handleInput("\x01"); // Ctrl+A - go to start
  1269. editor.handleInput("\x1b[C"); // Right arrow
  1270. editor.handleInput("\x1b[3~"); // Delete key
  1271. assert.strictEqual(editor.getText(), "hllo");
  1272. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1273. assert.strictEqual(editor.getText(), "hello");
  1274. });
  1275. it("undoes Ctrl+W (delete word backward)", () => {
  1276. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1277. editor.handleInput("h");
  1278. editor.handleInput("e");
  1279. editor.handleInput("l");
  1280. editor.handleInput("l");
  1281. editor.handleInput("o");
  1282. editor.handleInput(" ");
  1283. editor.handleInput("w");
  1284. editor.handleInput("o");
  1285. editor.handleInput("r");
  1286. editor.handleInput("l");
  1287. editor.handleInput("d");
  1288. assert.strictEqual(editor.getText(), "hello world");
  1289. editor.handleInput("\x17"); // Ctrl+W
  1290. assert.strictEqual(editor.getText(), "hello ");
  1291. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1292. assert.strictEqual(editor.getText(), "hello world");
  1293. });
  1294. it("undoes Ctrl+K (delete to line end)", () => {
  1295. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1296. editor.handleInput("h");
  1297. editor.handleInput("e");
  1298. editor.handleInput("l");
  1299. editor.handleInput("l");
  1300. editor.handleInput("o");
  1301. editor.handleInput(" ");
  1302. editor.handleInput("w");
  1303. editor.handleInput("o");
  1304. editor.handleInput("r");
  1305. editor.handleInput("l");
  1306. editor.handleInput("d");
  1307. editor.handleInput("\x01"); // Ctrl+A - go to start
  1308. for (let i = 0; i < 6; i++) editor.handleInput("\x1b[C"); // Move right 6 times
  1309. editor.handleInput("\x0b"); // Ctrl+K
  1310. assert.strictEqual(editor.getText(), "hello ");
  1311. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1312. assert.strictEqual(editor.getText(), "hello world");
  1313. editor.handleInput("|");
  1314. assert.strictEqual(editor.getText(), "hello |world");
  1315. });
  1316. it("undoes Ctrl+U (delete to line start)", () => {
  1317. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1318. editor.handleInput("h");
  1319. editor.handleInput("e");
  1320. editor.handleInput("l");
  1321. editor.handleInput("l");
  1322. editor.handleInput("o");
  1323. editor.handleInput(" ");
  1324. editor.handleInput("w");
  1325. editor.handleInput("o");
  1326. editor.handleInput("r");
  1327. editor.handleInput("l");
  1328. editor.handleInput("d");
  1329. editor.handleInput("\x01"); // Ctrl+A - go to start
  1330. for (let i = 0; i < 6; i++) editor.handleInput("\x1b[C"); // Move right 6 times
  1331. editor.handleInput("\x15"); // Ctrl+U
  1332. assert.strictEqual(editor.getText(), "world");
  1333. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1334. assert.strictEqual(editor.getText(), "hello world");
  1335. });
  1336. it("undoes yank", () => {
  1337. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1338. editor.handleInput("h");
  1339. editor.handleInput("e");
  1340. editor.handleInput("l");
  1341. editor.handleInput("l");
  1342. editor.handleInput("o");
  1343. editor.handleInput(" ");
  1344. editor.handleInput("\x17"); // Ctrl+W - delete "hello "
  1345. editor.handleInput("\x19"); // Ctrl+Y - yank
  1346. assert.strictEqual(editor.getText(), "hello ");
  1347. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1348. assert.strictEqual(editor.getText(), "");
  1349. });
  1350. it("undoes single-line paste atomically", () => {
  1351. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1352. editor.setText("hello world");
  1353. editor.handleInput("\x01"); // Ctrl+A - go to start
  1354. for (let i = 0; i < 5; i++) editor.handleInput("\x1b[C"); // Move right 5 (after "hello", before space)
  1355. // Simulate bracketed paste of "beep boop"
  1356. editor.handleInput("\x1b[200~beep boop\x1b[201~");
  1357. assert.strictEqual(editor.getText(), "hellobeep boop world");
  1358. // Single undo should restore entire pre-paste state
  1359. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1360. assert.strictEqual(editor.getText(), "hello world");
  1361. editor.handleInput("|");
  1362. assert.strictEqual(editor.getText(), "hello| world");
  1363. });
  1364. it("does not trigger autocomplete during single-line paste", () => {
  1365. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1366. let suggestionCalls = 0;
  1367. const mockProvider: AutocompleteProvider = {
  1368. getSuggestions: async () => {
  1369. suggestionCalls += 1;
  1370. return null;
  1371. },
  1372. applyCompletion,
  1373. };
  1374. editor.setAutocompleteProvider(mockProvider);
  1375. editor.handleInput("\x1b[200~look at @node_modules/react/index.js please\x1b[201~");
  1376. assert.strictEqual(editor.getText(), "look at @node_modules/react/index.js please");
  1377. assert.strictEqual(suggestionCalls, 0);
  1378. assert.strictEqual(editor.isShowingAutocomplete(), false);
  1379. });
  1380. it("decodes CSI-u Ctrl+letter sequences inside bracketed paste (tmux popup)", () => {
  1381. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1382. // tmux popups with extended-keys-format=csi-u re-encode \n in pastes as
  1383. // \x1b[106;5u (Ctrl+J). Without decoding, the per-char filter strips ESC
  1384. // and leaks "[106;5u" between lines. See issue #3599.
  1385. editor.handleInput("\x1b[200~line1\x1b[106;5uline2\x1b[106;5uline3\x1b[201~");
  1386. assert.strictEqual(editor.getText(), "line1\nline2\nline3");
  1387. });
  1388. it("undoes multi-line paste atomically", () => {
  1389. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1390. editor.setText("hello world");
  1391. editor.handleInput("\x01"); // Ctrl+A - go to start
  1392. for (let i = 0; i < 5; i++) editor.handleInput("\x1b[C"); // Move right 5 (after "hello", before space)
  1393. // Simulate bracketed paste of multi-line text
  1394. editor.handleInput("\x1b[200~line1\nline2\nline3\x1b[201~");
  1395. assert.strictEqual(editor.getText(), "helloline1\nline2\nline3 world");
  1396. // Single undo should restore entire pre-paste state
  1397. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1398. assert.strictEqual(editor.getText(), "hello world");
  1399. editor.handleInput("|");
  1400. assert.strictEqual(editor.getText(), "hello| world");
  1401. });
  1402. it("undoes insertTextAtCursor atomically", () => {
  1403. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1404. editor.setText("hello world");
  1405. editor.handleInput("\x01"); // Ctrl+A - go to start
  1406. for (let i = 0; i < 5; i++) editor.handleInput("\x1b[C"); // Move right 5 (after "hello", before space)
  1407. // Programmatic insertion (e.g., clipboard image path)
  1408. editor.insertTextAtCursor("/tmp/image.png");
  1409. assert.strictEqual(editor.getText(), "hello/tmp/image.png world");
  1410. // Single undo should restore entire pre-insert state
  1411. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1412. assert.strictEqual(editor.getText(), "hello world");
  1413. editor.handleInput("|");
  1414. assert.strictEqual(editor.getText(), "hello| world");
  1415. });
  1416. it("insertTextAtCursor handles multiline text", () => {
  1417. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1418. editor.setText("hello world");
  1419. editor.handleInput("\x01"); // Ctrl+A - go to start
  1420. for (let i = 0; i < 5; i++) editor.handleInput("\x1b[C"); // Move right 5 (after "hello", before space)
  1421. // Insert multiline text
  1422. editor.insertTextAtCursor("line1\nline2\nline3");
  1423. assert.strictEqual(editor.getText(), "helloline1\nline2\nline3 world");
  1424. // Cursor should be at end of inserted text (after "line3", before " world")
  1425. const cursor = editor.getCursor();
  1426. assert.strictEqual(cursor.line, 2);
  1427. assert.strictEqual(cursor.col, 5); // "line3".length
  1428. // Single undo should restore entire pre-insert state
  1429. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1430. assert.strictEqual(editor.getText(), "hello world");
  1431. });
  1432. it("insertTextAtCursor normalizes CRLF and CR line endings", () => {
  1433. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1434. editor.setText("");
  1435. // Insert text with CRLF
  1436. editor.insertTextAtCursor("a\r\nb\r\nc");
  1437. assert.strictEqual(editor.getText(), "a\nb\nc");
  1438. editor.handleInput("\x1b[45;5u"); // Undo
  1439. assert.strictEqual(editor.getText(), "");
  1440. // Insert text with CR only
  1441. editor.insertTextAtCursor("x\ry\rz");
  1442. assert.strictEqual(editor.getText(), "x\ny\nz");
  1443. });
  1444. it("undoes setText to empty string", () => {
  1445. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1446. editor.handleInput("h");
  1447. editor.handleInput("e");
  1448. editor.handleInput("l");
  1449. editor.handleInput("l");
  1450. editor.handleInput("o");
  1451. editor.handleInput(" ");
  1452. editor.handleInput("w");
  1453. editor.handleInput("o");
  1454. editor.handleInput("r");
  1455. editor.handleInput("l");
  1456. editor.handleInput("d");
  1457. assert.strictEqual(editor.getText(), "hello world");
  1458. editor.setText("");
  1459. assert.strictEqual(editor.getText(), "");
  1460. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1461. assert.strictEqual(editor.getText(), "hello world");
  1462. });
  1463. it("clears undo stack on submit", () => {
  1464. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1465. let submitted = "";
  1466. editor.onSubmit = (text) => {
  1467. submitted = text;
  1468. };
  1469. editor.handleInput("h");
  1470. editor.handleInput("e");
  1471. editor.handleInput("l");
  1472. editor.handleInput("l");
  1473. editor.handleInput("o");
  1474. editor.handleInput("\r"); // Enter - submit
  1475. assert.strictEqual(submitted, "hello");
  1476. assert.strictEqual(editor.getText(), "");
  1477. // Undo should do nothing - stack was cleared
  1478. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1479. assert.strictEqual(editor.getText(), "");
  1480. });
  1481. it("exits history browsing mode on undo", () => {
  1482. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1483. // Add "hello" to history
  1484. editor.addToHistory("hello");
  1485. assert.strictEqual(editor.getText(), "");
  1486. // Type "world"
  1487. editor.handleInput("w");
  1488. editor.handleInput("o");
  1489. editor.handleInput("r");
  1490. editor.handleInput("l");
  1491. editor.handleInput("d");
  1492. assert.strictEqual(editor.getText(), "world");
  1493. // Ctrl+W - delete word
  1494. editor.handleInput("\x17"); // Ctrl+W
  1495. assert.strictEqual(editor.getText(), "");
  1496. // Press Up - enter history browsing, shows "hello"
  1497. editor.handleInput("\x1b[A"); // Up arrow
  1498. assert.strictEqual(editor.getText(), "hello");
  1499. // Undo should restore to "" (state before entering history browsing)
  1500. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1501. assert.strictEqual(editor.getText(), "");
  1502. // Undo again should restore to "world" (state before Ctrl+W)
  1503. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1504. assert.strictEqual(editor.getText(), "world");
  1505. });
  1506. it("undo restores to pre-history state even after multiple history navigations", () => {
  1507. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1508. // Add history entries
  1509. editor.addToHistory("first");
  1510. editor.addToHistory("second");
  1511. editor.addToHistory("third");
  1512. // Type something
  1513. editor.handleInput("c");
  1514. editor.handleInput("u");
  1515. editor.handleInput("r");
  1516. editor.handleInput("r");
  1517. editor.handleInput("e");
  1518. editor.handleInput("n");
  1519. editor.handleInput("t");
  1520. assert.strictEqual(editor.getText(), "current");
  1521. // Clear editor
  1522. editor.handleInput("\x17"); // Ctrl+W
  1523. assert.strictEqual(editor.getText(), "");
  1524. // Navigate through history multiple times
  1525. editor.handleInput("\x1b[A"); // Up - "third"
  1526. assert.strictEqual(editor.getText(), "third");
  1527. editor.handleInput("\x1b[A"); // Up - "second"
  1528. assert.strictEqual(editor.getText(), "second");
  1529. editor.handleInput("\x1b[A"); // Up - "first"
  1530. assert.strictEqual(editor.getText(), "first");
  1531. // Undo should go back to "" (state before we started browsing), not intermediate states
  1532. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1533. assert.strictEqual(editor.getText(), "");
  1534. // Another undo goes back to "current"
  1535. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1536. assert.strictEqual(editor.getText(), "current");
  1537. });
  1538. it("cursor movement starts new undo unit", () => {
  1539. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1540. editor.handleInput("h");
  1541. editor.handleInput("e");
  1542. editor.handleInput("l");
  1543. editor.handleInput("l");
  1544. editor.handleInput("o");
  1545. editor.handleInput(" ");
  1546. editor.handleInput("w");
  1547. editor.handleInput("o");
  1548. editor.handleInput("r");
  1549. editor.handleInput("l");
  1550. editor.handleInput("d");
  1551. assert.strictEqual(editor.getText(), "hello world");
  1552. // Move cursor left 5 (to after "hello ")
  1553. for (let i = 0; i < 5; i++) editor.handleInput("\x1b[D");
  1554. // Type "lol" in the middle
  1555. editor.handleInput("l");
  1556. editor.handleInput("o");
  1557. editor.handleInput("l");
  1558. assert.strictEqual(editor.getText(), "hello lolworld");
  1559. // Undo should restore to "hello world" (before inserting "lol")
  1560. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1561. assert.strictEqual(editor.getText(), "hello world");
  1562. editor.handleInput("|");
  1563. assert.strictEqual(editor.getText(), "hello |world");
  1564. });
  1565. it("no-op delete operations do not push undo snapshots", () => {
  1566. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1567. editor.handleInput("h");
  1568. editor.handleInput("e");
  1569. editor.handleInput("l");
  1570. editor.handleInput("l");
  1571. editor.handleInput("o");
  1572. assert.strictEqual(editor.getText(), "hello");
  1573. // Delete word on empty - multiple times (should be no-ops)
  1574. editor.handleInput("\x17"); // Ctrl+W - deletes "hello"
  1575. assert.strictEqual(editor.getText(), "");
  1576. editor.handleInput("\x17"); // Ctrl+W - no-op (nothing to delete)
  1577. editor.handleInput("\x17"); // Ctrl+W - no-op
  1578. // Single undo should restore "hello"
  1579. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1580. assert.strictEqual(editor.getText(), "hello");
  1581. });
  1582. it("undoes autocomplete", async () => {
  1583. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1584. // Create a mock autocomplete provider
  1585. const mockProvider: AutocompleteProvider = {
  1586. getSuggestions: async (lines, _cursorLine, cursorCol) => {
  1587. const text = lines[0] || "";
  1588. const prefix = text.slice(0, cursorCol);
  1589. if (prefix === "di") {
  1590. return {
  1591. items: [{ value: "dist/", label: "dist/" }],
  1592. prefix: "di",
  1593. };
  1594. }
  1595. return null;
  1596. },
  1597. applyCompletion,
  1598. };
  1599. editor.setAutocompleteProvider(mockProvider);
  1600. // Type "di"
  1601. editor.handleInput("d");
  1602. editor.handleInput("i");
  1603. assert.strictEqual(editor.getText(), "di");
  1604. // Press Tab to trigger autocomplete
  1605. editor.handleInput("\t");
  1606. await flushAutocomplete();
  1607. assert.strictEqual(editor.getText(), "dist/");
  1608. assert.strictEqual(editor.isShowingAutocomplete(), false);
  1609. // Undo should restore to "di"
  1610. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1611. assert.strictEqual(editor.getText(), "di");
  1612. });
  1613. });
  1614. describe("Autocomplete", () => {
  1615. it("auto-applies single force-file suggestion without showing menu", async () => {
  1616. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1617. const mockProvider: AutocompleteProvider = {
  1618. getSuggestions: async (lines, _cursorLine, cursorCol, options) => {
  1619. if (!options.force) {
  1620. return null;
  1621. }
  1622. const text = lines[0] || "";
  1623. const prefix = text.slice(0, cursorCol);
  1624. if (prefix === "Work") {
  1625. return {
  1626. items: [{ value: "Workspace/", label: "Workspace/" }],
  1627. prefix: "Work",
  1628. };
  1629. }
  1630. return null;
  1631. },
  1632. applyCompletion,
  1633. };
  1634. editor.setAutocompleteProvider(mockProvider);
  1635. // Type "Work"
  1636. editor.handleInput("W");
  1637. editor.handleInput("o");
  1638. editor.handleInput("r");
  1639. editor.handleInput("k");
  1640. assert.strictEqual(editor.getText(), "Work");
  1641. // Press Tab - should auto-apply without showing menu
  1642. editor.handleInput("\t");
  1643. await flushAutocomplete();
  1644. assert.strictEqual(editor.getText(), "Workspace/");
  1645. assert.strictEqual(editor.isShowingAutocomplete(), false);
  1646. // Undo should restore to "Work"
  1647. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  1648. assert.strictEqual(editor.getText(), "Work");
  1649. });
  1650. it("shows menu when force-file has multiple suggestions", async () => {
  1651. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1652. const mockProvider: AutocompleteProvider = {
  1653. getSuggestions: async (lines, _cursorLine, cursorCol, options) => {
  1654. if (!options.force) {
  1655. return null;
  1656. }
  1657. const text = lines[0] || "";
  1658. const prefix = text.slice(0, cursorCol);
  1659. if (prefix === "src") {
  1660. return {
  1661. items: [
  1662. { value: "src/", label: "src/" },
  1663. { value: "src.txt", label: "src.txt" },
  1664. ],
  1665. prefix: "src",
  1666. };
  1667. }
  1668. return null;
  1669. },
  1670. applyCompletion,
  1671. };
  1672. editor.setAutocompleteProvider(mockProvider);
  1673. // Type "src"
  1674. editor.handleInput("s");
  1675. editor.handleInput("r");
  1676. editor.handleInput("c");
  1677. assert.strictEqual(editor.getText(), "src");
  1678. // Press Tab - should show menu because there are multiple suggestions
  1679. editor.handleInput("\t");
  1680. await flushAutocomplete();
  1681. assert.strictEqual(editor.getText(), "src");
  1682. assert.strictEqual(editor.isShowingAutocomplete(), true);
  1683. // Press Tab again to accept first suggestion
  1684. editor.handleInput("\t");
  1685. assert.strictEqual(editor.getText(), "src/");
  1686. assert.strictEqual(editor.isShowingAutocomplete(), false);
  1687. });
  1688. it("keeps suggestions open when typing in force mode (Tab-triggered)", async () => {
  1689. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1690. const allFiles = [
  1691. { value: "readme.md", label: "readme.md" },
  1692. { value: "package.json", label: "package.json" },
  1693. { value: "src/", label: "src/" },
  1694. { value: "dist/", label: "dist/" },
  1695. ];
  1696. const mockProvider: AutocompleteProvider = {
  1697. getSuggestions: async (lines, _cursorLine, cursorCol, options) => {
  1698. const text = lines[0] || "";
  1699. const prefix = text.slice(0, cursorCol);
  1700. const shouldMatch = options.force || prefix.includes("/") || prefix.startsWith(".");
  1701. if (!shouldMatch) {
  1702. return null;
  1703. }
  1704. const filtered = allFiles.filter((f) => f.value.toLowerCase().startsWith(prefix.toLowerCase()));
  1705. if (filtered.length > 0) {
  1706. return { items: filtered, prefix };
  1707. }
  1708. return null;
  1709. },
  1710. applyCompletion,
  1711. };
  1712. editor.setAutocompleteProvider(mockProvider);
  1713. // Press Tab on empty prompt - should show all files (force mode)
  1714. editor.handleInput("\t");
  1715. await flushAutocomplete();
  1716. assert.strictEqual(editor.isShowingAutocomplete(), true);
  1717. // Type "r" - should narrow to "readme.md" (force mode keeps suggestions open)
  1718. editor.handleInput("r");
  1719. await flushAutocomplete();
  1720. assert.strictEqual(editor.getText(), "r");
  1721. assert.strictEqual(editor.isShowingAutocomplete(), true);
  1722. // Type "e" - should still show "readme.md"
  1723. editor.handleInput("e");
  1724. await flushAutocomplete();
  1725. assert.strictEqual(editor.getText(), "re");
  1726. assert.strictEqual(editor.isShowingAutocomplete(), true);
  1727. // Accept with Tab
  1728. editor.handleInput("\t");
  1729. assert.strictEqual(editor.getText(), "readme.md");
  1730. assert.strictEqual(editor.isShowingAutocomplete(), false);
  1731. });
  1732. it("debounces @ autocomplete while typing", async () => {
  1733. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1734. let suggestionCalls = 0;
  1735. const mockProvider: AutocompleteProvider = {
  1736. getSuggestions: async (lines, _cursorLine, cursorCol) => {
  1737. suggestionCalls += 1;
  1738. const text = (lines[0] || "").slice(0, cursorCol);
  1739. return {
  1740. items: [{ value: "@main.ts", label: "main.ts" }],
  1741. prefix: text,
  1742. };
  1743. },
  1744. applyCompletion,
  1745. };
  1746. editor.setAutocompleteProvider(mockProvider);
  1747. editor.handleInput("@");
  1748. editor.handleInput("m");
  1749. editor.handleInput("a");
  1750. editor.handleInput("i");
  1751. assert.strictEqual(suggestionCalls, 0);
  1752. assert.strictEqual(editor.isShowingAutocomplete(), false);
  1753. await new Promise((resolve) => setTimeout(resolve, 50));
  1754. await flushAutocomplete();
  1755. assert.strictEqual(suggestionCalls, 1);
  1756. assert.strictEqual(editor.isShowingAutocomplete(), true);
  1757. });
  1758. it("re-queries the autocomplete picker when the cursor moves back into the command name", async () => {
  1759. // Regression for earendil-works/pi#5496: arrowing left out of a slash
  1760. // command's argument region must re-query the picker, not leave the
  1761. // stale argument list showing. Before the fix, moveCursor() never
  1762. // called updateAutocomplete(), so `/cmd ` (argument menu) + Left kept
  1763. // displaying the arguments against a `/cmd` prefix — and a Tab there
  1764. // would concatenate the stale suggestion onto the partial command name.
  1765. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1766. const mockProvider: AutocompleteProvider = {
  1767. getSuggestions: async (lines, _cursorLine, cursorCol) => {
  1768. const before = (lines[0] || "").slice(0, cursorCol);
  1769. if (!before.startsWith("/")) return null;
  1770. // Past the command name (a space before the cursor): offer arguments.
  1771. if (before.includes(" ")) {
  1772. return {
  1773. items: [
  1774. { value: "repo", label: "repo" },
  1775. { value: "message", label: "message" },
  1776. { value: "help", label: "help" },
  1777. ],
  1778. prefix: before.slice(before.indexOf(" ") + 1),
  1779. };
  1780. }
  1781. // Inside the command name: offer the command name only.
  1782. return { items: [{ value: "cmd", label: "cmd" }], prefix: before };
  1783. },
  1784. applyCompletion,
  1785. };
  1786. editor.setAutocompleteProvider(mockProvider);
  1787. // Type `/cmd ` so the picker ends up showing the argument list.
  1788. for (const ch of "/cmd ") {
  1789. editor.handleInput(ch);
  1790. await flushAutocomplete();
  1791. }
  1792. assert.strictEqual(editor.getText(), "/cmd ");
  1793. assert.strictEqual(editor.isShowingAutocomplete(), true);
  1794. const atArg = editor
  1795. .render(80)
  1796. .map((l) => stripVTControlCharacters(l))
  1797. .join("\n");
  1798. assert.ok(atArg.includes("repo"), "argument menu should be visible at `/cmd `");
  1799. // Arrow Left back into the command name (`/cmd`).
  1800. editor.handleInput("\x1b[D");
  1801. await flushAutocomplete();
  1802. // The picker must have re-queried: the stale argument items are gone
  1803. // (replaced by the command-name suggestion, or the picker closed).
  1804. const afterMove = editor
  1805. .render(80)
  1806. .map((l) => stripVTControlCharacters(l))
  1807. .join("\n");
  1808. assert.ok(!afterMove.includes("repo"), "stale argument menu must not survive the cursor move");
  1809. assert.ok(!afterMove.includes("message"), "stale argument menu must not survive the cursor move");
  1810. });
  1811. it("debounces # autocomplete while typing", async () => {
  1812. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1813. let suggestionCalls = 0;
  1814. const mockProvider: AutocompleteProvider = {
  1815. getSuggestions: async (lines, _cursorLine, cursorCol) => {
  1816. suggestionCalls += 1;
  1817. const text = (lines[0] || "").slice(0, cursorCol);
  1818. return {
  1819. items: [{ value: "#2983", label: "#2983" }],
  1820. prefix: text,
  1821. };
  1822. },
  1823. applyCompletion,
  1824. };
  1825. editor.setAutocompleteProvider(mockProvider);
  1826. editor.handleInput("#");
  1827. editor.handleInput("2");
  1828. editor.handleInput("9");
  1829. editor.handleInput("8");
  1830. assert.strictEqual(suggestionCalls, 0);
  1831. assert.strictEqual(editor.isShowingAutocomplete(), false);
  1832. await new Promise((resolve) => setTimeout(resolve, 50));
  1833. await flushAutocomplete();
  1834. assert.strictEqual(suggestionCalls, 1);
  1835. assert.strictEqual(editor.isShowingAutocomplete(), true);
  1836. });
  1837. it("debounces custom triggerCharacters autocomplete while typing", async () => {
  1838. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1839. let suggestionCalls = 0;
  1840. editor.setAutocompleteProvider({
  1841. triggerCharacters: ["$"],
  1842. getSuggestions: async (lines, _cursorLine, cursorCol) => {
  1843. suggestionCalls += 1;
  1844. const prefix = (lines[0] || "").slice(0, cursorCol);
  1845. return { items: [{ value: "$skill-name", label: "skill-name" }], prefix };
  1846. },
  1847. applyCompletion,
  1848. });
  1849. editor.handleInput("$");
  1850. editor.handleInput("s");
  1851. editor.handleInput("k");
  1852. assert.strictEqual(suggestionCalls, 0);
  1853. await new Promise((resolve) => setTimeout(resolve, 50));
  1854. await flushAutocomplete();
  1855. assert.strictEqual(suggestionCalls, 1);
  1856. assert.strictEqual(editor.isShowingAutocomplete(), true);
  1857. });
  1858. it("resets custom triggerCharacters when provider changes", async () => {
  1859. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1860. let suggestionCalls = 0;
  1861. editor.setAutocompleteProvider({
  1862. triggerCharacters: ["$"],
  1863. getSuggestions: async () => ({ items: [{ value: "$skill-name", label: "skill-name" }], prefix: "$" }),
  1864. applyCompletion,
  1865. });
  1866. editor.setAutocompleteProvider({
  1867. getSuggestions: async () => {
  1868. suggestionCalls += 1;
  1869. return { items: [{ value: "$skill-name", label: "skill-name" }], prefix: "$" };
  1870. },
  1871. applyCompletion,
  1872. });
  1873. editor.handleInput("$");
  1874. editor.handleInput("s");
  1875. await new Promise((resolve) => setTimeout(resolve, 50));
  1876. await flushAutocomplete();
  1877. assert.strictEqual(suggestionCalls, 0);
  1878. assert.strictEqual(editor.isShowingAutocomplete(), false);
  1879. });
  1880. it("aborts active @ autocomplete when typing continues", async () => {
  1881. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1882. let aborts = 0;
  1883. const mockProvider: AutocompleteProvider = {
  1884. getSuggestions: async (_lines, _cursorLine, _cursorCol, options) => {
  1885. return await new Promise((resolve) => {
  1886. const timeout = setTimeout(() => {
  1887. resolve({ items: [{ value: "@main.ts", label: "main.ts" }], prefix: "@main" });
  1888. }, 500);
  1889. options.signal.addEventListener(
  1890. "abort",
  1891. () => {
  1892. aborts += 1;
  1893. clearTimeout(timeout);
  1894. resolve(null);
  1895. },
  1896. { once: true },
  1897. );
  1898. });
  1899. },
  1900. applyCompletion,
  1901. };
  1902. editor.setAutocompleteProvider(mockProvider);
  1903. editor.handleInput("@");
  1904. editor.handleInput("m");
  1905. editor.handleInput("a");
  1906. editor.handleInput("i");
  1907. await new Promise((resolve) => setTimeout(resolve, 250));
  1908. editor.handleInput("n");
  1909. await new Promise((resolve) => setTimeout(resolve, 50));
  1910. assert.strictEqual(aborts, 1);
  1911. });
  1912. it("hides autocomplete when backspacing slash command to empty", async () => {
  1913. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1914. // Mock provider with slash commands
  1915. const mockProvider: AutocompleteProvider = {
  1916. getSuggestions: async (lines, _cursorLine, cursorCol) => {
  1917. const text = lines[0] || "";
  1918. const prefix = text.slice(0, cursorCol);
  1919. // Only return slash command suggestions when line starts with /
  1920. if (prefix.startsWith("/")) {
  1921. const commands = [
  1922. { value: "/model", label: "model", description: "Change model" },
  1923. { value: "/help", label: "help", description: "Show help" },
  1924. ];
  1925. const query = prefix.slice(1); // Remove leading /
  1926. const filtered = commands.filter((c) => c.value.startsWith(query));
  1927. if (filtered.length > 0) {
  1928. return { items: filtered, prefix };
  1929. }
  1930. }
  1931. return null;
  1932. },
  1933. applyCompletion,
  1934. };
  1935. editor.setAutocompleteProvider(mockProvider);
  1936. // Type "/" - should show slash command suggestions
  1937. editor.handleInput("/");
  1938. await flushAutocomplete();
  1939. assert.strictEqual(editor.getText(), "/");
  1940. assert.strictEqual(editor.isShowingAutocomplete(), true);
  1941. // Backspace to delete "/" - should hide autocomplete completely
  1942. editor.handleInput("\x7f"); // Backspace
  1943. await flushAutocomplete();
  1944. assert.strictEqual(editor.getText(), "");
  1945. assert.strictEqual(editor.isShowingAutocomplete(), false);
  1946. });
  1947. it("applies exact typed slash-argument value on Enter even when first item is highlighted", async () => {
  1948. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1949. // Mock provider for /argtest command with argument completions
  1950. const mockProvider: AutocompleteProvider = {
  1951. getSuggestions: async (lines, _cursorLine, cursorCol) => {
  1952. const text = lines[0] || "";
  1953. const beforeCursor = text.slice(0, cursorCol);
  1954. // Check if we're in argument completion context: "/argtest <prefix>"
  1955. const argtestMatch = beforeCursor.match(/^\/argtest\s+(\S+)$/);
  1956. if (argtestMatch) {
  1957. const argumentText = argtestMatch[1]!;
  1958. const allArguments = [
  1959. { value: "one", label: "one" },
  1960. { value: "two", label: "two" },
  1961. { value: "three", label: "three" },
  1962. ];
  1963. // Return all arguments that start with the typed prefix
  1964. const filtered = allArguments.filter((arg) => arg.value.startsWith(argumentText));
  1965. if (filtered.length > 0) {
  1966. return { items: filtered, prefix: argumentText };
  1967. }
  1968. }
  1969. return null;
  1970. },
  1971. applyCompletion,
  1972. };
  1973. editor.setAutocompleteProvider(mockProvider);
  1974. // Type "/argtest two"
  1975. editor.handleInput("/");
  1976. editor.handleInput("a");
  1977. editor.handleInput("r");
  1978. editor.handleInput("g");
  1979. editor.handleInput("t");
  1980. editor.handleInput("e");
  1981. editor.handleInput("s");
  1982. editor.handleInput("t");
  1983. editor.handleInput(" ");
  1984. editor.handleInput("t");
  1985. editor.handleInput("w");
  1986. editor.handleInput("o");
  1987. assert.strictEqual(editor.getText(), "/argtest two");
  1988. await flushAutocomplete();
  1989. assert.strictEqual(editor.isShowingAutocomplete(), true);
  1990. // Press Enter - should apply the exact typed value "two", not the first item
  1991. editor.handleInput("\r");
  1992. // The exact typed value "two" should be retained
  1993. assert.strictEqual(editor.getText(), "/argtest two");
  1994. });
  1995. it("selects first prefix match on Enter when typed arg is not exact match", async () => {
  1996. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  1997. // Mock provider for /argtest command with argument completions
  1998. const mockProvider: AutocompleteProvider = {
  1999. getSuggestions: async (lines, _cursorLine, cursorCol) => {
  2000. const text = lines[0] || "";
  2001. const beforeCursor = text.slice(0, cursorCol);
  2002. // Check if we're in argument completion context
  2003. const argtestMatch = beforeCursor.match(/^\/argtest\s+(\S+)$/);
  2004. if (argtestMatch) {
  2005. const argumentText = argtestMatch[1]!;
  2006. const allArguments = [
  2007. { value: "two", label: "two" },
  2008. { value: "three", label: "three" },
  2009. { value: "twelve", label: "twelve" },
  2010. ];
  2011. // Return all items that start with the typed prefix
  2012. const filtered = allArguments.filter((arg) => arg.value.startsWith(argumentText));
  2013. if (filtered.length > 0) {
  2014. return { items: filtered, prefix: argumentText };
  2015. }
  2016. }
  2017. return null;
  2018. },
  2019. applyCompletion,
  2020. };
  2021. editor.setAutocompleteProvider(mockProvider);
  2022. // Type "/argtest t" - filtered to [two, three, twelve], prefix "t" matches "two" first
  2023. editor.handleInput("/");
  2024. editor.handleInput("a");
  2025. editor.handleInput("r");
  2026. editor.handleInput("g");
  2027. editor.handleInput("t");
  2028. editor.handleInput("e");
  2029. editor.handleInput("s");
  2030. editor.handleInput("t");
  2031. editor.handleInput(" ");
  2032. editor.handleInput("t");
  2033. await flushAutocomplete();
  2034. assert.strictEqual(editor.isShowingAutocomplete(), true);
  2035. // Press Enter - "t" prefix matches "two" (first in list), so "two" is applied
  2036. editor.handleInput("\r");
  2037. assert.strictEqual(editor.getText(), "/argtest two");
  2038. });
  2039. it("highlights unique prefix match as user types (before full exact match)", async () => {
  2040. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2041. // Mock provider that returns all items unfiltered (like real extensions do)
  2042. const mockProvider: AutocompleteProvider = {
  2043. getSuggestions: async (lines, _cursorLine, cursorCol) => {
  2044. const text = lines[0] || "";
  2045. const beforeCursor = text.slice(0, cursorCol);
  2046. const argtestMatch = beforeCursor.match(/^\/argtest\s+(\S+)$/);
  2047. if (argtestMatch) {
  2048. const argumentText = argtestMatch[1]!;
  2049. // Return all items - provider does not filter
  2050. const allArguments = [
  2051. { value: "one", label: "one" },
  2052. { value: "two", label: "two" },
  2053. { value: "three", label: "three" },
  2054. ];
  2055. return { items: allArguments, prefix: argumentText };
  2056. }
  2057. return null;
  2058. },
  2059. applyCompletion,
  2060. };
  2061. editor.setAutocompleteProvider(mockProvider);
  2062. // Type "/argtest tw" - "tw" is a prefix of only "two"
  2063. editor.handleInput("/");
  2064. editor.handleInput("a");
  2065. editor.handleInput("r");
  2066. editor.handleInput("g");
  2067. editor.handleInput("t");
  2068. editor.handleInput("e");
  2069. editor.handleInput("s");
  2070. editor.handleInput("t");
  2071. editor.handleInput(" ");
  2072. editor.handleInput("t");
  2073. editor.handleInput("w");
  2074. assert.strictEqual(editor.getText(), "/argtest tw");
  2075. await flushAutocomplete();
  2076. assert.strictEqual(editor.isShowingAutocomplete(), true);
  2077. // Press Enter - "tw" uniquely matches "two", so "two" should be applied
  2078. editor.handleInput("\r");
  2079. assert.strictEqual(editor.getText(), "/argtest two");
  2080. });
  2081. it("selects first prefix match when multiple items match", async () => {
  2082. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2083. // Mock provider that returns all items unfiltered
  2084. const mockProvider: AutocompleteProvider = {
  2085. getSuggestions: async (lines, _cursorLine, cursorCol) => {
  2086. const text = lines[0] || "";
  2087. const beforeCursor = text.slice(0, cursorCol);
  2088. const argtestMatch = beforeCursor.match(/^\/argtest\s+(\S+)$/);
  2089. if (argtestMatch) {
  2090. const argumentText = argtestMatch[1]!;
  2091. const allArguments = [
  2092. { value: "one", label: "one" },
  2093. { value: "two", label: "two" },
  2094. { value: "three", label: "three" },
  2095. ];
  2096. return { items: allArguments, prefix: argumentText };
  2097. }
  2098. return null;
  2099. },
  2100. applyCompletion,
  2101. };
  2102. editor.setAutocompleteProvider(mockProvider);
  2103. // Type "/argtest t" - "t" is a prefix of both "two" and "three"
  2104. editor.handleInput("/");
  2105. editor.handleInput("a");
  2106. editor.handleInput("r");
  2107. editor.handleInput("g");
  2108. editor.handleInput("t");
  2109. editor.handleInput("e");
  2110. editor.handleInput("s");
  2111. editor.handleInput("t");
  2112. editor.handleInput(" ");
  2113. editor.handleInput("t");
  2114. await flushAutocomplete();
  2115. assert.strictEqual(editor.isShowingAutocomplete(), true);
  2116. // Press Enter - "t" matches "two" first, so "two" is selected
  2117. editor.handleInput("\r");
  2118. assert.strictEqual(editor.getText(), "/argtest two");
  2119. });
  2120. it("works for built-in-style command argument completion path (model-like)", async () => {
  2121. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2122. // Mock provider for /model command with model completions
  2123. const mockProvider: AutocompleteProvider = {
  2124. getSuggestions: async (lines, _cursorLine, cursorCol) => {
  2125. const text = lines[0] || "";
  2126. const beforeCursor = text.slice(0, cursorCol);
  2127. // Check if we're in /model argument completion context
  2128. // Use [^ ]+ to match any non-space characters (including hyphens)
  2129. const modelMatch = beforeCursor.match(/^\/model\s+(\S+)$/);
  2130. if (modelMatch) {
  2131. const modelText = modelMatch[1]!;
  2132. const allModels = [
  2133. { value: "gpt-4o", label: "gpt-4o" },
  2134. { value: "gpt-4o-mini", label: "gpt-4o-mini" },
  2135. { value: "claude-sonnet", label: "claude-sonnet" },
  2136. ];
  2137. // Return all models that start with the typed prefix
  2138. const filtered = allModels.filter((m) => m.value.startsWith(modelText));
  2139. if (filtered.length > 0) {
  2140. return { items: filtered, prefix: modelText };
  2141. }
  2142. }
  2143. return null;
  2144. },
  2145. applyCompletion,
  2146. };
  2147. editor.setAutocompleteProvider(mockProvider);
  2148. // Type "/model gpt-4o-mini" - exact match for second item in list
  2149. editor.handleInput("/");
  2150. editor.handleInput("m");
  2151. editor.handleInput("o");
  2152. editor.handleInput("d");
  2153. editor.handleInput("e");
  2154. editor.handleInput("l");
  2155. editor.handleInput(" ");
  2156. editor.handleInput("g");
  2157. editor.handleInput("p");
  2158. editor.handleInput("t");
  2159. editor.handleInput("-");
  2160. editor.handleInput("4");
  2161. editor.handleInput("o");
  2162. editor.handleInput("-");
  2163. editor.handleInput("m");
  2164. editor.handleInput("i");
  2165. editor.handleInput("n");
  2166. editor.handleInput("i");
  2167. assert.strictEqual(editor.getText(), "/model gpt-4o-mini");
  2168. await flushAutocomplete();
  2169. assert.strictEqual(editor.isShowingAutocomplete(), true);
  2170. // Press Enter - should retain exact typed value, not apply first highlighted item
  2171. editor.handleInput("\r");
  2172. // The exact typed value should be retained
  2173. assert.strictEqual(editor.getText(), "/model gpt-4o-mini");
  2174. });
  2175. it("awaits async slash command argument completions", async () => {
  2176. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2177. const provider = new CombinedAutocompleteProvider(
  2178. [
  2179. {
  2180. name: "load-skills",
  2181. description: "Load skills",
  2182. getArgumentCompletions: async (prefix) =>
  2183. prefix.startsWith("s") ? [{ value: "skill-a", label: "skill-a" }] : null,
  2184. },
  2185. ],
  2186. process.cwd(),
  2187. );
  2188. editor.setAutocompleteProvider(provider);
  2189. editor.setText("/load-skills ");
  2190. editor.handleInput("s");
  2191. await flushAutocomplete();
  2192. assert.strictEqual(editor.isShowingAutocomplete(), true);
  2193. editor.handleInput("\t");
  2194. assert.strictEqual(editor.getText(), "/load-skills skill-a");
  2195. assert.strictEqual(editor.isShowingAutocomplete(), false);
  2196. });
  2197. it("ignores invalid slash command argument completion results", async () => {
  2198. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2199. const provider = new CombinedAutocompleteProvider(
  2200. [
  2201. {
  2202. name: "load-skills",
  2203. description: "Load skills",
  2204. getArgumentCompletions: (() => "not-an-array") as unknown as (
  2205. argumentPrefix: string,
  2206. ) => Promise<{ value: string; label: string }[] | null>,
  2207. },
  2208. ],
  2209. process.cwd(),
  2210. );
  2211. editor.setAutocompleteProvider(provider);
  2212. editor.setText("/load-skills ");
  2213. editor.handleInput("s");
  2214. await flushAutocomplete();
  2215. assert.strictEqual(editor.isShowingAutocomplete(), false);
  2216. assert.strictEqual(editor.getText(), "/load-skills s");
  2217. });
  2218. it("does not show argument completions when command has no argument completer", async () => {
  2219. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2220. const provider = new CombinedAutocompleteProvider(
  2221. [
  2222. { name: "help", description: "Show help" },
  2223. {
  2224. name: "model",
  2225. description: "Switch model",
  2226. getArgumentCompletions: () => [{ value: "claude-opus", label: "claude-opus" }],
  2227. },
  2228. ],
  2229. process.cwd(),
  2230. );
  2231. editor.setAutocompleteProvider(provider);
  2232. editor.handleInput("/");
  2233. editor.handleInput("h");
  2234. editor.handleInput("e");
  2235. await flushAutocomplete();
  2236. assert.strictEqual(editor.isShowingAutocomplete(), true);
  2237. editor.handleInput("\t");
  2238. assert.strictEqual(editor.getText(), "/help ");
  2239. assert.strictEqual(editor.isShowingAutocomplete(), false);
  2240. });
  2241. });
  2242. describe("Character jump (Ctrl+])", () => {
  2243. it("jumps forward to first occurrence of character on same line", () => {
  2244. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2245. editor.setText("hello world");
  2246. editor.handleInput("\x01"); // Ctrl+A - go to start
  2247. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
  2248. editor.handleInput("\x1d"); // Ctrl+] (legacy sequence for ctrl+])
  2249. editor.handleInput("o"); // Jump to first 'o'
  2250. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 4 }); // 'o' in "hello"
  2251. });
  2252. it("jumps forward to next occurrence after cursor", () => {
  2253. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2254. editor.setText("hello world");
  2255. editor.handleInput("\x01"); // Ctrl+A - go to start
  2256. // Move cursor to the 'o' in "hello" (col 4)
  2257. for (let i = 0; i < 4; i++) editor.handleInput("\x1b[C");
  2258. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 4 });
  2259. editor.handleInput("\x1d"); // Ctrl+]
  2260. editor.handleInput("o"); // Jump to next 'o' (in "world")
  2261. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 7 }); // 'o' in "world"
  2262. });
  2263. it("jumps forward across multiple lines", () => {
  2264. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2265. editor.setText("abc\ndef\nghi");
  2266. // Cursor is at end (line 2, col 3). Move to line 0 via up arrows, then Ctrl+A
  2267. editor.handleInput("\x1b[A"); // Up
  2268. editor.handleInput("\x1b[A"); // Up - now on line 0
  2269. editor.handleInput("\x01"); // Ctrl+A - go to start of line
  2270. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
  2271. editor.handleInput("\x1d"); // Ctrl+]
  2272. editor.handleInput("g"); // Jump to 'g' on line 3
  2273. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 0 });
  2274. });
  2275. it("jumps backward to first occurrence before cursor on same line", () => {
  2276. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2277. editor.setText("hello world");
  2278. // Cursor at end (col 11)
  2279. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 11 });
  2280. editor.handleInput("\x1b\x1d"); // Ctrl+Alt+] (ESC followed by Ctrl+])
  2281. editor.handleInput("o"); // Jump to last 'o' before cursor
  2282. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 7 }); // 'o' in "world"
  2283. });
  2284. it("jumps backward across multiple lines", () => {
  2285. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2286. editor.setText("abc\ndef\nghi");
  2287. // Cursor at end of line 3
  2288. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 3 });
  2289. editor.handleInput("\x1b\x1d"); // Ctrl+Alt+]
  2290. editor.handleInput("a"); // Jump to 'a' on line 1
  2291. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
  2292. });
  2293. it("does nothing when character is not found (forward)", () => {
  2294. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2295. editor.setText("hello world");
  2296. editor.handleInput("\x01"); // Ctrl+A - go to start
  2297. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
  2298. editor.handleInput("\x1d"); // Ctrl+]
  2299. editor.handleInput("z"); // 'z' doesn't exist
  2300. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 }); // Cursor unchanged
  2301. });
  2302. it("does nothing when character is not found (backward)", () => {
  2303. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2304. editor.setText("hello world");
  2305. // Cursor at end
  2306. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 11 });
  2307. editor.handleInput("\x1b\x1d"); // Ctrl+Alt+]
  2308. editor.handleInput("z"); // 'z' doesn't exist
  2309. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 11 }); // Cursor unchanged
  2310. });
  2311. it("is case-sensitive", () => {
  2312. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2313. editor.setText("Hello World");
  2314. editor.handleInput("\x01"); // Ctrl+A - go to start
  2315. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
  2316. // Search for lowercase 'h' - should not find it (only 'H' exists)
  2317. editor.handleInput("\x1d"); // Ctrl+]
  2318. editor.handleInput("h");
  2319. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 }); // Cursor unchanged
  2320. // Search for uppercase 'W' - should find it
  2321. editor.handleInput("\x1d"); // Ctrl+]
  2322. editor.handleInput("W");
  2323. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 6 }); // 'W' in "World"
  2324. });
  2325. it("cancels jump mode when Ctrl+] is pressed again", () => {
  2326. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2327. editor.setText("hello world");
  2328. editor.handleInput("\x01"); // Ctrl+A - go to start
  2329. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
  2330. editor.handleInput("\x1d"); // Ctrl+] - enter jump mode
  2331. editor.handleInput("\x1d"); // Ctrl+] again - cancel
  2332. // Type 'o' normally - should insert, not jump
  2333. editor.handleInput("o");
  2334. assert.strictEqual(editor.getText(), "ohello world");
  2335. });
  2336. it("cancels jump mode on Escape and processes the Escape", () => {
  2337. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2338. editor.setText("hello world");
  2339. editor.handleInput("\x01"); // Ctrl+A - go to start
  2340. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
  2341. editor.handleInput("\x1d"); // Ctrl+] - enter jump mode
  2342. editor.handleInput("\x1b"); // Escape - cancel jump mode
  2343. // Cursor should be unchanged (Escape itself doesn't move cursor in editor)
  2344. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
  2345. // Type 'o' normally - should insert, not jump
  2346. editor.handleInput("o");
  2347. assert.strictEqual(editor.getText(), "ohello world");
  2348. });
  2349. it("cancels backward jump mode when Ctrl+Alt+] is pressed again", () => {
  2350. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2351. editor.setText("hello world");
  2352. // Cursor at end
  2353. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 11 });
  2354. editor.handleInput("\x1b\x1d"); // Ctrl+Alt+] - enter backward jump mode
  2355. editor.handleInput("\x1b\x1d"); // Ctrl+Alt+] again - cancel
  2356. // Type 'o' normally - should insert, not jump
  2357. editor.handleInput("o");
  2358. assert.strictEqual(editor.getText(), "hello worldo");
  2359. });
  2360. it("searches for special characters", () => {
  2361. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2362. editor.setText("foo(bar) = baz;");
  2363. editor.handleInput("\x01"); // Ctrl+A - go to start
  2364. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
  2365. // Jump to '('
  2366. editor.handleInput("\x1d"); // Ctrl+]
  2367. editor.handleInput("(");
  2368. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 3 });
  2369. // Jump to '='
  2370. editor.handleInput("\x1d"); // Ctrl+]
  2371. editor.handleInput("=");
  2372. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 9 });
  2373. });
  2374. it("handles empty text gracefully", () => {
  2375. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2376. editor.setText("");
  2377. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
  2378. editor.handleInput("\x1d"); // Ctrl+]
  2379. editor.handleInput("x");
  2380. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 }); // Cursor unchanged
  2381. });
  2382. it("resets lastAction when jumping", () => {
  2383. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2384. editor.setText("hello world");
  2385. editor.handleInput("\x01"); // Ctrl+A - go to start
  2386. // Type to set lastAction to "type-word"
  2387. editor.handleInput("x");
  2388. assert.strictEqual(editor.getText(), "xhello world");
  2389. // Jump forward
  2390. editor.handleInput("\x1d"); // Ctrl+]
  2391. editor.handleInput("o");
  2392. // Type more - should start a new undo unit (lastAction was reset)
  2393. editor.handleInput("Y");
  2394. assert.strictEqual(editor.getText(), "xhellYo world");
  2395. // Undo should only undo "Y", not "x" as well
  2396. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  2397. assert.strictEqual(editor.getText(), "xhello world");
  2398. });
  2399. });
  2400. describe("Sticky column", () => {
  2401. // Helper: position cursor at a specific line and column
  2402. function positionCursor(editor: Editor, line: number, col: number): void {
  2403. // Go to line 0 first
  2404. for (let i = 0; i < 20; i++) editor.handleInput("\x1b[A");
  2405. // Go to target line
  2406. for (let i = 0; i < line; i++) editor.handleInput("\x1b[B");
  2407. // Go to target col
  2408. editor.handleInput("\x01"); // Ctrl+A
  2409. for (let i = 0; i < col; i++) editor.handleInput("\x1b[C");
  2410. }
  2411. it("preserves target column when moving up through a shorter line", () => {
  2412. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2413. // Line 0: "2222222222x222" (x at col 10)
  2414. // Line 1: "" (empty)
  2415. // Line 2: "1111111111_111111111111" (_ at col 10)
  2416. editor.setText("2222222222x222\n\n1111111111_111111111111");
  2417. // Position cursor on _ (line 2, col 10)
  2418. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 23 }); // At end
  2419. editor.handleInput("\x01"); // Ctrl+A - go to start of line
  2420. for (let i = 0; i < 10; i++) editor.handleInput("\x1b[C"); // Move right to col 10
  2421. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 10 });
  2422. // Press Up - should move to empty line (col clamped to 0)
  2423. editor.handleInput("\x1b[A"); // Up arrow
  2424. assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 0 });
  2425. // Press Up again - should move to line 0 at col 10 (on 'x')
  2426. editor.handleInput("\x1b[A"); // Up arrow
  2427. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 10 });
  2428. });
  2429. it("preserves target column when moving down through a shorter line", () => {
  2430. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2431. editor.setText("1111111111_111\n\n2222222222x222222222222");
  2432. // Position cursor on _ (line 0, col 10)
  2433. editor.handleInput("\x1b[A"); // Up to line 1
  2434. editor.handleInput("\x1b[A"); // Up to line 0
  2435. editor.handleInput("\x01"); // Ctrl+A
  2436. for (let i = 0; i < 10; i++) editor.handleInput("\x1b[C");
  2437. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 10 });
  2438. // Press Down - should move to empty line (col clamped to 0)
  2439. editor.handleInput("\x1b[B"); // Down arrow
  2440. assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 0 });
  2441. // Press Down again - should move to line 2 at col 10 (on 'x')
  2442. editor.handleInput("\x1b[B"); // Down arrow
  2443. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 10 });
  2444. });
  2445. it("resets sticky column on horizontal movement (left arrow)", () => {
  2446. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2447. editor.setText("1234567890\n\n1234567890");
  2448. // Start at line 2, col 5
  2449. editor.handleInput("\x01"); // Ctrl+A
  2450. for (let i = 0; i < 5; i++) editor.handleInput("\x1b[C");
  2451. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 5 });
  2452. // Move up through empty line
  2453. editor.handleInput("\x1b[A"); // Up - line 1, col 0
  2454. editor.handleInput("\x1b[A"); // Up - line 0, col 5 (sticky)
  2455. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 5 });
  2456. // Move left - resets sticky column
  2457. editor.handleInput("\x1b[D"); // Left
  2458. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 4 });
  2459. // Move down twice
  2460. editor.handleInput("\x1b[B"); // Down - line 1, col 0
  2461. editor.handleInput("\x1b[B"); // Down - line 2, col 4 (new sticky from col 4)
  2462. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 4 });
  2463. });
  2464. it("resets sticky column on horizontal movement (right arrow)", () => {
  2465. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2466. editor.setText("1234567890\n\n1234567890");
  2467. // Start at line 0, col 5
  2468. editor.handleInput("\x1b[A"); // Up to line 1
  2469. editor.handleInput("\x1b[A"); // Up to line 0
  2470. editor.handleInput("\x01"); // Ctrl+A
  2471. for (let i = 0; i < 5; i++) editor.handleInput("\x1b[C");
  2472. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 5 });
  2473. // Move down through empty line
  2474. editor.handleInput("\x1b[B"); // Down - line 1, col 0
  2475. editor.handleInput("\x1b[B"); // Down - line 2, col 5 (sticky)
  2476. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 5 });
  2477. // Move right - resets sticky column
  2478. editor.handleInput("\x1b[C"); // Right
  2479. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 6 });
  2480. // Move up twice
  2481. editor.handleInput("\x1b[A"); // Up - line 1, col 0
  2482. editor.handleInput("\x1b[A"); // Up - line 0, col 6 (new sticky from col 6)
  2483. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 6 });
  2484. });
  2485. it("resets sticky column on typing", () => {
  2486. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2487. editor.setText("1234567890\n\n1234567890");
  2488. // Start at line 2, col 8
  2489. editor.handleInput("\x01"); // Ctrl+A
  2490. for (let i = 0; i < 8; i++) editor.handleInput("\x1b[C");
  2491. // Move up through empty line
  2492. editor.handleInput("\x1b[A"); // Up
  2493. editor.handleInput("\x1b[A"); // Up - line 0, col 8
  2494. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 8 });
  2495. // Type a character - resets sticky column
  2496. editor.handleInput("X");
  2497. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 9 });
  2498. // Move down twice
  2499. editor.handleInput("\x1b[B"); // Down - line 1, col 0
  2500. editor.handleInput("\x1b[B"); // Down - line 2, col 9 (new sticky from col 9)
  2501. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 9 });
  2502. });
  2503. it("resets sticky column on backspace", () => {
  2504. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2505. editor.setText("1234567890\n\n1234567890");
  2506. // Start at line 2, col 8
  2507. editor.handleInput("\x01"); // Ctrl+A
  2508. for (let i = 0; i < 8; i++) editor.handleInput("\x1b[C");
  2509. // Move up through empty line
  2510. editor.handleInput("\x1b[A"); // Up
  2511. editor.handleInput("\x1b[A"); // Up - line 0, col 8
  2512. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 8 });
  2513. // Backspace - resets sticky column
  2514. editor.handleInput("\x7f"); // Backspace
  2515. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 7 });
  2516. // Move down twice
  2517. editor.handleInput("\x1b[B"); // Down - line 1, col 0
  2518. editor.handleInput("\x1b[B"); // Down - line 2, col 7 (new sticky from col 7)
  2519. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 7 });
  2520. });
  2521. it("resets sticky column on Ctrl+A (move to line start)", () => {
  2522. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2523. editor.setText("1234567890\n\n1234567890");
  2524. // Start at line 2, col 8
  2525. editor.handleInput("\x01"); // Ctrl+A
  2526. for (let i = 0; i < 8; i++) editor.handleInput("\x1b[C");
  2527. // Move up - establishes sticky col 8
  2528. editor.handleInput("\x1b[A"); // Up - line 1, col 0
  2529. // Ctrl+A - resets sticky column to 0
  2530. editor.handleInput("\x01"); // Ctrl+A
  2531. assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 0 });
  2532. // Move up
  2533. editor.handleInput("\x1b[A"); // Up - line 0, col 0 (new sticky from col 0)
  2534. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
  2535. });
  2536. it("resets sticky column on Ctrl+E (move to line end)", () => {
  2537. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2538. editor.setText("12345\n\n1234567890");
  2539. // Start at line 2, col 3
  2540. editor.handleInput("\x01"); // Ctrl+A
  2541. for (let i = 0; i < 3; i++) editor.handleInput("\x1b[C");
  2542. // Move up through empty line - establishes sticky col 3
  2543. editor.handleInput("\x1b[A"); // Up - line 1, col 0
  2544. editor.handleInput("\x1b[A"); // Up - line 0, col 3
  2545. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 3 });
  2546. // Ctrl+E - resets sticky column to end
  2547. editor.handleInput("\x05"); // Ctrl+E
  2548. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 5 });
  2549. // Move down twice
  2550. editor.handleInput("\x1b[B"); // Down - line 1, col 0
  2551. editor.handleInput("\x1b[B"); // Down - line 2, col 5 (new sticky from col 5)
  2552. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 5 });
  2553. });
  2554. it("resets sticky column on word movement (Ctrl+Left)", () => {
  2555. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2556. editor.setText("hello world\n\nhello world");
  2557. // Start at end of line 2 (col 11)
  2558. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 11 });
  2559. // Move up through empty line - establishes sticky col 11
  2560. editor.handleInput("\x1b[A"); // Up - line 1, col 0
  2561. editor.handleInput("\x1b[A"); // Up - line 0, col 11
  2562. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 11 });
  2563. // Ctrl+Left - word movement resets sticky column
  2564. editor.handleInput("\x1b[1;5D"); // Ctrl+Left
  2565. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 6 }); // Before "world"
  2566. // Move down twice
  2567. editor.handleInput("\x1b[B"); // Down - line 1, col 0
  2568. editor.handleInput("\x1b[B"); // Down - line 2, col 6 (new sticky from col 6)
  2569. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 6 });
  2570. });
  2571. it("resets sticky column on word movement (Ctrl+Right)", () => {
  2572. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2573. editor.setText("hello world\n\nhello world");
  2574. // Start at line 0, col 0
  2575. editor.handleInput("\x1b[A"); // Up
  2576. editor.handleInput("\x1b[A"); // Up
  2577. editor.handleInput("\x01"); // Ctrl+A
  2578. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
  2579. // Move down through empty line - establishes sticky col 0
  2580. editor.handleInput("\x1b[B"); // Down - line 1, col 0
  2581. editor.handleInput("\x1b[B"); // Down - line 2, col 0
  2582. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 0 });
  2583. // Ctrl+Right - word movement resets sticky column
  2584. editor.handleInput("\x1b[1;5C"); // Ctrl+Right
  2585. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 5 }); // After "hello"
  2586. // Move up twice
  2587. editor.handleInput("\x1b[A"); // Up - line 1, col 0
  2588. editor.handleInput("\x1b[A"); // Up - line 0, col 5 (new sticky from col 5)
  2589. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 5 });
  2590. });
  2591. it("resets sticky column on undo", () => {
  2592. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2593. editor.setText("1234567890\n\n1234567890");
  2594. // Go to line 0, col 8
  2595. editor.handleInput("\x1b[A"); // Up to line 1
  2596. editor.handleInput("\x1b[A"); // Up to line 0
  2597. editor.handleInput("\x01"); // Ctrl+A
  2598. for (let i = 0; i < 8; i++) editor.handleInput("\x1b[C");
  2599. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 8 });
  2600. // Move down through empty line - establishes sticky col 8
  2601. editor.handleInput("\x1b[B"); // Down - line 1, col 0
  2602. editor.handleInput("\x1b[B"); // Down - line 2, col 8 (sticky)
  2603. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 8 });
  2604. // Type something to create undo state - this clears sticky and sets col to 9
  2605. editor.handleInput("X");
  2606. assert.strictEqual(editor.getText(), "1234567890\n\n12345678X90");
  2607. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 9 });
  2608. // Move up - establishes new sticky col 9
  2609. editor.handleInput("\x1b[A"); // Up - line 1, col 0
  2610. editor.handleInput("\x1b[A"); // Up - line 0, col 9
  2611. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 9 });
  2612. // Undo - resets sticky column and restores cursor to line 2, col 8
  2613. editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
  2614. assert.strictEqual(editor.getText(), "1234567890\n\n1234567890");
  2615. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 8 });
  2616. // Move up - should capture new sticky from restored col 8, not old col 9
  2617. editor.handleInput("\x1b[A"); // Up - line 1, col 0
  2618. editor.handleInput("\x1b[A"); // Up - line 0, col 8 (new sticky from restored position)
  2619. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 8 });
  2620. });
  2621. it("handles multiple consecutive up/down movements", () => {
  2622. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2623. editor.setText("1234567890\nab\ncd\nef\n1234567890");
  2624. // Start at line 4, col 7
  2625. editor.handleInput("\x01"); // Ctrl+A
  2626. for (let i = 0; i < 7; i++) editor.handleInput("\x1b[C");
  2627. assert.deepStrictEqual(editor.getCursor(), { line: 4, col: 7 });
  2628. // Move up multiple times through short lines
  2629. editor.handleInput("\x1b[A"); // Up - line 3, col 2 (clamped)
  2630. editor.handleInput("\x1b[A"); // Up - line 2, col 2 (clamped)
  2631. editor.handleInput("\x1b[A"); // Up - line 1, col 2 (clamped)
  2632. editor.handleInput("\x1b[A"); // Up - line 0, col 7 (restored)
  2633. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 7 });
  2634. // Move down multiple times - sticky should still be 7
  2635. editor.handleInput("\x1b[B"); // Down - line 1, col 2
  2636. editor.handleInput("\x1b[B"); // Down - line 2, col 2
  2637. editor.handleInput("\x1b[B"); // Down - line 3, col 2
  2638. editor.handleInput("\x1b[B"); // Down - line 4, col 7 (restored)
  2639. assert.deepStrictEqual(editor.getCursor(), { line: 4, col: 7 });
  2640. });
  2641. it("moves correctly through wrapped visual lines without getting stuck", () => {
  2642. const tui = createTestTUI(15, 24); // Narrow terminal
  2643. const editor = new Editor(tui, defaultEditorTheme);
  2644. // Line 0: short
  2645. // Line 1: 30 chars = wraps to 3 visual lines at width 10 (after padding)
  2646. editor.setText("short\n123456789012345678901234567890");
  2647. editor.render(15); // This gives 14 layout width
  2648. // Position at end of line 1 (col 30)
  2649. assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 30 });
  2650. // Move up repeatedly - should traverse all visual lines of the wrapped text
  2651. // and eventually reach line 0
  2652. editor.handleInput("\x1b[A"); // Up - to previous visual line within line 1
  2653. assert.strictEqual(editor.getCursor().line, 1);
  2654. editor.handleInput("\x1b[A"); // Up - another visual line
  2655. assert.strictEqual(editor.getCursor().line, 1);
  2656. editor.handleInput("\x1b[A"); // Up - should reach line 0
  2657. assert.strictEqual(editor.getCursor().line, 0);
  2658. });
  2659. it("handles setText resetting sticky column", () => {
  2660. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2661. editor.setText("1234567890\n\n1234567890");
  2662. // Establish sticky column
  2663. editor.handleInput("\x01"); // Ctrl+A
  2664. for (let i = 0; i < 8; i++) editor.handleInput("\x1b[C");
  2665. editor.handleInput("\x1b[A"); // Up
  2666. // setText should reset sticky column
  2667. editor.setText("abcdefghij\n\nabcdefghij");
  2668. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 10 }); // At end
  2669. // Move up - should capture new sticky from current position (10)
  2670. editor.handleInput("\x1b[A"); // Up - line 1, col 0
  2671. editor.handleInput("\x1b[A"); // Up - line 0, col 10
  2672. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 10 });
  2673. });
  2674. it("sets preferredVisualCol when pressing right at end of prompt (last line)", () => {
  2675. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2676. // Line 0: 20 chars with 'x' at col 10
  2677. // Line 1: empty
  2678. // Line 2: 10 chars ending with '_'
  2679. editor.setText("111111111x1111111111\n\n333333333_");
  2680. // Go to line 0, press Ctrl+E (end of line) - col 20
  2681. editor.handleInput("\x1b[A"); // Up to line 1
  2682. editor.handleInput("\x1b[A"); // Up to line 0
  2683. editor.handleInput("\x05"); // Ctrl+E - move to end of line
  2684. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 20 });
  2685. // Move down to line 2 - cursor clamped to col 10 (end of line)
  2686. editor.handleInput("\x1b[B"); // Down to line 1, col 0
  2687. editor.handleInput("\x1b[B"); // Down to line 2, col 10 (clamped)
  2688. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 10 });
  2689. // Press Right at end of prompt - nothing visible happens, but sets preferredVisualCol to 10
  2690. editor.handleInput("\x1b[C"); // Right - can't move, but sets preferredVisualCol
  2691. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 10 }); // Still at same position
  2692. // Move up twice to line 0 - should use preferredVisualCol (10) to land on 'x'
  2693. editor.handleInput("\x1b[A"); // Up to line 1, col 0
  2694. editor.handleInput("\x1b[A"); // Up to line 0, col 10 (on 'x')
  2695. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 10 });
  2696. });
  2697. it("handles editor resizes when preferredVisualCol is on the same line", () => {
  2698. // Create editor with wider terminal
  2699. const tui = createTestTUI(80, 24);
  2700. const editor = new Editor(tui, defaultEditorTheme);
  2701. editor.setText("12345678901234567890\n\n12345678901234567890");
  2702. // Start at line 2, col 15
  2703. editor.handleInput("\x01"); // Ctrl+A
  2704. for (let i = 0; i < 15; i++) editor.handleInput("\x1b[C");
  2705. // Move up through empty line - establishes sticky col 15
  2706. editor.handleInput("\x1b[A"); // Up
  2707. editor.handleInput("\x1b[A"); // Up - line 0, col 15
  2708. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 15 });
  2709. // Render with narrower width to simulate resize
  2710. editor.render(12); // Width 12
  2711. // Move down - sticky should be clamped to new width
  2712. editor.handleInput("\x1b[B"); // Down - line 1
  2713. editor.handleInput("\x1b[B"); // Down - line 2, col should be clamped
  2714. assert.equal(editor.getCursor().col, 4);
  2715. });
  2716. it("handles editor resizes when preferredVisualCol is on a different line", () => {
  2717. const tui = createTestTUI(80, 24);
  2718. const editor = new Editor(tui, defaultEditorTheme);
  2719. // Create a line that wraps into multiple visual lines at width 10
  2720. // "12345678901234567890" = 20 chars, wraps to 2 visual lines at width 10
  2721. editor.setText("short\n12345678901234567890");
  2722. // Go to line 1, col 15
  2723. editor.handleInput("\x01"); // Ctrl+A
  2724. for (let i = 0; i < 15; i++) editor.handleInput("\x1b[C");
  2725. assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 15 });
  2726. // Move up to establish sticky col 15
  2727. editor.handleInput("\x1b[A"); // Up to line 0
  2728. // Line 0 has only 5 chars, so cursor at col 5
  2729. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 5 });
  2730. // Narrow the editor
  2731. editor.render(10);
  2732. // Move down - preferredVisualCol was 15, but width is 10
  2733. // Should land on line 1, clamped to width (visual col 9, which is logical col 9)
  2734. editor.handleInput("\x1b[B"); // Down to line 1
  2735. assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 8 });
  2736. // Move up
  2737. editor.handleInput("\x1b[A"); // Up - should go to line 0
  2738. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 5 }); // Line 0 only has 5 chars
  2739. // Restore the original width
  2740. editor.render(80);
  2741. // Move down - preferredVisualCol was kept at 15
  2742. editor.handleInput("\x1b[B"); // Down to line 1
  2743. assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 15 });
  2744. });
  2745. it("rewrapped lines: target fits current visual column", () => {
  2746. const tui = createTestTUI(80, 24);
  2747. const editor = new Editor(tui, defaultEditorTheme);
  2748. editor.setText("abcdefghijklmnopqr\n123456789012345678");
  2749. positionCursor(editor, 0, 18);
  2750. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 18 });
  2751. // Narrow to width 10 (layoutWidth = 9).
  2752. // Line 0 last segment has visual col max 9, line 1 first segment max 8
  2753. editor.render(10);
  2754. // Move down: cursor clamps to 8
  2755. editor.handleInput("\x1b[B");
  2756. assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 8 });
  2757. // Widen back. Move up, the current visual col wins
  2758. editor.render(80);
  2759. editor.handleInput("\x1b[A");
  2760. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 8 });
  2761. // Preferred was cleared by the rewrapped branch
  2762. editor.handleInput("\x1b[B");
  2763. assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 8 });
  2764. });
  2765. it("rewrapped lines: target shorter than current visual column", () => {
  2766. const tui = createTestTUI(80, 24);
  2767. const editor = new Editor(tui, defaultEditorTheme);
  2768. editor.setText("abcdefghijklmnopqr\n123456789012345678\nab");
  2769. positionCursor(editor, 0, 18);
  2770. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 18 });
  2771. // Narrow to width 10 (layoutWidth = 9). Moving down clamps to col 8
  2772. editor.render(10);
  2773. editor.handleInput("\x1b[B");
  2774. assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 8 });
  2775. // Widen the editor
  2776. editor.render(80);
  2777. // Move down to short line "ab".
  2778. // preferredVisualCol is replaced with current visual col (8), cursor clamps to 2
  2779. editor.handleInput("\x1b[B");
  2780. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 2 });
  2781. // Moving up restores to preferred col 8
  2782. editor.handleInput("\x1b[A");
  2783. assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 8 });
  2784. });
  2785. });
  2786. describe("Paste marker atomic behavior", () => {
  2787. /** Helper: simulate a large paste that creates a marker */
  2788. function pasteWithMarker(editor: Editor): string {
  2789. const bigContent = "line\n".repeat(20).trimEnd(); // 20 lines
  2790. editor.handleInput(`\x1b[200~${bigContent}\x1b[201~`);
  2791. // The editor replaces large pastes with a marker like "[paste #1 +20 lines]"
  2792. return editor.getText();
  2793. }
  2794. it("creates a paste marker for large pastes", () => {
  2795. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2796. const text = pasteWithMarker(editor);
  2797. assert.match(text, /\[paste #\d+ \+\d+ lines\]/);
  2798. });
  2799. it("treats paste marker as single unit for right arrow", () => {
  2800. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2801. editor.handleInput("A");
  2802. pasteWithMarker(editor);
  2803. editor.handleInput("B");
  2804. // Text: "A[paste #1 +20 lines]B", cursor at end
  2805. // Go to start
  2806. editor.handleInput("\x01"); // Ctrl+A
  2807. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
  2808. // Right arrow: should move past "A"
  2809. editor.handleInput("\x1b[C");
  2810. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 1 });
  2811. // Right arrow: should skip the entire marker
  2812. editor.handleInput("\x1b[C");
  2813. const marker = editor.getText().match(/\[paste #\d+ \+\d+ lines\]/)![0];
  2814. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 1 + marker.length });
  2815. // Right arrow: should move past "B"
  2816. editor.handleInput("\x1b[C");
  2817. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 1 + marker.length + 1 });
  2818. });
  2819. it("treats paste marker as single unit for left arrow", () => {
  2820. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2821. editor.handleInput("A");
  2822. pasteWithMarker(editor);
  2823. editor.handleInput("B");
  2824. // Cursor at end
  2825. // Left arrow: past "B"
  2826. editor.handleInput("\x1b[D");
  2827. const text = editor.getText();
  2828. const marker = text.match(/\[paste #\d+ \+\d+ lines\]/)![0];
  2829. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 1 + marker.length });
  2830. // Left arrow: skip the entire marker
  2831. editor.handleInput("\x1b[D");
  2832. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 1 });
  2833. // Left arrow: past "A"
  2834. editor.handleInput("\x1b[D");
  2835. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
  2836. });
  2837. it("treats paste marker as single unit for backspace", () => {
  2838. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2839. editor.handleInput("A");
  2840. pasteWithMarker(editor);
  2841. editor.handleInput("B");
  2842. const text = editor.getText();
  2843. const marker = text.match(/\[paste #\d+ \+\d+ lines\]/)![0];
  2844. // Position cursor right after the marker (before "B")
  2845. editor.handleInput("\x01"); // Ctrl+A
  2846. // Move past "A" and the marker
  2847. editor.handleInput("\x1b[C"); // past "A"
  2848. editor.handleInput("\x1b[C"); // past marker
  2849. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 1 + marker.length });
  2850. // Backspace: should delete the entire marker at once
  2851. editor.handleInput("\x7f");
  2852. assert.strictEqual(editor.getText(), "AB");
  2853. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 1 });
  2854. });
  2855. it("treats paste marker as single unit for forward delete", () => {
  2856. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2857. editor.handleInput("A");
  2858. pasteWithMarker(editor);
  2859. editor.handleInput("B");
  2860. // Position cursor on "A" (col 0) then move right once to be just before marker
  2861. editor.handleInput("\x01"); // Ctrl+A
  2862. editor.handleInput("\x1b[C"); // past "A", now at col 1 (start of marker)
  2863. // Forward delete: should delete the entire marker at once
  2864. editor.handleInput("\x1b[3~"); // Delete key
  2865. assert.strictEqual(editor.getText(), "AB");
  2866. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 1 });
  2867. });
  2868. it("treats paste marker as single unit for word movement", () => {
  2869. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2870. editor.handleInput("X");
  2871. editor.handleInput(" ");
  2872. pasteWithMarker(editor);
  2873. editor.handleInput(" ");
  2874. editor.handleInput("Y");
  2875. // Text: "X [paste #1 +20 lines] Y"
  2876. const text = editor.getText();
  2877. const marker = text.match(/\[paste #\d+ \+\d+ lines\]/)![0];
  2878. // Go to start
  2879. editor.handleInput("\x01"); // Ctrl+A
  2880. // Ctrl+Right: skip "X"
  2881. editor.handleInput("\x1b[1;5C");
  2882. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 1 });
  2883. // Ctrl+Right: skip whitespace + marker (marker treated as single non-ws, non-punct unit)
  2884. editor.handleInput("\x1b[1;5C");
  2885. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 2 + marker.length });
  2886. });
  2887. it("undo restores marker after backspace deletion", () => {
  2888. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2889. editor.handleInput("A");
  2890. pasteWithMarker(editor);
  2891. editor.handleInput("B");
  2892. const textBefore = editor.getText();
  2893. // Position after marker
  2894. editor.handleInput("\x01");
  2895. editor.handleInput("\x1b[C"); // past A
  2896. editor.handleInput("\x1b[C"); // past marker
  2897. // Delete marker
  2898. editor.handleInput("\x7f");
  2899. assert.strictEqual(editor.getText(), "AB");
  2900. // Undo
  2901. editor.handleInput("\x1b[45;5u");
  2902. assert.strictEqual(editor.getText(), textBefore);
  2903. });
  2904. it("handles multiple paste markers in same line", () => {
  2905. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2906. pasteWithMarker(editor);
  2907. editor.handleInput(" ");
  2908. pasteWithMarker(editor);
  2909. const text = editor.getText();
  2910. const markers = [...text.matchAll(/\[paste #\d+ \+\d+ lines\]/g)];
  2911. assert.strictEqual(markers.length, 2);
  2912. // Go to start
  2913. editor.handleInput("\x01");
  2914. // Right arrow: should skip first marker atomically
  2915. editor.handleInput("\x1b[C");
  2916. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: markers[0]![0].length });
  2917. // Right arrow: past space
  2918. editor.handleInput("\x1b[C");
  2919. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: markers[0]![0].length + 1 });
  2920. // Right arrow: should skip second marker atomically
  2921. editor.handleInput("\x1b[C");
  2922. assert.deepStrictEqual(editor.getCursor(), {
  2923. line: 0,
  2924. col: markers[0]![0].length + 1 + markers[1]![0].length,
  2925. });
  2926. });
  2927. it("does not treat manually typed marker-like text as atomic (no valid paste ID)", () => {
  2928. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  2929. // Type text that matches the pattern but was typed manually (no paste entry)
  2930. const fakeMarker = "[paste #99 +5 lines]";
  2931. for (const ch of fakeMarker) editor.handleInput(ch);
  2932. assert.strictEqual(editor.getText(), fakeMarker);
  2933. // No paste with ID 99 exists, so the marker is NOT treated atomically.
  2934. // Right arrow should move one grapheme at a time.
  2935. editor.handleInput("\x01"); // Ctrl+A
  2936. editor.handleInput("\x1b[C"); // Right
  2937. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 1 }); // Just past "["
  2938. });
  2939. it("does not crash when paste marker is wider than terminal width", () => {
  2940. // Reproduce: terminal width 8, paste marker "[paste #1 +47 lines]" (21 chars)
  2941. const tui = createTestTUI();
  2942. const editor = new Editor(tui, defaultEditorTheme);
  2943. const bigContent = "line\n".repeat(47).trimEnd();
  2944. editor.handleInput(`\x1b[200~${bigContent}\x1b[201~`);
  2945. const text = editor.getText();
  2946. const marker = text.match(/\[paste #\d+ \+\d+ lines\]/);
  2947. assert.ok(marker, "paste marker should be created");
  2948. assert.ok(visibleWidth(marker[0]) > 8, "marker should be wider than render width");
  2949. // Render at very narrow width - should not throw
  2950. const lines = editor.render(8);
  2951. // Every rendered line must fit within the width (marker is split)
  2952. for (const line of lines) {
  2953. assert.ok(
  2954. visibleWidth(line) <= 8,
  2955. `line exceeds width 8: visible=${visibleWidth(line)} text=${JSON.stringify(line)}`,
  2956. );
  2957. }
  2958. });
  2959. it("does not crash when text + paste marker exceeds terminal width with cursor on marker", () => {
  2960. // Reproduce: terminal width 54, text "b".repeat(35) + "[paste #1 +27 lines]" + "bbbb"
  2961. // Cursor lands on the paste marker after word-wrap, causing the rendered line
  2962. // to be 55 visible chars (1 over the width).
  2963. const tui = createTestTUI();
  2964. const editor = new Editor(tui, defaultEditorTheme);
  2965. // Type 35 'b' characters
  2966. for (let i = 0; i < 35; i++) editor.handleInput("b");
  2967. // Paste 27 lines
  2968. const bigContent = "line\n".repeat(27).trimEnd();
  2969. editor.handleInput(`\x1b[200~${bigContent}\x1b[201~`);
  2970. // Type a few more characters
  2971. for (let i = 0; i < 4; i++) editor.handleInput("b");
  2972. // Move cursor left to land on the paste marker
  2973. editor.handleInput("\x1b[D"); // past last 'b'
  2974. editor.handleInput("\x1b[D"); // past last 'b'
  2975. editor.handleInput("\x1b[D"); // past last 'b'
  2976. editor.handleInput("\x1b[D"); // past last 'b'
  2977. editor.handleInput("\x1b[D"); // now on the paste marker
  2978. // Render at width 54 - should not throw
  2979. const renderWidth = 54;
  2980. const lines = editor.render(renderWidth);
  2981. for (const line of lines) {
  2982. assert.ok(
  2983. visibleWidth(line) <= renderWidth,
  2984. `line exceeds width ${renderWidth}: visible=${visibleWidth(line)} text=${JSON.stringify(line)}`,
  2985. );
  2986. }
  2987. });
  2988. it("wordWrapLine re-checks overflow after backtracking to wrap opportunity", () => {
  2989. // Reproduce crash #2: " " + "b".repeat(35) + atomic_marker(20 chars) + "bbbb"
  2990. // layoutWidth=53. After wrapping at the space, the remaining 35 b's + marker = 55
  2991. // must trigger a second force-break instead of silently overflowing.
  2992. const tui = createTestTUI();
  2993. const editor = new Editor(tui, defaultEditorTheme);
  2994. // Type a space, then 35 b's
  2995. editor.handleInput(" ");
  2996. for (let i = 0; i < 35; i++) editor.handleInput("b");
  2997. // Paste 27 lines to create marker
  2998. const bigContent = "line\n".repeat(27).trimEnd();
  2999. editor.handleInput(`\x1b[200~${bigContent}\x1b[201~`);
  3000. // Type trailing chars
  3001. for (let i = 0; i < 4; i++) editor.handleInput("b");
  3002. // Render at width 54 (contentWidth=54, layoutWidth=53 with paddingX=0)
  3003. const renderWidth = 54;
  3004. const lines = editor.render(renderWidth);
  3005. for (const line of lines) {
  3006. assert.ok(
  3007. visibleWidth(line) <= renderWidth,
  3008. `line exceeds width ${renderWidth}: visible=${visibleWidth(line)} text=${JSON.stringify(line)}`,
  3009. );
  3010. }
  3011. });
  3012. it("expands large pasted content literally in getExpandedText", () => {
  3013. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  3014. const pastedText = [
  3015. "line 1",
  3016. "line 2",
  3017. "line 3",
  3018. "line 4",
  3019. "line 5",
  3020. "line 6",
  3021. "line 7",
  3022. "line 8",
  3023. "line 9",
  3024. "line 10",
  3025. "tokens $1 $2 $& $$ $` $' end",
  3026. ].join("\n");
  3027. editor.handleInput(`\x1b[200~${pastedText}\x1b[201~`);
  3028. assert.match(editor.getText(), /\[paste #\d+ \+\d+ lines\]/);
  3029. assert.strictEqual(editor.getExpandedText(), pastedText);
  3030. });
  3031. it("snaps to the paste marker start when navigating down into it", () => {
  3032. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  3033. // Line 0: long enough text to establish a sticky column
  3034. editor.setText("12345678901234567890\n\nhello ");
  3035. // Create a large paste to get a marker
  3036. const bigContent = "x".repeat(2000);
  3037. editor.handleInput(`\x1b[200~${bigContent}\x1b[201~`);
  3038. editor.render(80);
  3039. const text = editor.getText();
  3040. const _marker = text.match(/\[paste #\d+ \d+ chars\]/)![0];
  3041. // Line 0: "12345678901234567890"
  3042. // Line 1: "" (empty)
  3043. // Line 2: "hello [paste #1 2000 chars]"
  3044. // marker starts at col 6
  3045. // Navigate to line 0, col 10
  3046. editor.handleInput("\x1b[A"); // Up to line 1
  3047. editor.handleInput("\x1b[A"); // Up to line 0
  3048. editor.handleInput("\x01"); // Ctrl+A (start of line)
  3049. for (let i = 0; i < 10; i++) editor.handleInput("\x1b[C"); // Right 10
  3050. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 10 });
  3051. // Down to empty line
  3052. editor.handleInput("\x1b[B");
  3053. assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 0 });
  3054. // Down to paste marker line - sticky col 10 falls inside marker (starts at col 6).
  3055. // Cursor should snap to start of marker (col 6), not end (col 6 + marker.length).
  3056. editor.handleInput("\x1b[B");
  3057. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 6 });
  3058. });
  3059. it("preserves sticky column when navigating through paste marker line", () => {
  3060. const tui = createTestTUI(30, 24);
  3061. const editor = new Editor(tui, defaultEditorTheme);
  3062. // Build:
  3063. // Line 0: "1234567890123456" (16 chars)
  3064. // Line 1: "" (empty)
  3065. // Line 2: "[paste #1 2000 chars]" (22 chars, paste marker)
  3066. // Line 3: "" (empty)
  3067. // Line 4: "abcdefghijklmnop" (16 chars)
  3068. for (const ch of "1234567890123456") editor.handleInput(ch);
  3069. editor.handleInput("\n");
  3070. editor.handleInput("\n");
  3071. editor.handleInput(`\x1b[200~${"x".repeat(2000)}\x1b[201~`);
  3072. editor.handleInput("\n");
  3073. editor.handleInput("\n");
  3074. for (const ch of "abcdefghijklmnop") editor.handleInput(ch);
  3075. editor.render(30);
  3076. // Navigate to line 0, col 10
  3077. for (let i = 0; i < 4; i++) editor.handleInput("\x1b[A"); // Up to line 0
  3078. editor.handleInput("\x01"); // Ctrl+A
  3079. for (let i = 0; i < 10; i++) editor.handleInput("\x1b[C");
  3080. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 10 });
  3081. // Down to empty line - sticky col 10 established
  3082. editor.handleInput("\x1b[B");
  3083. assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 0 });
  3084. // Down to paste marker - cursor snapped to col 0 (start of marker)
  3085. editor.handleInput("\x1b[B");
  3086. assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 0 });
  3087. // Down to empty line
  3088. editor.handleInput("\x1b[B");
  3089. assert.deepStrictEqual(editor.getCursor(), { line: 3, col: 0 });
  3090. // Down to last line - should restore sticky col 10
  3091. editor.handleInput("\x1b[B");
  3092. assert.deepStrictEqual(editor.getCursor(), { line: 4, col: 10 });
  3093. });
  3094. it("does not get stuck moving down from a multi-visual-line paste marker", () => {
  3095. const tui = createTestTUI(20, 24);
  3096. const editor = new Editor(tui, defaultEditorTheme);
  3097. // Build:
  3098. // Logical line 0: "abcdefgh" + marker(21 chars) + "ijklmnopqr"
  3099. // Logical line 1: "123456789012345678"
  3100. //
  3101. // Marker "[paste #1 +100 lines]" (21 chars) is wider than the
  3102. // terminal (20). Word-wrap splits at the space before "lines",
  3103. // producing:
  3104. // VL1: abcdefgh (startCol 0, len 8)
  3105. // VL2: [paste #1 +100 (startCol 8, len 15) <- marker head
  3106. // VL3: lines]ijklmnopqr (startCol 23, len 16) <- marker tail + content
  3107. // VL4: 123456789012345678 (line 1)
  3108. //
  3109. // On VL3 the marker tail "lines]" occupies visual cols 0-5.
  3110. // Content ("i") starts at visual col 6 = logical col 29.
  3111. for (const ch of "abcdefgh") editor.handleInput(ch);
  3112. const bigContent = "line\n".repeat(100).trimEnd();
  3113. editor.handleInput(`\x1b[200~${bigContent}\x1b[201~`);
  3114. for (const ch of "ijklmnopqr") editor.handleInput(ch);
  3115. editor.handleInput("\n");
  3116. for (const ch of "123456789012345678") editor.handleInput(ch);
  3117. editor.render(20);
  3118. const text = editor.getText();
  3119. const markerMatch = text.match(/\[paste #\d+ \+\d+ lines]/);
  3120. assert.ok(markerMatch, "paste marker should be created");
  3121. const markerLen = markerMatch[0].length; // 21
  3122. assert.ok(markerLen > 20, "marker should be wider than terminal");
  3123. const markerStart = 8;
  3124. const markerEnd = markerStart + markerLen; // 29
  3125. // Navigate to line 0, col 6 (on "g"). Preferred col 6 is past the
  3126. // marker tail on VL3, so the cursor should land on content ("i" at
  3127. // col 29) without snapping back.
  3128. editor.handleInput("\x1b[A"); // Up to line 0
  3129. editor.handleInput("\x01"); // Ctrl+A (start of line)
  3130. for (let i = 0; i < 6; i++) editor.handleInput("\x1b[C"); // Right to col 6
  3131. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 6 });
  3132. // Down: cursor lands on paste marker start
  3133. editor.handleInput("\x1b[B");
  3134. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: markerStart });
  3135. // Down again: preferred col 6 lands at VL3 col 29 ("i"), which is
  3136. // past the marker. Cursor stays on line 0.
  3137. editor.handleInput("\x1b[B");
  3138. assert.strictEqual(editor.getCursor().line, 0);
  3139. assert.strictEqual(editor.getCursor().col, markerEnd); // col 29 = "i"
  3140. // Up: back to paste marker
  3141. editor.handleInput("\x1b[A");
  3142. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: markerStart });
  3143. // Up again: back to col 6 ("g")
  3144. editor.handleInput("\x1b[A");
  3145. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 6 });
  3146. });
  3147. it("skips marker continuation VLs when preferred col falls in marker tail", () => {
  3148. const tui = createTestTUI(20, 24);
  3149. const editor = new Editor(tui, defaultEditorTheme);
  3150. // Same layout. Start at col 3 ("d"). Preferred col 3 maps to VL3
  3151. // visual col 3 which is inside the "lines]" marker tail.
  3152. // moveToVisualLine detects the continuation VL and skips to VL4
  3153. // (line 1).
  3154. // VL1: abcdefgh (startCol 0, len 8)
  3155. // VL2: [paste #1 +100 (startCol 8, len 15) <- marker head
  3156. // VL3: lines]ijklmnopqr (startCol 23, len 16) <- marker tail + content
  3157. // VL4: 123456789012345678 (line 1)
  3158. for (const ch of "abcdefgh") editor.handleInput(ch);
  3159. const bigContent = "line\n".repeat(100).trimEnd();
  3160. editor.handleInput(`\x1b[200~${bigContent}\x1b[201~`);
  3161. for (const ch of "ijklmnopqr") editor.handleInput(ch);
  3162. editor.handleInput("\n");
  3163. for (const ch of "123456789012345678") editor.handleInput(ch);
  3164. editor.render(20);
  3165. // Navigate to line 0, col 3 (on "d")
  3166. editor.handleInput("\x1b[A"); // Up to line 0
  3167. editor.handleInput("\x01"); // Ctrl+A
  3168. for (let i = 0; i < 3; i++) editor.handleInput("\x1b[C");
  3169. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 3 });
  3170. // Down: marker
  3171. editor.handleInput("\x1b[B");
  3172. assert.strictEqual(editor.getCursor().col, 8);
  3173. // Down: skips VL3 (col 3 in marker tail) and lands on line 1
  3174. editor.handleInput("\x1b[B");
  3175. assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 3 });
  3176. // Round-trip back
  3177. editor.handleInput("\x1b[A");
  3178. assert.strictEqual(editor.getCursor().col, 8); // marker
  3179. editor.handleInput("\x1b[A");
  3180. assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 3 });
  3181. });
  3182. it("submits large pasted content literally", () => {
  3183. const editor = new Editor(createTestTUI(), defaultEditorTheme);
  3184. const pastedText = [
  3185. "line 1",
  3186. "line 2",
  3187. "line 3",
  3188. "line 4",
  3189. "line 5",
  3190. "line 6",
  3191. "line 7",
  3192. "line 8",
  3193. "line 9",
  3194. "line 10",
  3195. "tokens $1 $2 $& $$ $` $' end",
  3196. ].join("\n");
  3197. let submitted = "";
  3198. editor.onSubmit = (text) => {
  3199. submitted = text;
  3200. };
  3201. editor.handleInput(`\x1b[200~${pastedText}\x1b[201~`);
  3202. editor.handleInput("\r");
  3203. assert.strictEqual(submitted, pastedText);
  3204. });
  3205. });
  3206. });