vim.js 245 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743
  1. /* eslint-disable */
  2. // @ts-nocheck
  3. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  4. // Distributed under an MIT license: https://codemirror.net/5/LICENSE
  5. /**
  6. * Supported keybindings:
  7. * Too many to list. Refer to defaultKeymap below.
  8. *
  9. * Supported Ex commands:
  10. * Refer to defaultExCommandMap below.
  11. *
  12. * Registers: unnamed, -, ., :, /, _, a-z, A-Z, 0-9
  13. * (Does not respect the special case for number registers when delete
  14. * operator is made with these commands: %, (, ), , /, ?, n, N, {, } )
  15. * TODO: Implement the remaining registers.
  16. *
  17. * Marks: a-z, A-Z, and 0-9
  18. * TODO: Implement the remaining special marks. They have more complex
  19. * behavior.
  20. *
  21. * Events:
  22. * 'vim-mode-change' - raised on the editor anytime the current mode changes,
  23. * Event object: {mode: "visual", subMode: "linewise"}
  24. *
  25. * Code structure:
  26. * 1. Default keymap
  27. * 2. Variable declarations and short basic helpers
  28. * 3. Instance (External API) implementation
  29. * 4. Internal state tracking objects (input state, counter) implementation
  30. * and instantiation
  31. * 5. Key handler (the main command dispatcher) implementation
  32. * 6. Motion, operator, and action implementations
  33. * 7. Helper functions for the key handler, motions, operators, and actions
  34. * 8. Set up Vim to work as a keymap for CodeMirror.
  35. * 9. Ex command implementations.
  36. */
  37. /**
  38. * @typedef { import("./cm_adapter").CodeMirror } CodeMirror
  39. * @typedef { import("./types").CodeMirrorV} CodeMirrorV
  40. * @typedef { import("./types").Pos } Pos
  41. * @typedef { import("./types").CM5Range } CM5Range
  42. * @typedef { import("./types").vimState } vimState
  43. * @typedef { import("./types").ExFn } ExFn
  44. * @typedef { import("./types").MotionArgs } MotionArgs
  45. * @typedef { import("./types").ActionArgs } ActionArgs
  46. * @typedef { import("./types").OperatorArgs } OperatorArgs
  47. * @typedef { import("./types").vimKey } vimKey
  48. * @typedef { import("./types").InputStateInterface } InputStateInterface
  49. */
  50. /** @arg {typeof import("./cm_adapter").CodeMirror} CodeMirror */
  51. export function initVim(CodeMirror) {
  52. var Pos = CodeMirror.Pos;
  53. /** @arg {CodeMirror} cm @arg {Pos} curStart @arg {Pos} curEnd */
  54. function updateSelectionForSurrogateCharacters(cm, curStart, curEnd) {
  55. // start and character position when no selection
  56. // is the same in visual mode, and differs in 1 character in normal mode
  57. if (curStart.line === curEnd.line && curStart.ch >= curEnd.ch - 1) {
  58. var text = cm.getLine(curStart.line);
  59. var charCode = text.charCodeAt(curStart.ch);
  60. if (0xD800 <= charCode && charCode <= 0xD8FF) {
  61. curEnd.ch += 1;
  62. }
  63. }
  64. return {start: curStart, end: curEnd};
  65. }
  66. /** @type {import("./types").vimKeyMap} */
  67. var defaultKeymap = [
  68. // Key to key mapping. This goes first to make it possible to override
  69. // existing mappings.
  70. { keys: '<Left>', type: 'keyToKey', toKeys: 'h' },
  71. { keys: '<Right>', type: 'keyToKey', toKeys: 'l' },
  72. { keys: '<Up>', type: 'keyToKey', toKeys: 'k' },
  73. { keys: '<Down>', type: 'keyToKey', toKeys: 'j' },
  74. { keys: 'g<Up>', type: 'keyToKey', toKeys: 'gk' },
  75. { keys: 'g<Down>', type: 'keyToKey', toKeys: 'gj' },
  76. { keys: '<Space>', type: 'keyToKey', toKeys: 'l' },
  77. { keys: '<BS>', type: 'keyToKey', toKeys: 'h'},
  78. { keys: '<Del>', type: 'keyToKey', toKeys: 'x' },
  79. { keys: '<C-Space>', type: 'keyToKey', toKeys: 'W' },
  80. { keys: '<C-BS>', type: 'keyToKey', toKeys: 'B' },
  81. { keys: '<S-Space>', type: 'keyToKey', toKeys: 'w' },
  82. { keys: '<S-BS>', type: 'keyToKey', toKeys: 'b' },
  83. { keys: '<C-n>', type: 'keyToKey', toKeys: 'j' },
  84. { keys: '<C-p>', type: 'keyToKey', toKeys: 'k' },
  85. { keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>' },
  86. { keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>' },
  87. { keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
  88. { keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
  89. { keys: '<C-Esc>', type: 'keyToKey', toKeys: '<Esc>' }, // ipad keyboard sends C-Esc instead of C-[
  90. { keys: '<C-Esc>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
  91. { keys: 's', type: 'keyToKey', toKeys: 'cl', context: 'normal' },
  92. { keys: 's', type: 'keyToKey', toKeys: 'c', context: 'visual'},
  93. { keys: 'S', type: 'keyToKey', toKeys: 'cc', context: 'normal' },
  94. { keys: 'S', type: 'keyToKey', toKeys: 'VdO', context: 'visual' },
  95. { keys: '<Home>', type: 'keyToKey', toKeys: '0' },
  96. { keys: '<End>', type: 'keyToKey', toKeys: '$' },
  97. { keys: '<PageUp>', type: 'keyToKey', toKeys: '<C-b>' },
  98. { keys: '<PageDown>', type: 'keyToKey', toKeys: '<C-f>' },
  99. { keys: '<CR>', type: 'keyToKey', toKeys: 'j^', context: 'normal' },
  100. { keys: '<Ins>', type: 'keyToKey', toKeys: 'i', context: 'normal'},
  101. { keys: '<Ins>', type: 'action', action: 'toggleOverwrite', context: 'insert' },
  102. // Motions
  103. { keys: 'H', type: 'motion', motion: 'moveToTopLine', motionArgs: { linewise: true, toJumplist: true }},
  104. { keys: 'M', type: 'motion', motion: 'moveToMiddleLine', motionArgs: { linewise: true, toJumplist: true }},
  105. { keys: 'L', type: 'motion', motion: 'moveToBottomLine', motionArgs: { linewise: true, toJumplist: true }},
  106. { keys: 'h', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: false }},
  107. { keys: 'l', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: true }},
  108. { keys: 'j', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, linewise: true }},
  109. { keys: 'k', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, linewise: true }},
  110. { keys: 'gj', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: true }},
  111. { keys: 'gk', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: false }},
  112. { keys: 'w', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false }},
  113. { keys: 'W', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false, bigWord: true }},
  114. { keys: 'e', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, inclusive: true }},
  115. { keys: 'E', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, bigWord: true, inclusive: true }},
  116. { keys: 'b', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }},
  117. { keys: 'B', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false, bigWord: true }},
  118. { keys: 'ge', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, inclusive: true }},
  119. { keys: 'gE', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, bigWord: true, inclusive: true }},
  120. { keys: '{', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: false, toJumplist: true }},
  121. { keys: '}', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: true, toJumplist: true }},
  122. { keys: '(', type: 'motion', motion: 'moveBySentence', motionArgs: { forward: false }},
  123. { keys: ')', type: 'motion', motion: 'moveBySentence', motionArgs: { forward: true }},
  124. { keys: '<C-f>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: true }},
  125. { keys: '<C-b>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: false }},
  126. { keys: '<C-d>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: true, explicitRepeat: true }},
  127. { keys: '<C-u>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: false, explicitRepeat: true }},
  128. { keys: 'gg', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},
  129. { keys: 'G', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},
  130. {keys: "g$", type: "motion", motion: "moveToEndOfDisplayLine"},
  131. {keys: "g^", type: "motion", motion: "moveToStartOfDisplayLine"},
  132. {keys: "g0", type: "motion", motion: "moveToStartOfDisplayLine"},
  133. { keys: '0', type: 'motion', motion: 'moveToStartOfLine' },
  134. { keys: '^', type: 'motion', motion: 'moveToFirstNonWhiteSpaceCharacter' },
  135. { keys: '+', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true }},
  136. { keys: '-', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, toFirstChar:true }},
  137. { keys: '_', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},
  138. { keys: '$', type: 'motion', motion: 'moveToEol', motionArgs: { inclusive: true }},
  139. { keys: '%', type: 'motion', motion: 'moveToMatchedSymbol', motionArgs: { inclusive: true, toJumplist: true }},
  140. { keys: 'f<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: true , inclusive: true }},
  141. { keys: 'F<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: false }},
  142. { keys: 't<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: true, inclusive: true }},
  143. { keys: 'T<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: false }},
  144. { keys: ';', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: true }},
  145. { keys: ',', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: false }},
  146. { keys: '\'<register>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true, linewise: true}},
  147. { keys: '`<register>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true}},
  148. { keys: ']`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
  149. { keys: '[`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
  150. { keys: ']\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
  151. { keys: '[\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
  152. // the next two aren't motions but must come before more general motion declarations
  153. { keys: ']p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true, matchIndent: true}},
  154. { keys: '[p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true, matchIndent: true}},
  155. { keys: ']<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: true, toJumplist: true}},
  156. { keys: '[<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: false, toJumplist: true}},
  157. { keys: '|', type: 'motion', motion: 'moveToColumn'},
  158. { keys: 'o', type: 'motion', motion: 'moveToOtherHighlightedEnd', context:'visual'},
  159. { keys: 'O', type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: {sameLine: true}, context:'visual'},
  160. // Operators
  161. { keys: 'd', type: 'operator', operator: 'delete' },
  162. { keys: 'y', type: 'operator', operator: 'yank' },
  163. { keys: 'c', type: 'operator', operator: 'change' },
  164. { keys: '=', type: 'operator', operator: 'indentAuto' },
  165. { keys: '>', type: 'operator', operator: 'indent', operatorArgs: { indentRight: true }},
  166. { keys: '<', type: 'operator', operator: 'indent', operatorArgs: { indentRight: false }},
  167. { keys: 'g~', type: 'operator', operator: 'changeCase' },
  168. { keys: 'gu', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, isEdit: true },
  169. { keys: 'gU', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, isEdit: true },
  170. { keys: 'n', type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: true }},
  171. { keys: 'N', type: 'motion', motion: 'findNext', motionArgs: { forward: false, toJumplist: true }},
  172. { keys: 'gn', type: 'motion', motion: 'findAndSelectNextInclusive', motionArgs: { forward: true }},
  173. { keys: 'gN', type: 'motion', motion: 'findAndSelectNextInclusive', motionArgs: { forward: false }},
  174. { keys: 'gq', type: 'operator', operator: 'hardWrap' },
  175. { keys: 'gw', type: 'operator', operator: 'hardWrap', operatorArgs: {keepCursor: true}},
  176. // Operator-Motion dual commands
  177. { keys: 'x', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorMotionArgs: { visualLine: false }},
  178. { keys: 'X', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: false }, operatorMotionArgs: { visualLine: true }},
  179. { keys: 'D', type: 'operatorMotion', operator: 'delete', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
  180. { keys: 'D', type: 'operator', operator: 'delete', operatorArgs: { linewise: true }, context: 'visual'},
  181. { keys: 'Y', type: 'operatorMotion', operator: 'yank', motion: 'expandToLine', motionArgs: { linewise: true }, context: 'normal'},
  182. { keys: 'Y', type: 'operator', operator: 'yank', operatorArgs: { linewise: true }, context: 'visual'},
  183. { keys: 'C', type: 'operatorMotion', operator: 'change', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
  184. { keys: 'C', type: 'operator', operator: 'change', operatorArgs: { linewise: true }, context: 'visual'},
  185. { keys: '~', type: 'operatorMotion', operator: 'changeCase', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorArgs: { shouldMoveCursor: true }, context: 'normal'},
  186. { keys: '~', type: 'operator', operator: 'changeCase', context: 'visual'},
  187. { keys: '<C-u>', type: 'operatorMotion', operator: 'delete', motion: 'moveToStartOfLine', context: 'insert' },
  188. { keys: '<C-w>', type: 'operatorMotion', operator: 'delete', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }, context: 'insert' },
  189. //ignore C-w in normal mode
  190. { keys: '<C-w>', type: 'idle', context: 'normal' },
  191. // Actions
  192. { keys: '<C-i>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: true }},
  193. { keys: '<C-o>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: false }},
  194. { keys: '<C-e>', type: 'action', action: 'scroll', actionArgs: { forward: true, linewise: true }},
  195. { keys: '<C-y>', type: 'action', action: 'scroll', actionArgs: { forward: false, linewise: true }},
  196. { keys: 'a', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'charAfter' }, context: 'normal' },
  197. { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'eol' }, context: 'normal' },
  198. { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' },
  199. { keys: 'i', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'inplace' }, context: 'normal' },
  200. { keys: 'gi', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'lastEdit' }, context: 'normal' },
  201. { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'firstNonBlank'}, context: 'normal' },
  202. { keys: 'gI', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'bol'}, context: 'normal' },
  203. { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'startOfSelectedArea' }, context: 'visual' },
  204. { keys: 'o', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: true }, context: 'normal' },
  205. { keys: 'O', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: false }, context: 'normal' },
  206. { keys: 'v', type: 'action', action: 'toggleVisualMode' },
  207. { keys: 'V', type: 'action', action: 'toggleVisualMode', actionArgs: { linewise: true }},
  208. { keys: '<C-v>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }},
  209. { keys: '<C-q>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }},
  210. { keys: 'gv', type: 'action', action: 'reselectLastSelection' },
  211. { keys: 'J', type: 'action', action: 'joinLines', isEdit: true },
  212. { keys: 'gJ', type: 'action', action: 'joinLines', actionArgs: { keepSpaces: true }, isEdit: true },
  213. { keys: 'p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true }},
  214. { keys: 'P', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true }},
  215. { keys: 'r<character>', type: 'action', action: 'replace', isEdit: true },
  216. { keys: '@<register>', type: 'action', action: 'replayMacro' },
  217. { keys: 'q<register>', type: 'action', action: 'enterMacroRecordMode' },
  218. // Handle Replace-mode as a special case of insert mode.
  219. { keys: 'R', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { replace: true }, context: 'normal'},
  220. { keys: 'R', type: 'operator', operator: 'change', operatorArgs: { linewise: true, fullLine: true }, context: 'visual', exitVisualBlock: true},
  221. { keys: 'u', type: 'action', action: 'undo', context: 'normal' },
  222. { keys: 'u', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, context: 'visual', isEdit: true },
  223. { keys: 'U', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, context: 'visual', isEdit: true },
  224. { keys: '<C-r>', type: 'action', action: 'redo' },
  225. { keys: 'm<register>', type: 'action', action: 'setMark' },
  226. { keys: '"<register>', type: 'action', action: 'setRegister' },
  227. { keys: '<C-r><register>', type: 'action', action: 'insertRegister', context: 'insert', isEdit: true },
  228. { keys: '<C-o>', type: 'action', action: 'oneNormalCommand', context: 'insert' },
  229. { keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }},
  230. { keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
  231. { keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }},
  232. { keys: 'z<CR>', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
  233. { keys: 'zb', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }},
  234. { keys: 'z-', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
  235. { keys: '.', type: 'action', action: 'repeatLastEdit' },
  236. { keys: '<C-a>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: true, backtrack: false}},
  237. { keys: '<C-x>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: false, backtrack: false}},
  238. { keys: '<C-t>', type: 'action', action: 'indent', actionArgs: { indentRight: true }, context: 'insert' },
  239. { keys: '<C-d>', type: 'action', action: 'indent', actionArgs: { indentRight: false }, context: 'insert' },
  240. // Text object motions
  241. { keys: 'a<register>', type: 'motion', motion: 'textObjectManipulation' },
  242. { keys: 'i<register>', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }},
  243. // Search
  244. { keys: '/', type: 'search', searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},
  245. { keys: '?', type: 'search', searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},
  246. { keys: '*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
  247. { keys: '#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
  248. { keys: 'g*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},
  249. { keys: 'g#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},
  250. // Ex command
  251. { keys: ':', type: 'ex' }
  252. ];
  253. var defaultKeymapLength = defaultKeymap.length;
  254. /**
  255. * Ex commands
  256. * Care must be taken when adding to the default Ex command map. For any
  257. * pair of commands that have a shared prefix, at least one of their
  258. * shortNames must not match the prefix of the other command.
  259. */
  260. var defaultExCommandMap = [
  261. { name: 'colorscheme', shortName: 'colo' },
  262. { name: 'map' },
  263. { name: 'imap', shortName: 'im' },
  264. { name: 'nmap', shortName: 'nm' },
  265. { name: 'vmap', shortName: 'vm' },
  266. { name: 'omap', shortName: 'om' },
  267. { name: 'noremap', shortName: 'no' },
  268. { name: 'nnoremap', shortName: 'nn' },
  269. { name: 'vnoremap', shortName: 'vn' },
  270. { name: 'inoremap', shortName: 'ino' },
  271. { name: 'onoremap', shortName: 'ono' },
  272. { name: 'unmap' },
  273. { name: 'mapclear', shortName: 'mapc' },
  274. { name: 'nmapclear', shortName: 'nmapc' },
  275. { name: 'vmapclear', shortName: 'vmapc' },
  276. { name: 'imapclear', shortName: 'imapc' },
  277. { name: 'omapclear', shortName: 'omapc' },
  278. { name: 'write', shortName: 'w' },
  279. { name: 'undo', shortName: 'u' },
  280. { name: 'redo', shortName: 'red' },
  281. { name: 'set', shortName: 'se' },
  282. { name: 'setlocal', shortName: 'setl' },
  283. { name: 'setglobal', shortName: 'setg' },
  284. { name: 'sort', shortName: 'sor' },
  285. { name: 'substitute', shortName: 's', possiblyAsync: true },
  286. { name: 'startinsert', shortName: 'start' },
  287. { name: 'nohlsearch', shortName: 'noh' },
  288. { name: 'yank', shortName: 'y' },
  289. { name: 'delmarks', shortName: 'delm' },
  290. { name: 'registers', shortName: 'reg', excludeFromCommandHistory: true },
  291. { name: 'vglobal', shortName: 'v' },
  292. { name: 'delete', shortName: 'd' },
  293. { name: 'join', shortName: 'j' },
  294. { name: 'normal', shortName: 'norm' },
  295. { name: 'global', shortName: 'g' }
  296. ];
  297. /**
  298. * Langmap
  299. * Determines how to interpret keystrokes in Normal and Visual mode.
  300. * Useful for people who use a different keyboard layout than QWERTY
  301. */
  302. var langmap = parseLangmap('');
  303. /** @arg {CodeMirror} cm */
  304. function enterVimMode(cm) {
  305. cm.setOption('disableInput', true);
  306. cm.setOption('showCursorWhenSelecting', false);
  307. CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
  308. cm.on('cursorActivity', onCursorActivity);
  309. maybeInitVimState(cm);
  310. // @ts-ignore
  311. CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm));
  312. }
  313. /** @arg {CodeMirror} cm */
  314. function leaveVimMode(cm) {
  315. cm.setOption('disableInput', false);
  316. cm.off('cursorActivity', onCursorActivity);
  317. // @ts-ignore
  318. CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm));
  319. cm.state.vim = null;
  320. if (highlightTimeout) clearTimeout(highlightTimeout);
  321. }
  322. /** @arg {CodeMirrorV} cm */
  323. function getOnPasteFn(cm) {
  324. var vim = cm.state.vim;
  325. if (!vim.onPasteFn) {
  326. vim.onPasteFn = function() {
  327. if (!vim.insertMode) {
  328. cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
  329. actions.enterInsertMode(cm, {}, vim);
  330. }
  331. };
  332. }
  333. return vim.onPasteFn;
  334. }
  335. var numberRegex = /[\d]/;
  336. var wordCharTest = [CodeMirror.isWordChar, function(ch) {
  337. return ch && !CodeMirror.isWordChar(ch) && !/\s/.test(ch);
  338. }], bigWordCharTest = [function(ch) {
  339. return /\S/.test(ch);
  340. }];
  341. var validMarks = ['<', '>'];
  342. var validRegisters = ['-', '"', '.', ':', '_', '/', '+'];
  343. var latinCharRegex = /^\w$/
  344. var upperCaseChars;
  345. try { upperCaseChars = new RegExp("^[\\p{Lu}]$", "u"); }
  346. catch (_) { upperCaseChars = /^[A-Z]$/; }
  347. /** @arg {CodeMirror} cm @arg {number} line */
  348. function isLine(cm, line) {
  349. return line >= cm.firstLine() && line <= cm.lastLine();
  350. }
  351. /** @arg {string} k */
  352. function isLowerCase(k) {
  353. return (/^[a-z]$/).test(k);
  354. }
  355. /** @arg {string} k */
  356. function isMatchableSymbol(k) {
  357. return '()[]{}'.indexOf(k) != -1;
  358. }
  359. /** @arg {string} k */
  360. function isNumber(k) {
  361. return numberRegex.test(k);
  362. }
  363. /** @arg {string} k */
  364. function isUpperCase(k) {
  365. return upperCaseChars.test(k);
  366. }
  367. /** @arg {string} k */
  368. function isWhiteSpaceString(k) {
  369. return (/^\s*$/).test(k);
  370. }
  371. /** @arg {string} k */
  372. function isEndOfSentenceSymbol(k) {
  373. return '.?!'.indexOf(k) != -1;
  374. }
  375. /** @arg {any} val @arg {string | any[]} arr */
  376. function inArray(val, arr) {
  377. for (var i = 0; i < arr.length; i++) {
  378. if (arr[i] == val) {
  379. return true;
  380. }
  381. }
  382. return false;
  383. }
  384. /** @typedef {import("./types").optionCallback} optionCallback */
  385. /** @typedef {import("./types").vimOption} vimOption */
  386. /** @type {Object<string, vimOption>} */
  387. var options = {};
  388. /**
  389. * @arg {string} name
  390. * @arg {any} defaultValue
  391. * @arg {string} type
  392. * @arg {string[] } [aliases]
  393. * @arg {optionCallback} [callback]
  394. * */
  395. function defineOption(name, defaultValue, type, aliases, callback) {
  396. if (defaultValue === undefined && !callback) {
  397. throw Error('defaultValue is required unless callback is provided');
  398. }
  399. if (!type) { type = 'string'; }
  400. options[name] = {
  401. type: type,
  402. defaultValue: defaultValue,
  403. callback: callback
  404. };
  405. if (aliases) {
  406. for (var i = 0; i < aliases.length; i++) {
  407. options[aliases[i]] = options[name];
  408. }
  409. }
  410. if (defaultValue) {
  411. setOption(name, defaultValue);
  412. }
  413. }
  414. /**
  415. * @arg {string} name
  416. * @arg {any} value
  417. * @arg {CodeMirrorV} [cm]
  418. * @arg {{ scope?: any; } | undefined} [cfg] */
  419. function setOption(name, value, cm, cfg) {
  420. var option = options[name];
  421. cfg = cfg || {};
  422. var scope = cfg.scope;
  423. if (!option) {
  424. return new Error('Unknown option: ' + name);
  425. }
  426. if (option.type == 'boolean') {
  427. if (value && value !== true) {
  428. return new Error('Invalid argument: ' + name + '=' + value);
  429. } else if (value !== false) {
  430. // Boolean options are set to true if value is not defined.
  431. value = true;
  432. }
  433. }
  434. if (option.callback) {
  435. if (scope !== 'local') {
  436. option.callback(value, undefined);
  437. }
  438. if (scope !== 'global' && cm) {
  439. option.callback(value, cm);
  440. }
  441. } else {
  442. if (scope !== 'local') {
  443. option.value = option.type == 'boolean' ? !!value : value;
  444. }
  445. if (scope !== 'global' && cm) {
  446. cm.state.vim.options[name] = {value: value};
  447. }
  448. }
  449. }
  450. /**
  451. * @arg {string} name
  452. * @arg {CodeMirrorV} [cm]
  453. * @arg {{ scope?: any; } | undefined} [cfg] */
  454. function getOption(name, cm, cfg) {
  455. var option = options[name];
  456. cfg = cfg || {};
  457. var scope = cfg.scope;
  458. if (!option) {
  459. return new Error('Unknown option: ' + name);
  460. }
  461. if (option.callback) {
  462. let local = cm && option.callback(undefined, cm);
  463. if (scope !== 'global' && local !== undefined) {
  464. return local;
  465. }
  466. if (scope !== 'local') {
  467. return option.callback();
  468. }
  469. return;
  470. } else {
  471. let local = (scope !== 'global') && (cm && cm.state.vim.options[name]);
  472. return (local || (scope !== 'local') && option || {}).value;
  473. }
  474. }
  475. /** @arg {string|undefined} name @arg {CodeMirrorV} [cm] */
  476. defineOption('filetype', undefined, 'string', ['ft'], function(name, cm) {
  477. // Option is local. Do nothing for global.
  478. if (cm === undefined) {
  479. return;
  480. }
  481. // The 'filetype' option proxies to the CodeMirror 'mode' option.
  482. if (name === undefined) {
  483. let mode = cm.getOption('mode');
  484. return mode == 'null' ? '' : mode;
  485. } else {
  486. let mode = name == '' ? 'null' : name;
  487. cm.setOption('mode', mode);
  488. }
  489. });
  490. defineOption('textwidth', 80, 'number', ['tw'], function(width, cm) {
  491. // Option is local. Do nothing for global.
  492. if (cm === undefined) {
  493. return;
  494. }
  495. // The 'filetype' option proxies to the CodeMirror 'mode' option.
  496. if (width === undefined) {
  497. var value = cm.getOption('textwidth');
  498. return value;
  499. } else {
  500. var column = Math.round(/**@type {any}*/(width));
  501. if (column > 1) {
  502. cm.setOption('textwidth', column);
  503. }
  504. }
  505. });
  506. var createCircularJumpList = function() {
  507. var size = 100;
  508. var pointer = -1;
  509. var head = 0;
  510. var tail = 0;
  511. var buffer = new Array(size);
  512. /** @arg {CodeMirror} cm @arg {any} oldCur @arg {any} newCur */
  513. function add(cm, oldCur, newCur) {
  514. var current = pointer % size;
  515. var curMark = buffer[current];
  516. /** @arg {Pos} cursor */
  517. function useNextSlot(cursor) {
  518. var next = ++pointer % size;
  519. var trashMark = buffer[next];
  520. if (trashMark) {
  521. trashMark.clear();
  522. }
  523. buffer[next] = cm.setBookmark(cursor);
  524. }
  525. if (curMark) {
  526. var markPos = curMark.find();
  527. // avoid recording redundant cursor position
  528. if (markPos && !cursorEqual(markPos, oldCur)) {
  529. useNextSlot(oldCur);
  530. }
  531. } else {
  532. useNextSlot(oldCur);
  533. }
  534. useNextSlot(newCur);
  535. head = pointer;
  536. tail = pointer - size + 1;
  537. if (tail < 0) {
  538. tail = 0;
  539. }
  540. }
  541. /** @arg {CodeMirror} cm @arg {number} offset */
  542. function move(cm, offset) {
  543. pointer += offset;
  544. if (pointer > head) {
  545. pointer = head;
  546. } else if (pointer < tail) {
  547. pointer = tail;
  548. }
  549. var mark = buffer[(size + pointer) % size];
  550. // skip marks that are temporarily removed from text buffer
  551. if (mark && !mark.find()) {
  552. var inc = offset > 0 ? 1 : -1;
  553. var newCur;
  554. var oldCur = cm.getCursor();
  555. do {
  556. pointer += inc;
  557. mark = buffer[(size + pointer) % size];
  558. // skip marks that are the same as current position
  559. if (mark &&
  560. (newCur = mark.find()) &&
  561. !cursorEqual(oldCur, newCur)) {
  562. break;
  563. }
  564. } while (pointer < head && pointer > tail);
  565. }
  566. return mark;
  567. }
  568. /** @arg {CodeMirror} cm @arg {number} offset */
  569. function find(cm, offset) {
  570. var oldPointer = pointer;
  571. var mark = move(cm, offset);
  572. pointer = oldPointer;
  573. return mark && mark.find();
  574. }
  575. return {
  576. cachedCursor: undefined, //used for # and * jumps
  577. add: add,
  578. find: find,
  579. move: move
  580. };
  581. };
  582. /**
  583. * Returns an object to track the changes associated insert mode. It
  584. * clones the object that is passed in, or creates an empty object one if
  585. * none is provided.
  586. * @arg {import("./types").InsertModeChanges | undefined} [c]
  587. * @returns {import("./types").InsertModeChanges}
  588. */
  589. var createInsertModeChanges = function(c) {
  590. if (c) {
  591. // Copy construction
  592. return {
  593. changes: c.changes,
  594. expectCursorActivityForChange: c.expectCursorActivityForChange
  595. };
  596. }
  597. return {
  598. // Change list
  599. changes: [],
  600. // Set to true on change, false on cursorActivity.
  601. expectCursorActivityForChange: false
  602. };
  603. };
  604. class MacroModeState {
  605. constructor() {
  606. this.latestRegister = undefined;
  607. this.isPlaying = false;
  608. this.isRecording = false;
  609. this.replaySearchQueries = [];
  610. this.onRecordingDone = undefined;
  611. this.lastInsertModeChanges = createInsertModeChanges();
  612. }
  613. exitMacroRecordMode() {
  614. var macroModeState = vimGlobalState.macroModeState;
  615. if (macroModeState.onRecordingDone) {
  616. macroModeState.onRecordingDone(); // close dialog
  617. }
  618. macroModeState.onRecordingDone = undefined;
  619. macroModeState.isRecording = false;
  620. }
  621. enterMacroRecordMode(cm, registerName) {
  622. var register = vimGlobalState.registerController.getRegister(registerName);
  623. if (register) {
  624. register.clear();
  625. this.latestRegister = registerName;
  626. if (cm.openDialog) {
  627. var template = dom('span', {class: 'cm-vim-message'}, 'recording @' + registerName);
  628. this.onRecordingDone = cm.openDialog(template, null, {bottom:true});
  629. }
  630. this.isRecording = true;
  631. }
  632. }
  633. }
  634. /**
  635. * @arg Codemirror
  636. * @return {vimState}
  637. */
  638. function maybeInitVimState(cm) {
  639. if (!cm.state.vim) {
  640. // Store instance state in the CodeMirror object.
  641. cm.state.vim = {
  642. inputState: new InputState(),
  643. // Vim's input state that triggered the last edit, used to repeat
  644. // motions and operators with '.'.
  645. lastEditInputState: undefined,
  646. // Vim's action command before the last edit, used to repeat actions
  647. // with '.' and insert mode repeat.
  648. lastEditActionCommand: undefined,
  649. // When using jk for navigation, if you move from a longer line to a
  650. // shorter line, the cursor may clip to the end of the shorter line.
  651. // If j is pressed again and cursor goes to the next line, the
  652. // cursor should go back to its horizontal position on the longer
  653. // line if it can. This is to keep track of the horizontal position.
  654. lastHPos: -1,
  655. // Doing the same with screen-position for gj/gk
  656. lastHSPos: -1,
  657. // The last motion command run. Cleared if a non-motion command gets
  658. // executed in between.
  659. lastMotion: null,
  660. marks: {},
  661. insertMode: false,
  662. insertModeReturn: false,
  663. // Repeat count for changes made in insert mode, triggered by key
  664. // sequences like 3,i. Only exists when insertMode is true.
  665. insertModeRepeat: undefined,
  666. visualMode: false,
  667. // If we are in visual line mode. No effect if visualMode is false.
  668. visualLine: false,
  669. visualBlock: false,
  670. lastSelection: null,
  671. lastPastedText: null,
  672. sel: {},
  673. // Buffer-local/window-local values of vim options.
  674. options: {},
  675. // Whether the next character should be interpreted literally
  676. // Necassary for correct implementation of f<character>, r<character> etc.
  677. // in terms of langmaps.
  678. expectLiteralNext: false
  679. };
  680. }
  681. return cm.state.vim;
  682. }
  683. /**
  684. * @type {
  685. {
  686. macroModeState: MacroModeState;
  687. registerController: RegisterController;
  688. searchHistoryController: HistoryController;
  689. jumpList: any;
  690. exCommandHistoryController: HistoryController;
  691. lastCharacterSearch: any;
  692. query?: any;
  693. isReversed?: any;
  694. lastSubstituteReplacePart: any;
  695. searchQuery?: null;
  696. searchIsReversed?: boolean;
  697. }
  698. }
  699. */
  700. var vimGlobalState;
  701. function resetVimGlobalState() {
  702. vimGlobalState = {
  703. // The current search query.
  704. searchQuery: null,
  705. // Whether we are searching backwards.
  706. searchIsReversed: false,
  707. // Replace part of the last substituted pattern
  708. lastSubstituteReplacePart: undefined,
  709. jumpList: createCircularJumpList(),
  710. macroModeState: new MacroModeState(),
  711. // Recording latest f, t, F or T motion command.
  712. lastCharacterSearch: {increment:0, forward:true, selectedCharacter:''},
  713. registerController: new RegisterController({}),
  714. // search history buffer
  715. searchHistoryController: new HistoryController(),
  716. // ex Command history buffer
  717. exCommandHistoryController : new HistoryController()
  718. };
  719. for (var optionName in options) {
  720. var option = options[optionName];
  721. option.value = option.defaultValue;
  722. }
  723. }
  724. /** @type {number | undefined|false} */
  725. var lastInsertModeKeyTimer;
  726. var vimApi = {
  727. enterVimMode: enterVimMode,
  728. leaveVimMode: leaveVimMode,
  729. buildKeyMap: function() {
  730. // TODO: Convert keymap into dictionary format for fast lookup.
  731. },
  732. // Testing hook, though it might be useful to expose the register
  733. // controller anyway.
  734. getRegisterController: function() {
  735. return vimGlobalState.registerController;
  736. },
  737. // Testing hook.
  738. resetVimGlobalState_: resetVimGlobalState,
  739. // Testing hook.
  740. getVimGlobalState_: function() {
  741. return vimGlobalState;
  742. },
  743. // Testing hook.
  744. maybeInitVimState_: maybeInitVimState,
  745. suppressErrorLogging: false,
  746. InsertModeKey: InsertModeKey,
  747. /**@type {(lhs: string, rhs: string, ctx: string) => void} */
  748. map: function(lhs, rhs, ctx) {
  749. // Add user defined key bindings.
  750. exCommandDispatcher.map(lhs, rhs, ctx);
  751. },
  752. /**@type {(lhs: string, ctx: string) => any} */
  753. unmap: function(lhs, ctx) {
  754. return exCommandDispatcher.unmap(lhs, ctx);
  755. },
  756. // Non-recursive map function.
  757. // NOTE: This will not create mappings to key maps that aren't present
  758. // in the default key map. See TODO at bottom of function.
  759. /**@type {(lhs: string, rhs: string, ctx: string) => void} */
  760. noremap: function(lhs, rhs, ctx) {
  761. exCommandDispatcher.map(lhs, rhs, ctx, true);
  762. },
  763. // Remove all user-defined mappings for the provided context.
  764. /**@arg {string} [ctx]} */
  765. mapclear: function(ctx) {
  766. // Partition the existing keymap into user-defined and true defaults.
  767. var actualLength = defaultKeymap.length,
  768. origLength = defaultKeymapLength;
  769. var userKeymap = defaultKeymap.slice(0, actualLength - origLength);
  770. defaultKeymap = defaultKeymap.slice(actualLength - origLength);
  771. if (ctx) {
  772. // If a specific context is being cleared, we need to keep mappings
  773. // from all other contexts.
  774. for (var i = userKeymap.length - 1; i >= 0; i--) {
  775. var mapping = userKeymap[i];
  776. if (ctx !== mapping.context) {
  777. if (mapping.context) {
  778. this._mapCommand(mapping);
  779. } else {
  780. // `mapping` applies to all contexts so create keymap copies
  781. // for each context except the one being cleared.
  782. var contexts = ['normal', 'insert', 'visual'];
  783. for (var j in contexts) {
  784. if (contexts[j] !== ctx) {
  785. var newMapping = Object.assign({}, mapping);
  786. newMapping.context = contexts[j];
  787. this._mapCommand(newMapping);
  788. }
  789. }
  790. }
  791. }
  792. }
  793. }
  794. },
  795. langmap: updateLangmap,
  796. vimKeyFromEvent: vimKeyFromEvent,
  797. // TODO: Expose setOption and getOption as instance methods. Need to decide how to namespace
  798. // them, or somehow make them work with the existing CodeMirror setOption/getOption API.
  799. setOption: setOption,
  800. getOption: getOption,
  801. defineOption: defineOption,
  802. /**@type {(name: string, prefix: string|undefined, func: ExFn) => void} */
  803. defineEx: function(name, prefix, func){
  804. if (!prefix) {
  805. prefix = name;
  806. } else if (name.indexOf(prefix) !== 0) {
  807. throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered');
  808. }
  809. exCommands[name]=func;
  810. exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'};
  811. },
  812. /**@type {(cm: CodeMirror, key: string, origin: string) => undefined | boolean} */
  813. handleKey: function (cm, key, origin) {
  814. var command = this.findKey(cm, key, origin);
  815. if (typeof command === 'function') {
  816. return command();
  817. }
  818. },
  819. multiSelectHandleKey: multiSelectHandleKey,
  820. /**
  821. * This is the outermost function called by CodeMirror, after keys have
  822. * been mapped to their Vim equivalents.
  823. *
  824. * Finds a command based on the key (and cached keys if there is a
  825. * multi-key sequence). Returns `undefined` if no key is matched, a noop
  826. * function if a partial match is found (multi-key), and a function to
  827. * execute the bound command if a a key is matched. The function always
  828. * returns true.
  829. */
  830. /**@type {(cm_: CodeMirror, key: string, origin?: string| undefined) => (() => boolean) | undefined} */
  831. findKey: function(cm_, key, origin) {
  832. var vim = maybeInitVimState(cm_);
  833. var cm = /**@type {CodeMirrorV}*/(cm_);
  834. function handleMacroRecording() {
  835. var macroModeState = vimGlobalState.macroModeState;
  836. if (macroModeState.isRecording) {
  837. if (key == 'q') {
  838. macroModeState.exitMacroRecordMode();
  839. clearInputState(cm);
  840. return true;
  841. }
  842. if (origin != 'mapping') {
  843. logKey(macroModeState, key);
  844. }
  845. }
  846. }
  847. function handleEsc() {
  848. if (key == '<Esc>') {
  849. if (vim.visualMode) {
  850. // Get back to normal mode.
  851. exitVisualMode(cm);
  852. } else if (vim.insertMode) {
  853. // Get back to normal mode.
  854. exitInsertMode(cm);
  855. } else {
  856. // We're already in normal mode. Let '<Esc>' be handled normally.
  857. return;
  858. }
  859. clearInputState(cm);
  860. return true;
  861. }
  862. }
  863. function handleKeyInsertMode() {
  864. if (handleEsc()) { return true; }
  865. vim.inputState.keyBuffer.push(key);
  866. var keys = vim.inputState.keyBuffer.join("");
  867. var keysAreChars = key.length == 1;
  868. var match = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
  869. var changeQueue = vim.inputState.changeQueue;
  870. if (match.type == 'none') { clearInputState(cm); return false; }
  871. else if (match.type == 'partial') {
  872. if (match.expectLiteralNext) vim.expectLiteralNext = true;
  873. if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
  874. lastInsertModeKeyTimer = keysAreChars && window.setTimeout(
  875. function() { if (vim.insertMode && vim.inputState.keyBuffer.length) { clearInputState(cm); } },
  876. getOption('insertModeEscKeysTimeout'));
  877. if (keysAreChars) {
  878. var selections = cm.listSelections();
  879. if (!changeQueue || changeQueue.removed.length != selections.length)
  880. changeQueue = vim.inputState.changeQueue = new ChangeQueue;
  881. changeQueue.inserted += key;
  882. for (var i = 0; i < selections.length; i++) {
  883. var from = cursorMin(selections[i].anchor, selections[i].head);
  884. var to = cursorMax(selections[i].anchor, selections[i].head);
  885. var text = cm.getRange(from, cm.state.overwrite ? offsetCursor(to, 0, 1) : to);
  886. changeQueue.removed[i] = (changeQueue.removed[i] || "") + text;
  887. }
  888. }
  889. return !keysAreChars;
  890. }
  891. vim.expectLiteralNext = false;
  892. if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
  893. if (match.command && changeQueue) {
  894. var selections = cm.listSelections();
  895. for (var i = 0; i < selections.length; i++) {
  896. var here = selections[i].head;
  897. cm.replaceRange(changeQueue.removed[i] || "",
  898. offsetCursor(here, 0, -changeQueue.inserted.length), here, '+input');
  899. }
  900. vimGlobalState.macroModeState.lastInsertModeChanges.changes.pop();
  901. }
  902. if (!match.command) clearInputState(cm);
  903. return match.command;
  904. }
  905. function handleKeyNonInsertMode() {
  906. if (handleMacroRecording() || handleEsc()) { return true; }
  907. vim.inputState.keyBuffer.push(key);
  908. var keys = vim.inputState.keyBuffer.join("");
  909. if (/^[1-9]\d*$/.test(keys)) { return true; }
  910. var keysMatcher = /^(\d*)(.*)$/.exec(keys);
  911. if (!keysMatcher) { clearInputState(cm); return false; }
  912. var context = vim.visualMode ? 'visual' :
  913. 'normal';
  914. var mainKey = keysMatcher[2] || keysMatcher[1];
  915. if (vim.inputState.operatorShortcut && vim.inputState.operatorShortcut.slice(-1) == mainKey) {
  916. // multikey operators act linewise by repeating only the last character
  917. mainKey = vim.inputState.operatorShortcut;
  918. }
  919. var match = commandDispatcher.matchCommand(mainKey, defaultKeymap, vim.inputState, context);
  920. if (match.type == 'none') { clearInputState(cm); return false; }
  921. else if (match.type == 'partial') {
  922. if (match.expectLiteralNext) vim.expectLiteralNext = true;
  923. return true;
  924. }
  925. else if (match.type == 'clear') { clearInputState(cm); return true; }
  926. vim.expectLiteralNext = false;
  927. vim.inputState.keyBuffer.length = 0;
  928. keysMatcher = /^(\d*)(.*)$/.exec(keys);
  929. if (keysMatcher && keysMatcher[1] && keysMatcher[1] != '0') {
  930. vim.inputState.pushRepeatDigit(keysMatcher[1]);
  931. }
  932. return match.command;
  933. }
  934. var command;
  935. if (vim.insertMode) { command = handleKeyInsertMode(); }
  936. else { command = handleKeyNonInsertMode(); }
  937. if (command === false) {
  938. return !vim.insertMode && key.length === 1 ? function() { return true; } : undefined;
  939. } else if (command === true) {
  940. // TODO: Look into using CodeMirror's multi-key handling.
  941. // Return no-op since we are caching the key. Counts as handled, but
  942. // don't want act on it just yet.
  943. return function() { return true; };
  944. } else {
  945. return function() {
  946. return cm.operation(function() {
  947. // @ts-ignore
  948. cm.curOp.isVimOp = true;
  949. try {
  950. if (command.type == 'keyToKey') {
  951. doKeyToKey(cm, command.toKeys, command);
  952. } else {
  953. commandDispatcher.processCommand(cm, vim, command);
  954. }
  955. } catch (e) {
  956. // clear VIM state in case it's in a bad state.
  957. // @ts-ignore
  958. cm.state.vim = undefined;
  959. maybeInitVimState(cm);
  960. if (!vimApi.suppressErrorLogging) {
  961. console['log'](e);
  962. }
  963. throw e;
  964. }
  965. return true;
  966. });
  967. };
  968. }
  969. },
  970. handleEx: function(cm, input) {
  971. exCommandDispatcher.processCommand(cm, input);
  972. },
  973. defineMotion: defineMotion,
  974. defineAction: defineAction,
  975. defineOperator: defineOperator,
  976. mapCommand: mapCommand,
  977. _mapCommand: _mapCommand,
  978. defineRegister: defineRegister,
  979. exitVisualMode: exitVisualMode,
  980. exitInsertMode: exitInsertMode
  981. };
  982. var keyToKeyStack = [];
  983. var noremap = false;
  984. var virtualPrompt;
  985. function sendKeyToPrompt(key) {
  986. if (key[0] == "<") {
  987. var lowerKey = key.toLowerCase().slice(1, -1);
  988. var parts = lowerKey.split('-');
  989. lowerKey = parts.pop() || '';
  990. if (lowerKey == 'lt') key = '<';
  991. else if (lowerKey == 'space') key = ' ';
  992. else if (lowerKey == 'cr') key = '\n';
  993. else if (vimToCmKeyMap[lowerKey]) {
  994. var value = virtualPrompt.value;
  995. var event = {
  996. key: vimToCmKeyMap[lowerKey],
  997. target: {
  998. value: value,
  999. selectionEnd: value.length,
  1000. selectionStart: value.length
  1001. }
  1002. }
  1003. if (virtualPrompt.onKeyDown) {
  1004. virtualPrompt.onKeyDown(event, virtualPrompt.value, close);
  1005. }
  1006. if (virtualPrompt && virtualPrompt.onKeyUp) {
  1007. virtualPrompt.onKeyUp(event, virtualPrompt.value, close);
  1008. }
  1009. return;
  1010. }
  1011. }
  1012. if (key == '\n') {
  1013. var prompt = virtualPrompt;
  1014. virtualPrompt = null;
  1015. prompt.onClose && prompt.onClose(prompt.value);
  1016. } else {
  1017. virtualPrompt.value = (virtualPrompt.value || '') + key;
  1018. }
  1019. function close(value) {
  1020. if (typeof value == 'string') { virtualPrompt.value = value; }
  1021. else { virtualPrompt = null; }
  1022. }
  1023. }
  1024. function doKeyToKey(cm, keys, fromKey) {
  1025. var noremapBefore = noremap;
  1026. // prevent infinite recursion.
  1027. if (fromKey) {
  1028. if (keyToKeyStack.indexOf(fromKey) != -1) return;
  1029. keyToKeyStack.push(fromKey);
  1030. noremap = fromKey.noremap != false;
  1031. }
  1032. try {
  1033. var vim = maybeInitVimState(cm);
  1034. var keyRe = /<(?:[CSMA]-)*\w+>|./gi;
  1035. var match;
  1036. // Pull off one command key, which is either a single character
  1037. // or a special sequence wrapped in '<' and '>', e.g. '<Space>'.
  1038. while ((match = keyRe.exec(keys))) {
  1039. var key = match[0];
  1040. var wasInsert = vim.insertMode;
  1041. if (virtualPrompt) {
  1042. sendKeyToPrompt(key);
  1043. continue;
  1044. }
  1045. var result = vimApi.handleKey(cm, key, 'mapping');
  1046. if (!result && wasInsert && vim.insertMode) {
  1047. if (key[0] == "<") {
  1048. var lowerKey = key.toLowerCase().slice(1, -1);
  1049. var parts = lowerKey.split('-');
  1050. lowerKey = parts.pop() || '';
  1051. if (lowerKey == 'lt') key = '<';
  1052. else if (lowerKey == 'space') key = ' ';
  1053. else if (lowerKey == 'cr') key = '\n';
  1054. else if (vimToCmKeyMap.hasOwnProperty(lowerKey)) {
  1055. // todo support codemirror keys in insertmode vimToCmKeyMap
  1056. key = vimToCmKeyMap[lowerKey];
  1057. sendCmKey(cm, key);
  1058. continue;
  1059. } else {
  1060. key = key[0];
  1061. keyRe.lastIndex = match.index + 1;
  1062. }
  1063. }
  1064. cm.replaceSelection(key);
  1065. }
  1066. }
  1067. } finally {
  1068. keyToKeyStack.pop();
  1069. noremap = keyToKeyStack.length ? noremapBefore : false;
  1070. if (!keyToKeyStack.length && virtualPrompt) {
  1071. var promptOptions = virtualPrompt;
  1072. virtualPrompt = null;
  1073. showPrompt(cm, promptOptions);
  1074. }
  1075. }
  1076. }
  1077. var specialKey = {
  1078. Return: 'CR', Backspace: 'BS', 'Delete': 'Del', Escape: 'Esc', Insert: 'Ins',
  1079. ArrowLeft: 'Left', ArrowRight: 'Right', ArrowUp: 'Up', ArrowDown: 'Down',
  1080. Enter: 'CR', ' ': 'Space'
  1081. };
  1082. var ignoredKeys = { Shift: 1, Alt: 1, Command: 1, Control: 1,
  1083. CapsLock: 1, AltGraph: 1, Dead: 1, Unidentified: 1 };
  1084. var vimToCmKeyMap = {};
  1085. 'Left|Right|Up|Down|End|Home'.split('|').concat(Object.keys(specialKey)).forEach(function(x) {
  1086. vimToCmKeyMap[(specialKey[x] || '').toLowerCase()]
  1087. = vimToCmKeyMap[x.toLowerCase()] = x;
  1088. });
  1089. function vimKeyFromEvent(e, vim) {
  1090. var key = e.key;
  1091. if (ignoredKeys[key]) return;
  1092. if (key.length > 1 && key[0] == "n") {
  1093. key = key.replace("Numpad", "");
  1094. }
  1095. key = specialKey[key] || key;
  1096. var name = '';
  1097. if (e.ctrlKey) { name += 'C-'; }
  1098. if (e.altKey) { name += 'A-'; }
  1099. if (e.metaKey) { name += 'M-'; }
  1100. // on mac many characters are entered as option- combos
  1101. // (e.g. on swiss keyboard { is option-8)
  1102. // so we ignore lonely A- modifier for keypress event on mac
  1103. if (CodeMirror.isMac && e.altKey && !e.metaKey && !e.ctrlKey) {
  1104. name = name.slice(2);
  1105. }
  1106. if ((name || key.length > 1) && e.shiftKey) { name += 'S-'; }
  1107. if (vim && !vim.expectLiteralNext && key.length == 1) {
  1108. if (langmap.keymap && key in langmap.keymap) {
  1109. if (langmap.remapCtrl != false || !name)
  1110. key = langmap.keymap[key];
  1111. } else if (key.charCodeAt(0) > 255) {
  1112. var code = e.code?.slice(-1) || "";
  1113. if (!e.shiftKey) code = code.toLowerCase();
  1114. if (code) key = code;
  1115. }
  1116. }
  1117. name += key;
  1118. if (name.length > 1) { name = '<' + name + '>'; }
  1119. return name;
  1120. };
  1121. // langmap support
  1122. function updateLangmap(langmapString, remapCtrl) {
  1123. if (langmap.string !== langmapString) {
  1124. langmap = parseLangmap(langmapString);
  1125. }
  1126. langmap.remapCtrl = remapCtrl;
  1127. }
  1128. /**
  1129. * From :help langmap
  1130. * The 'langmap' option is a list of parts, separated with commas. Each
  1131. * part can be in one of two forms:
  1132. * 1. A list of pairs. Each pair is a "from" character immediately
  1133. * followed by the "to" character. Examples: "aA", "aAbBcC".
  1134. * 2. A list of "from" characters, a semi-colon and a list of "to"
  1135. * characters. Example: "abc;ABC"
  1136. * @arg {string} langmapString
  1137. * @returns {{string: string, keymap: Record<string, string>, remapCtrl?: boolean}}
  1138. */
  1139. function parseLangmap(langmapString) {
  1140. let keymap = ({})/**@type {Record<string, string>}*/;
  1141. if (!langmapString) return { keymap: keymap, string: '' };
  1142. function getEscaped(list) {
  1143. return list.split(/\\?(.)/).filter(Boolean);
  1144. }
  1145. langmapString.split(/((?:[^\\,]|\\.)+),/).map(part => {
  1146. if (!part) return;
  1147. const semicolon = part.split(/((?:[^\\;]|\\.)+);/);
  1148. if (semicolon.length == 3) {
  1149. const from = getEscaped(semicolon[1]);
  1150. const to = getEscaped(semicolon[2]);
  1151. if (from.length !== to.length) return; // skip over malformed part
  1152. for (let i = 0; i < from.length; ++i) keymap[from[i]] = to[i];
  1153. } else if (semicolon.length == 1) {
  1154. const pairs = getEscaped(part);
  1155. if (pairs.length % 2 !== 0) return; // skip over malformed part
  1156. for (let i = 0; i < pairs.length; i += 2) keymap[pairs[i]] = pairs[i + 1];
  1157. }
  1158. });
  1159. return { keymap: keymap, string: langmapString };
  1160. }
  1161. defineOption('langmap', undefined, 'string', ['lmap'], function(name, cm) {
  1162. // The 'filetype' option proxies to the CodeMirror 'mode' option.
  1163. if (name === undefined) {
  1164. return langmap.string;
  1165. } else {
  1166. updateLangmap(name);
  1167. }
  1168. });
  1169. // Represents the current input state.
  1170. class InputState {
  1171. constructor() {
  1172. this.prefixRepeat = [];
  1173. this.motionRepeat = [];
  1174. this.operator = null;
  1175. this.operatorArgs = null;
  1176. this.motion = null;
  1177. this.motionArgs = null;
  1178. this.keyBuffer = []; // For matching multi-key commands.
  1179. this.registerName = null; // Defaults to the unnamed register.
  1180. this.changeQueue = null; // For restoring text used by insert mode keybindings
  1181. }
  1182. pushRepeatDigit(n) {
  1183. if (!this.operator) {
  1184. this.prefixRepeat = this.prefixRepeat.concat(n);
  1185. } else {
  1186. this.motionRepeat = this.motionRepeat.concat(n);
  1187. }
  1188. }
  1189. getRepeat() {
  1190. var repeat = 0;
  1191. if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) {
  1192. repeat = 1;
  1193. if (this.prefixRepeat.length > 0) {
  1194. repeat *= parseInt(this.prefixRepeat.join(''), 10);
  1195. }
  1196. if (this.motionRepeat.length > 0) {
  1197. repeat *= parseInt(this.motionRepeat.join(''), 10);
  1198. }
  1199. }
  1200. return repeat;
  1201. }
  1202. }
  1203. /** @arg {CodeMirrorV} cm @arg {string} [reason] */
  1204. function clearInputState(cm, reason) {
  1205. cm.state.vim.inputState = new InputState();
  1206. cm.state.vim.expectLiteralNext = false;
  1207. CodeMirror.signal(cm, 'vim-command-done', reason);
  1208. }
  1209. function ChangeQueue() {
  1210. this.removed = [];
  1211. this.inserted = "";
  1212. }
  1213. /**
  1214. * Register stores information about copy and paste registers. Besides
  1215. * text, a register must store whether it is linewise (i.e., when it is
  1216. * pasted, should it insert itself into a new line, or should the text be
  1217. * inserted at the cursor position.)
  1218. */
  1219. class Register {
  1220. constructor(text, linewise, blockwise) {
  1221. this.clear();
  1222. this.keyBuffer = [text || ''];
  1223. this.insertModeChanges = [];
  1224. this.searchQueries = [];
  1225. this.linewise = !!linewise;
  1226. this.blockwise = !!blockwise;
  1227. }
  1228. setText(text, linewise, blockwise) {
  1229. this.keyBuffer = [text || ''];
  1230. this.linewise = !!linewise;
  1231. this.blockwise = !!blockwise;
  1232. }
  1233. pushText(text, linewise) {
  1234. // if this register has ever been set to linewise, use linewise.
  1235. if (linewise) {
  1236. if (!this.linewise) {
  1237. this.keyBuffer.push('\n');
  1238. }
  1239. this.linewise = true;
  1240. }
  1241. this.keyBuffer.push(text);
  1242. }
  1243. pushInsertModeChanges(changes) {
  1244. this.insertModeChanges.push(createInsertModeChanges(changes));
  1245. }
  1246. pushSearchQuery(query) {
  1247. this.searchQueries.push(query);
  1248. }
  1249. clear() {
  1250. this.keyBuffer = [];
  1251. this.insertModeChanges = [];
  1252. this.searchQueries = [];
  1253. this.linewise = false;
  1254. }
  1255. toString() {
  1256. return this.keyBuffer.join('');
  1257. }
  1258. }
  1259. /**
  1260. * Defines an external register.
  1261. *
  1262. * The name should be a single character that will be used to reference the register.
  1263. * The register should support setText, pushText, clear, and toString(). See Register
  1264. * for a reference implementation.
  1265. * @arg {string} name
  1266. * @arg {Register} register
  1267. */
  1268. function defineRegister(name, register) {
  1269. var registers = vimGlobalState.registerController.registers;
  1270. if (!name || name.length != 1) {
  1271. throw Error('Register name must be 1 character');
  1272. }
  1273. if (registers[name]) {
  1274. throw Error('Register already defined ' + name);
  1275. }
  1276. registers[name] = register;
  1277. validRegisters.push(name);
  1278. }
  1279. /**
  1280. * vim registers allow you to keep many independent copy and paste buffers.
  1281. * See http://usevim.com/2012/04/13/registers/ for an introduction.
  1282. *
  1283. * RegisterController keeps the state of all the registers. An initial
  1284. * state may be passed in. The unnamed register '"' will always be
  1285. * overridden.
  1286. */
  1287. class RegisterController {
  1288. /** @arg {Object<string, Register>} registers */
  1289. constructor(registers) {
  1290. this.registers = registers;
  1291. this.unnamedRegister = registers['"'] = new Register();
  1292. registers['.'] = new Register();
  1293. registers[':'] = new Register();
  1294. registers['/'] = new Register();
  1295. registers['+'] = new Register();
  1296. }
  1297. pushText(registerName, operator, text, linewise, blockwise) {
  1298. // The black hole register, "_, means delete/yank to nowhere.
  1299. if (registerName === '_') return;
  1300. if (linewise && text.charAt(text.length - 1) !== '\n') {
  1301. text += '\n';
  1302. }
  1303. // Lowercase and uppercase registers refer to the same register.
  1304. // Uppercase just means append.
  1305. var register = this.isValidRegister(registerName) ?
  1306. this.getRegister(registerName) : null;
  1307. // if no register/an invalid register was specified, things go to the
  1308. // default registers
  1309. if (!register) {
  1310. switch (operator) {
  1311. case 'yank':
  1312. // The 0 register contains the text from the most recent yank.
  1313. this.registers['0'] = new Register(text, linewise, blockwise);
  1314. break;
  1315. case 'delete':
  1316. case 'change':
  1317. if (text.indexOf('\n') == -1) {
  1318. // Delete less than 1 line. Update the small delete register.
  1319. this.registers['-'] = new Register(text, linewise);
  1320. } else {
  1321. // Shift down the contents of the numbered registers and put the
  1322. // deleted text into register 1.
  1323. this.shiftNumericRegisters_();
  1324. this.registers['1'] = new Register(text, linewise);
  1325. }
  1326. break;
  1327. }
  1328. // Make sure the unnamed register is set to what just happened
  1329. this.unnamedRegister.setText(text, linewise, blockwise);
  1330. return;
  1331. }
  1332. // If we've gotten to this point, we've actually specified a register
  1333. var append = isUpperCase(registerName);
  1334. if (append) {
  1335. register.pushText(text, linewise);
  1336. } else {
  1337. register.setText(text, linewise, blockwise);
  1338. }
  1339. if (registerName === '+') {
  1340. navigator.clipboard.writeText(text);
  1341. }
  1342. // The unnamed register always has the same value as the last used
  1343. // register.
  1344. this.unnamedRegister.setText(register.toString(), linewise);
  1345. }
  1346. /**
  1347. * Gets the register named @name. If one of @name doesn't already exist,
  1348. * create it. If @name is invalid, return the unnamedRegister.
  1349. * @arg {string} [name]
  1350. */
  1351. getRegister(name) {
  1352. if (!this.isValidRegister(name)) {
  1353. return this.unnamedRegister;
  1354. }
  1355. name = name.toLowerCase();
  1356. if (!this.registers[name]) {
  1357. this.registers[name] = new Register();
  1358. }
  1359. return this.registers[name];
  1360. }
  1361. /**@type {{(name: any): name is string}} */
  1362. isValidRegister(name) {
  1363. return name && (inArray(name, validRegisters) || latinCharRegex.test(name));
  1364. }
  1365. shiftNumericRegisters_() {
  1366. for (var i = 9; i >= 2; i--) {
  1367. this.registers[i] = this.getRegister('' + (i - 1));
  1368. }
  1369. }
  1370. }
  1371. class HistoryController {
  1372. constructor() {
  1373. this.historyBuffer = [];
  1374. this.iterator = 0;
  1375. this.initialPrefix = null;
  1376. }
  1377. // the input argument here acts a user entered prefix for a small time
  1378. // until we start autocompletion in which case it is the autocompleted.
  1379. nextMatch(input, up) {
  1380. var historyBuffer = this.historyBuffer;
  1381. var dir = up ? -1 : 1;
  1382. if (this.initialPrefix === null) this.initialPrefix = input;
  1383. for (var i = this.iterator + dir; up ? i >= 0 : i < historyBuffer.length; i += dir) {
  1384. var element = historyBuffer[i];
  1385. for (var j = 0; j <= element.length; j++) {
  1386. if (this.initialPrefix == element.substring(0, j)) {
  1387. this.iterator = i;
  1388. return element;
  1389. }
  1390. }
  1391. }
  1392. // should return the user input in case we reach the end of buffer.
  1393. if (i >= historyBuffer.length) {
  1394. this.iterator = historyBuffer.length;
  1395. return this.initialPrefix;
  1396. }
  1397. // return the last autocompleted query or exCommand as it is.
  1398. if (i < 0) return input;
  1399. }
  1400. pushInput(input) {
  1401. var index = this.historyBuffer.indexOf(input);
  1402. if (index > -1) this.historyBuffer.splice(index, 1);
  1403. if (input.length) this.historyBuffer.push(input);
  1404. }
  1405. reset() {
  1406. this.initialPrefix = null;
  1407. this.iterator = this.historyBuffer.length;
  1408. }
  1409. }
  1410. var commandDispatcher = {
  1411. matchCommand: function(keys, keyMap, inputState, context) {
  1412. var matches = commandMatches(keys, keyMap, context, inputState);
  1413. if (!matches.full && !matches.partial) {
  1414. return {type: 'none'};
  1415. } else if (!matches.full && matches.partial) {
  1416. return {
  1417. type: 'partial',
  1418. expectLiteralNext: matches.partial.length == 1 && matches.partial[0].keys.slice(-11) == '<character>' // langmap literal logic
  1419. };
  1420. }
  1421. var bestMatch;
  1422. // @ts-ignore
  1423. for (var i = 0; i < matches.full.length; i++) {
  1424. var match = matches.full[i];
  1425. if (!bestMatch) {
  1426. bestMatch = match;
  1427. }
  1428. }
  1429. if (bestMatch.keys.slice(-11) == '<character>' || bestMatch.keys.slice(-10) == '<register>') {
  1430. var character = lastChar(keys);
  1431. if (!character || character.length > 1) return {type: 'clear'};
  1432. inputState.selectedCharacter = character;
  1433. }
  1434. return {type: 'full', command: bestMatch};
  1435. },
  1436. /**
  1437. * @arg {CodeMirrorV} cm
  1438. * @arg {vimState} vim
  1439. * @arg {vimKey} command
  1440. */
  1441. processCommand: function(cm, vim, command) {
  1442. vim.inputState.repeatOverride = command.repeatOverride;
  1443. switch (command.type) {
  1444. case 'motion':
  1445. this.processMotion(cm, vim, command);
  1446. break;
  1447. case 'operator':
  1448. this.processOperator(cm, vim, command);
  1449. break;
  1450. case 'operatorMotion':
  1451. this.processOperatorMotion(cm, vim, command);
  1452. break;
  1453. case 'action':
  1454. this.processAction(cm, vim, command);
  1455. break;
  1456. case 'search':
  1457. this.processSearch(cm, vim, command);
  1458. break;
  1459. case 'ex':
  1460. case 'keyToEx':
  1461. this.processEx(cm, vim, command);
  1462. break;
  1463. default:
  1464. break;
  1465. }
  1466. },
  1467. /**
  1468. * @arg {CodeMirrorV} cm
  1469. * @arg {vimState} vim
  1470. * @arg {import("./types").motionCommand|import("./types").operatorMotionCommand} command
  1471. */
  1472. processMotion: function(cm, vim, command) {
  1473. vim.inputState.motion = command.motion;
  1474. vim.inputState.motionArgs = /**@type {MotionArgs}*/(copyArgs(command.motionArgs));
  1475. this.evalInput(cm, vim);
  1476. },
  1477. /**
  1478. * @arg {CodeMirrorV} cm
  1479. * @arg {vimState} vim
  1480. * @arg {import("./types").operatorCommand|import("./types").operatorMotionCommand} command
  1481. */
  1482. processOperator: function(cm, vim, command) {
  1483. var inputState = vim.inputState;
  1484. if (inputState.operator) {
  1485. if (inputState.operator == command.operator) {
  1486. // Typing an operator twice like 'dd' makes the operator operate
  1487. // linewise
  1488. inputState.motion = 'expandToLine';
  1489. inputState.motionArgs = { linewise: true, repeat: 1 };
  1490. this.evalInput(cm, vim);
  1491. return;
  1492. } else {
  1493. // 2 different operators in a row doesn't make sense.
  1494. clearInputState(cm);
  1495. }
  1496. }
  1497. inputState.operator = command.operator;
  1498. inputState.operatorArgs = copyArgs(command.operatorArgs);
  1499. if (command.keys.length > 1) {
  1500. inputState.operatorShortcut = command.keys;
  1501. }
  1502. if (command.exitVisualBlock) {
  1503. vim.visualBlock = false;
  1504. updateCmSelection(cm);
  1505. }
  1506. if (vim.visualMode) {
  1507. // Operating on a selection in visual mode. We don't need a motion.
  1508. this.evalInput(cm, vim);
  1509. }
  1510. },
  1511. /**
  1512. * @arg {CodeMirrorV} cm
  1513. * @arg {vimState} vim
  1514. * @arg {import("./types").operatorMotionCommand} command
  1515. */
  1516. processOperatorMotion: function(cm, vim, command) {
  1517. var visualMode = vim.visualMode;
  1518. var operatorMotionArgs = copyArgs(command.operatorMotionArgs);
  1519. if (operatorMotionArgs) {
  1520. // Operator motions may have special behavior in visual mode.
  1521. if (visualMode && operatorMotionArgs.visualLine) {
  1522. vim.visualLine = true;
  1523. }
  1524. }
  1525. this.processOperator(cm, vim, command);
  1526. if (!visualMode) {
  1527. this.processMotion(cm, vim, command);
  1528. }
  1529. },
  1530. /**
  1531. * @arg {CodeMirrorV} cm
  1532. * @arg {vimState} vim
  1533. * @arg {import("./types").actionCommand} command
  1534. */
  1535. processAction: function(cm, vim, command) {
  1536. var inputState = vim.inputState;
  1537. var repeat = inputState.getRepeat();
  1538. var repeatIsExplicit = !!repeat;
  1539. var actionArgs = /**@type {ActionArgs}*/(copyArgs(command.actionArgs) || {repeat: 1});
  1540. if (inputState.selectedCharacter) {
  1541. actionArgs.selectedCharacter = inputState.selectedCharacter;
  1542. }
  1543. // Actions may or may not have motions and operators. Do these first.
  1544. if (command.operator) {
  1545. // @ts-ignore
  1546. this.processOperator(cm, vim, command);
  1547. }
  1548. if (command.motion) {
  1549. // @ts-ignore
  1550. this.processMotion(cm, vim, command);
  1551. }
  1552. if (command.motion || command.operator) {
  1553. this.evalInput(cm, vim);
  1554. }
  1555. actionArgs.repeat = repeat || 1;
  1556. actionArgs.repeatIsExplicit = repeatIsExplicit;
  1557. actionArgs.registerName = inputState.registerName;
  1558. clearInputState(cm);
  1559. vim.lastMotion = null;
  1560. if (command.isEdit) {
  1561. this.recordLastEdit(vim, inputState, command);
  1562. }
  1563. actions[command.action](cm, actionArgs, vim);
  1564. },
  1565. /** @arg {CodeMirrorV} cm @arg {vimState} vim @arg {import("./types").searchCommand} command*/
  1566. processSearch: function(cm, vim, command) {
  1567. if (!cm.getSearchCursor) {
  1568. // Search depends on SearchCursor.
  1569. return;
  1570. }
  1571. var forward = command.searchArgs.forward;
  1572. var wholeWordOnly = command.searchArgs.wholeWordOnly;
  1573. getSearchState(cm).setReversed(!forward);
  1574. var promptPrefix = (forward) ? '/' : '?';
  1575. var originalQuery = getSearchState(cm).getQuery();
  1576. var originalScrollPos = cm.getScrollInfo();
  1577. /** @arg {string} query @arg {boolean} ignoreCase @arg {boolean} smartCase */
  1578. function handleQuery(query, ignoreCase, smartCase) {
  1579. vimGlobalState.searchHistoryController.pushInput(query);
  1580. vimGlobalState.searchHistoryController.reset();
  1581. try {
  1582. updateSearchQuery(cm, query, ignoreCase, smartCase);
  1583. } catch (e) {
  1584. showConfirm(cm, 'Invalid regex: ' + query);
  1585. clearInputState(cm);
  1586. return;
  1587. }
  1588. commandDispatcher.processMotion(cm, vim, {
  1589. keys: '',
  1590. type: 'motion',
  1591. motion: 'findNext',
  1592. motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist }
  1593. });
  1594. }
  1595. /** @arg {string} query */
  1596. function onPromptClose(query) {
  1597. cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
  1598. handleQuery(query, true /** ignoreCase */, true /** smartCase */);
  1599. var macroModeState = vimGlobalState.macroModeState;
  1600. if (macroModeState.isRecording) {
  1601. logSearchQuery(macroModeState, query);
  1602. }
  1603. }
  1604. /**
  1605. * @arg {KeyboardEvent&{target:HTMLInputElement}} e
  1606. * @arg {any} query
  1607. * @arg {(arg0: any) => void} close
  1608. */
  1609. function onPromptKeyUp(e, query, close) {
  1610. var keyName = vimKeyFromEvent(e), up, offset;
  1611. if (keyName == '<Up>' || keyName == '<Down>') {
  1612. up = keyName == '<Up>' ? true : false;
  1613. offset = e.target ? e.target.selectionEnd : 0;
  1614. query = vimGlobalState.searchHistoryController.nextMatch(query, up) || '';
  1615. close(query);
  1616. if (offset && e.target) e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length);
  1617. } else if (keyName && keyName != '<Left>' && keyName != '<Right>') {
  1618. vimGlobalState.searchHistoryController.reset();
  1619. }
  1620. var parsedQuery;
  1621. try {
  1622. parsedQuery = updateSearchQuery(cm, query,
  1623. true /** ignoreCase */, true /** smartCase */);
  1624. } catch (e) {
  1625. // Swallow bad regexes for incremental search.
  1626. }
  1627. if (parsedQuery) {
  1628. cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30);
  1629. } else {
  1630. clearSearchHighlight(cm);
  1631. cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
  1632. }
  1633. }
  1634. /** @arg {KeyboardEvent} e @arg {string} query @arg {(arg0?: string) => void} close */
  1635. function onPromptKeyDown(e, query, close) {
  1636. var keyName = vimKeyFromEvent(e);
  1637. if (keyName == '<Esc>' || keyName == '<C-c>' || keyName == '<C-[>' ||
  1638. (keyName == '<BS>' && query == '')) {
  1639. vimGlobalState.searchHistoryController.pushInput(query);
  1640. vimGlobalState.searchHistoryController.reset();
  1641. updateSearchQuery(cm, originalQuery);
  1642. clearSearchHighlight(cm);
  1643. cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
  1644. CodeMirror.e_stop(e);
  1645. clearInputState(cm);
  1646. close();
  1647. cm.focus();
  1648. } else if (keyName == '<Up>' || keyName == '<Down>') {
  1649. CodeMirror.e_stop(e);
  1650. } else if (keyName == '<C-u>') {
  1651. // Ctrl-U clears input.
  1652. CodeMirror.e_stop(e);
  1653. close('');
  1654. }
  1655. }
  1656. switch (command.searchArgs.querySrc) {
  1657. case 'prompt':
  1658. var macroModeState = vimGlobalState.macroModeState;
  1659. if (macroModeState.isPlaying) {
  1660. let query = macroModeState.replaySearchQueries.shift();
  1661. handleQuery(query, true /** ignoreCase */, false /** smartCase */);
  1662. } else {
  1663. showPrompt(cm, {
  1664. onClose: onPromptClose,
  1665. prefix: promptPrefix,
  1666. desc: '(JavaScript regexp)',
  1667. onKeyUp: onPromptKeyUp,
  1668. onKeyDown: onPromptKeyDown
  1669. });
  1670. }
  1671. break;
  1672. case 'wordUnderCursor':
  1673. var word = expandWordUnderCursor(cm, {noSymbol: true});
  1674. var isKeyword = true;
  1675. if (!word) {
  1676. word = expandWordUnderCursor(cm, {noSymbol: false});
  1677. isKeyword = false;
  1678. }
  1679. if (!word) {
  1680. showConfirm(cm, 'No word under cursor');
  1681. clearInputState(cm);
  1682. return;
  1683. }
  1684. let query = cm.getLine(word.start.line).substring(word.start.ch,
  1685. word.end.ch);
  1686. if (isKeyword && wholeWordOnly) {
  1687. query = '\\b' + query + '\\b';
  1688. } else {
  1689. query = escapeRegex(query);
  1690. }
  1691. // cachedCursor is used to save the old position of the cursor
  1692. // when * or # causes vim to seek for the nearest word and shift
  1693. // the cursor before entering the motion.
  1694. vimGlobalState.jumpList.cachedCursor = cm.getCursor();
  1695. cm.setCursor(word.start);
  1696. handleQuery(query, true /** ignoreCase */, false /** smartCase */);
  1697. break;
  1698. }
  1699. },
  1700. /**
  1701. * @arg {CodeMirrorV} cm
  1702. * @arg {vimState} vim
  1703. * @arg {import("./types").exCommand | import("./types").keyToExCommand} command
  1704. */
  1705. processEx: function(cm, vim, command) {
  1706. /**@arg {string} input*/
  1707. function onPromptClose(input) {
  1708. // Give the prompt some time to close so that if processCommand shows
  1709. // an error, the elements don't overlap.
  1710. vimGlobalState.exCommandHistoryController.pushInput(input);
  1711. vimGlobalState.exCommandHistoryController.reset();
  1712. exCommandDispatcher.processCommand(cm, input);
  1713. if (cm.state.vim) clearInputState(cm);
  1714. }
  1715. /**
  1716. * @arg {KeyboardEvent&{target:HTMLInputElement}} e
  1717. * @arg {string} input
  1718. * @arg {(arg0?: string) => void} close
  1719. */
  1720. function onPromptKeyDown(e, input, close) {
  1721. var keyName = vimKeyFromEvent(e), up, offset;
  1722. if (keyName == '<Esc>' || keyName == '<C-c>' || keyName == '<C-[>' ||
  1723. (keyName == '<BS>' && input == '')) {
  1724. vimGlobalState.exCommandHistoryController.pushInput(input);
  1725. vimGlobalState.exCommandHistoryController.reset();
  1726. CodeMirror.e_stop(e);
  1727. clearInputState(cm);
  1728. close();
  1729. cm.focus();
  1730. }
  1731. if (keyName == '<Up>' || keyName == '<Down>') {
  1732. CodeMirror.e_stop(e);
  1733. up = keyName == '<Up>' ? true : false;
  1734. offset = e.target ? e.target.selectionEnd : 0;
  1735. input = vimGlobalState.exCommandHistoryController.nextMatch(input, up) || '';
  1736. close(input);
  1737. if (offset && e.target) e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length);
  1738. } else if (keyName == '<C-u>') {
  1739. // Ctrl-U clears input.
  1740. CodeMirror.e_stop(e);
  1741. close('');
  1742. } else if (keyName && keyName != '<Left>' && keyName != '<Right>') {
  1743. vimGlobalState.exCommandHistoryController.reset();
  1744. }
  1745. }
  1746. if (command.type == 'keyToEx') {
  1747. // Handle user defined Ex to Ex mappings
  1748. exCommandDispatcher.processCommand(cm, command.exArgs.input);
  1749. } else {
  1750. if (vim.visualMode) {
  1751. showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>',
  1752. onKeyDown: onPromptKeyDown, selectValueOnOpen: false});
  1753. } else {
  1754. showPrompt(cm, { onClose: onPromptClose, prefix: ':',
  1755. onKeyDown: onPromptKeyDown});
  1756. }
  1757. }
  1758. },
  1759. /**@arg {CodeMirrorV} cm @arg {vimState} vim */
  1760. evalInput: function(cm, vim) {
  1761. // If the motion command is set, execute both the operator and motion.
  1762. // Otherwise return.
  1763. var inputState = vim.inputState;
  1764. var motion = inputState.motion;
  1765. /** @type {MotionArgs}*/
  1766. var motionArgs = inputState.motionArgs || { repeat: 1};
  1767. var operator = inputState.operator;
  1768. /** @type {OperatorArgs}*/
  1769. var operatorArgs = inputState.operatorArgs || {};
  1770. var registerName = inputState.registerName;
  1771. var sel = vim.sel;
  1772. // TODO: Make sure cm and vim selections are identical outside visual mode.
  1773. var origHead = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.head): cm.getCursor('head'));
  1774. var origAnchor = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.anchor) : cm.getCursor('anchor'));
  1775. var oldHead = copyCursor(origHead);
  1776. var oldAnchor = copyCursor(origAnchor);
  1777. var newHead, newAnchor;
  1778. var repeat;
  1779. if (operator) {
  1780. this.recordLastEdit(vim, inputState);
  1781. }
  1782. if (inputState.repeatOverride !== undefined) {
  1783. // If repeatOverride is specified, that takes precedence over the
  1784. // input state's repeat. Used by Ex mode and can be user defined.
  1785. repeat = inputState.repeatOverride;
  1786. } else {
  1787. repeat = inputState.getRepeat();
  1788. }
  1789. if (repeat > 0 && motionArgs.explicitRepeat) {
  1790. motionArgs.repeatIsExplicit = true;
  1791. } else if (motionArgs.noRepeat ||
  1792. (!motionArgs.explicitRepeat && repeat === 0)) {
  1793. repeat = 1;
  1794. motionArgs.repeatIsExplicit = false;
  1795. }
  1796. if (inputState.selectedCharacter) {
  1797. // If there is a character input, stick it in all of the arg arrays.
  1798. motionArgs.selectedCharacter = operatorArgs.selectedCharacter =
  1799. inputState.selectedCharacter;
  1800. }
  1801. motionArgs.repeat = repeat;
  1802. clearInputState(cm);
  1803. if (motion) {
  1804. var motionResult = motions[motion](cm, origHead, motionArgs, vim, inputState);
  1805. vim.lastMotion = motions[motion];
  1806. if (!motionResult) {
  1807. return;
  1808. }
  1809. if (motionArgs.toJumplist) {
  1810. var jumpList = vimGlobalState.jumpList;
  1811. // if the current motion is # or *, use cachedCursor
  1812. var cachedCursor = jumpList.cachedCursor;
  1813. if (cachedCursor) {
  1814. // @ts-ignore
  1815. recordJumpPosition(cm, cachedCursor, motionResult);
  1816. delete jumpList.cachedCursor;
  1817. } else {
  1818. // @ts-ignore
  1819. recordJumpPosition(cm, origHead, motionResult);
  1820. }
  1821. }
  1822. if (motionResult instanceof Array) {
  1823. newAnchor = motionResult[0];
  1824. newHead = motionResult[1];
  1825. } else {
  1826. newHead = motionResult;
  1827. }
  1828. // TODO: Handle null returns from motion commands better.
  1829. if (!newHead) {
  1830. newHead = copyCursor(origHead);
  1831. }
  1832. if (vim.visualMode) {
  1833. if (!(vim.visualBlock && newHead.ch === Infinity)) {
  1834. newHead = clipCursorToContent(cm, newHead, oldHead);
  1835. }
  1836. if (newAnchor) {
  1837. newAnchor = clipCursorToContent(cm, newAnchor);
  1838. }
  1839. newAnchor = newAnchor || oldAnchor;
  1840. sel.anchor = newAnchor;
  1841. sel.head = newHead;
  1842. updateCmSelection(cm);
  1843. updateMark(cm, vim, '<',
  1844. cursorIsBefore(newAnchor, newHead) ? newAnchor
  1845. : newHead);
  1846. updateMark(cm, vim, '>',
  1847. cursorIsBefore(newAnchor, newHead) ? newHead
  1848. : newAnchor);
  1849. } else if (!operator) {
  1850. newHead = clipCursorToContent(cm, newHead, oldHead);
  1851. cm.setCursor(newHead.line, newHead.ch);
  1852. }
  1853. }
  1854. if (operator) {
  1855. if (operatorArgs.lastSel) {
  1856. // Replaying a visual mode operation
  1857. newAnchor = oldAnchor;
  1858. var lastSel = operatorArgs.lastSel;
  1859. var lineOffset = Math.abs(lastSel.head.line - lastSel.anchor.line);
  1860. var chOffset = Math.abs(lastSel.head.ch - lastSel.anchor.ch);
  1861. if (lastSel.visualLine) {
  1862. // Linewise Visual mode: The same number of lines.
  1863. newHead = new Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
  1864. } else if (lastSel.visualBlock) {
  1865. // Blockwise Visual mode: The same number of lines and columns.
  1866. newHead = new Pos(oldAnchor.line + lineOffset, oldAnchor.ch + chOffset);
  1867. } else if (lastSel.head.line == lastSel.anchor.line) {
  1868. // Normal Visual mode within one line: The same number of characters.
  1869. newHead = new Pos(oldAnchor.line, oldAnchor.ch + chOffset);
  1870. } else {
  1871. // Normal Visual mode with several lines: The same number of lines, in the
  1872. // last line the same number of characters as in the last line the last time.
  1873. newHead = new Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
  1874. }
  1875. vim.visualMode = true;
  1876. vim.visualLine = lastSel.visualLine;
  1877. vim.visualBlock = lastSel.visualBlock;
  1878. sel = vim.sel = {
  1879. anchor: newAnchor,
  1880. head: newHead
  1881. };
  1882. updateCmSelection(cm);
  1883. } else if (vim.visualMode) {
  1884. operatorArgs.lastSel = {
  1885. anchor: copyCursor(sel.anchor),
  1886. head: copyCursor(sel.head),
  1887. visualBlock: vim.visualBlock,
  1888. visualLine: vim.visualLine
  1889. };
  1890. }
  1891. var curStart, curEnd, linewise;
  1892. /** @type {'block'|'line'|'char'}*/ var mode;
  1893. var cmSel;
  1894. if (vim.visualMode) {
  1895. // Init visual op
  1896. curStart = cursorMin(sel.head, sel.anchor);
  1897. curEnd = cursorMax(sel.head, sel.anchor);
  1898. linewise = vim.visualLine || operatorArgs.linewise;
  1899. mode = vim.visualBlock ? 'block' :
  1900. linewise ? 'line' :
  1901. 'char';
  1902. var newPositions = updateSelectionForSurrogateCharacters(cm, curStart, curEnd);
  1903. cmSel = makeCmSelection(cm, {
  1904. anchor: newPositions.start,
  1905. head: newPositions.end
  1906. }, mode);
  1907. if (linewise) {
  1908. var ranges = cmSel.ranges;
  1909. if (mode == 'block') {
  1910. // Linewise operators in visual block mode extend to end of line
  1911. for (var i = 0; i < ranges.length; i++) {
  1912. ranges[i].head.ch = lineLength(cm, ranges[i].head.line);
  1913. }
  1914. } else if (mode == 'line') {
  1915. ranges[0].head = new Pos(ranges[0].head.line + 1, 0);
  1916. }
  1917. }
  1918. } else {
  1919. // Init motion op
  1920. curStart = copyCursor(newAnchor || oldAnchor);
  1921. curEnd = copyCursor(newHead || oldHead);
  1922. if (cursorIsBefore(curEnd, curStart)) {
  1923. var tmp = curStart;
  1924. curStart = curEnd;
  1925. curEnd = tmp;
  1926. }
  1927. linewise = motionArgs.linewise || operatorArgs.linewise;
  1928. if (linewise) {
  1929. // Expand selection to entire line.
  1930. expandSelectionToLine(cm, curStart, curEnd);
  1931. } else if (motionArgs.forward) {
  1932. // Clip to trailing newlines only if the motion goes forward.
  1933. clipToLine(cm, curStart, curEnd);
  1934. }
  1935. mode = 'char';
  1936. var exclusive = !motionArgs.inclusive || linewise;
  1937. var newPositions = updateSelectionForSurrogateCharacters(cm, curStart, curEnd);
  1938. cmSel = makeCmSelection(cm, {
  1939. anchor: newPositions.start,
  1940. head: newPositions.end
  1941. }, mode, exclusive);
  1942. }
  1943. cm.setSelections(cmSel.ranges, cmSel.primary);
  1944. vim.lastMotion = null;
  1945. operatorArgs.repeat = repeat; // For indent in visual mode.
  1946. operatorArgs.registerName = registerName;
  1947. // Keep track of linewise as it affects how paste and change behave.
  1948. operatorArgs.linewise = linewise;
  1949. var operatorMoveTo = operators[operator](
  1950. cm, operatorArgs, cmSel.ranges, oldAnchor, newHead);
  1951. if (vim.visualMode) {
  1952. exitVisualMode(cm, operatorMoveTo != null);
  1953. }
  1954. if (operatorMoveTo) {
  1955. cm.setCursor(operatorMoveTo);
  1956. }
  1957. }
  1958. },
  1959. /**@arg {vimState} vim @arg {InputStateInterface} inputState, @arg {import("./types").actionCommand} [actionCommand] */
  1960. recordLastEdit: function(vim, inputState, actionCommand) {
  1961. var macroModeState = vimGlobalState.macroModeState;
  1962. if (macroModeState.isPlaying) { return; }
  1963. vim.lastEditInputState = inputState;
  1964. vim.lastEditActionCommand = actionCommand;
  1965. macroModeState.lastInsertModeChanges.changes = [];
  1966. macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false;
  1967. macroModeState.lastInsertModeChanges.visualBlock = vim.visualBlock ? vim.sel.head.line - vim.sel.anchor.line : 0;
  1968. }
  1969. };
  1970. /**
  1971. * All of the functions below return Cursor objects.
  1972. * @type {import("./types").vimMotions}}
  1973. */
  1974. var motions = {
  1975. moveToTopLine: function(cm, _head, motionArgs) {
  1976. var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;
  1977. return new Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
  1978. },
  1979. moveToMiddleLine: function(cm) {
  1980. var range = getUserVisibleLines(cm);
  1981. var line = Math.floor((range.top + range.bottom) * 0.5);
  1982. return new Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
  1983. },
  1984. moveToBottomLine: function(cm, _head, motionArgs) {
  1985. var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;
  1986. return new Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
  1987. },
  1988. expandToLine: function(_cm, head, motionArgs) {
  1989. // Expands forward to end of line, and then to next line if repeat is
  1990. // >1. Does not handle backward motion!
  1991. var cur = head;
  1992. return new Pos(cur.line + motionArgs.repeat - 1, Infinity);
  1993. },
  1994. findNext: function(cm, _head, motionArgs) {
  1995. var state = getSearchState(cm);
  1996. var query = state.getQuery();
  1997. if (!query) {
  1998. return;
  1999. }
  2000. var prev = !motionArgs.forward;
  2001. // If search is initiated with ? instead of /, negate direction.
  2002. prev = (state.isReversed()) ? !prev : prev;
  2003. highlightSearchMatches(cm, query);
  2004. return findNext(cm, prev/** prev */, query, motionArgs.repeat);
  2005. },
  2006. /**
  2007. * Find and select the next occurrence of the search query. If the cursor is currently
  2008. * within a match, then find and select the current match. Otherwise, find the next occurrence in the
  2009. * appropriate direction.
  2010. *
  2011. * This differs from `findNext` in the following ways:
  2012. *
  2013. * 1. Instead of only returning the "from", this returns a "from", "to" range.
  2014. * 2. If the cursor is currently inside a search match, this selects the current match
  2015. * instead of the next match.
  2016. * 3. If there is no associated operator, this will turn on visual mode.
  2017. */
  2018. findAndSelectNextInclusive: function(cm, _head, motionArgs, vim, prevInputState) {
  2019. var state = getSearchState(cm);
  2020. var query = state.getQuery();
  2021. if (!query) {
  2022. return;
  2023. }
  2024. var prev = !motionArgs.forward;
  2025. prev = (state.isReversed()) ? !prev : prev;
  2026. // next: [from, to] | null
  2027. var next = findNextFromAndToInclusive(cm, prev, query, motionArgs.repeat, vim);
  2028. // No matches.
  2029. if (!next) {
  2030. return;
  2031. }
  2032. // If there's an operator that will be executed, return the selection.
  2033. if (prevInputState.operator) {
  2034. return next;
  2035. }
  2036. // At this point, we know that there is no accompanying operator -- let's
  2037. // deal with visual mode in order to select an appropriate match.
  2038. var from = next[0];
  2039. // For whatever reason, when we use the "to" as returned by searchcursor.js directly,
  2040. // the resulting selection is extended by 1 char. Let's shrink it so that only the
  2041. // match is selected.
  2042. var to = new Pos(next[1].line, next[1].ch - 1);
  2043. if (vim.visualMode) {
  2044. // If we were in visualLine or visualBlock mode, get out of it.
  2045. if (vim.visualLine || vim.visualBlock) {
  2046. vim.visualLine = false;
  2047. vim.visualBlock = false;
  2048. CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: ""});
  2049. }
  2050. // If we're currently in visual mode, we should extend the selection to include
  2051. // the search result.
  2052. var anchor = vim.sel.anchor;
  2053. if (anchor) {
  2054. if (state.isReversed()) {
  2055. if (motionArgs.forward) {
  2056. return [anchor, from];
  2057. }
  2058. return [anchor, to];
  2059. } else {
  2060. if (motionArgs.forward) {
  2061. return [anchor, to];
  2062. }
  2063. return [anchor, from];
  2064. }
  2065. }
  2066. } else {
  2067. // Let's turn visual mode on.
  2068. vim.visualMode = true;
  2069. vim.visualLine = false;
  2070. vim.visualBlock = false;
  2071. CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: ""});
  2072. }
  2073. return prev ? [to, from] : [from, to];
  2074. },
  2075. goToMark: function(cm, _head, motionArgs, vim) {
  2076. var pos = getMarkPos(cm, vim, motionArgs.selectedCharacter || "");
  2077. if (pos) {
  2078. return motionArgs.linewise ? { line: pos.line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line)) } : pos;
  2079. }
  2080. return null;
  2081. },
  2082. moveToOtherHighlightedEnd: function(cm, _head, motionArgs, vim) {
  2083. if (vim.visualBlock && motionArgs.sameLine) {
  2084. var sel = vim.sel;
  2085. return [
  2086. clipCursorToContent(cm, new Pos(sel.anchor.line, sel.head.ch)),
  2087. clipCursorToContent(cm, new Pos(sel.head.line, sel.anchor.ch))
  2088. ];
  2089. } else {
  2090. return ([vim.sel.head, vim.sel.anchor]);
  2091. }
  2092. },
  2093. jumpToMark: function(cm, head, motionArgs, vim) {
  2094. var best = head;
  2095. for (var i = 0; i < motionArgs.repeat; i++) {
  2096. var cursor = best;
  2097. for (var key in vim.marks) {
  2098. if (!isLowerCase(key)) {
  2099. continue;
  2100. }
  2101. var mark = vim.marks[key].find();
  2102. var isWrongDirection = (motionArgs.forward) ?
  2103. // @ts-ignore
  2104. cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark);
  2105. if (isWrongDirection) {
  2106. continue;
  2107. }
  2108. // @ts-ignore
  2109. if (motionArgs.linewise && (mark.line == cursor.line)) {
  2110. continue;
  2111. }
  2112. var equal = cursorEqual(cursor, best);
  2113. var between = (motionArgs.forward) ?
  2114. // @ts-ignore
  2115. cursorIsBetween(cursor, mark, best) :
  2116. // @ts-ignore
  2117. cursorIsBetween(best, mark, cursor);
  2118. if (equal || between) {
  2119. // @ts-ignore
  2120. best = mark;
  2121. }
  2122. }
  2123. }
  2124. if (motionArgs.linewise) {
  2125. // Vim places the cursor on the first non-whitespace character of
  2126. // the line if there is one, else it places the cursor at the end
  2127. // of the line, regardless of whether a mark was found.
  2128. best = new Pos(best.line, findFirstNonWhiteSpaceCharacter(cm.getLine(best.line)));
  2129. }
  2130. return best;
  2131. },
  2132. moveByCharacters: function(_cm, head, motionArgs) {
  2133. var cur = head;
  2134. var repeat = motionArgs.repeat;
  2135. var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;
  2136. return new Pos(cur.line, ch);
  2137. },
  2138. moveByLines: function(cm, head, motionArgs, vim) {
  2139. var cur = head;
  2140. var endCh = cur.ch;
  2141. // Depending what our last motion was, we may want to do different
  2142. // things. If our last motion was moving vertically, we want to
  2143. // preserve the HPos from our last horizontal move. If our last motion
  2144. // was going to the end of a line, moving vertically we should go to
  2145. // the end of the line, etc.
  2146. switch (vim.lastMotion) {
  2147. case this.moveByLines:
  2148. case this.moveByDisplayLines:
  2149. case this.moveByScroll:
  2150. case this.moveToColumn:
  2151. case this.moveToEol:
  2152. endCh = vim.lastHPos;
  2153. break;
  2154. default:
  2155. vim.lastHPos = endCh;
  2156. }
  2157. var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0);
  2158. var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat;
  2159. var first = cm.firstLine();
  2160. var last = cm.lastLine();
  2161. var posV = cm.findPosV(cur, (motionArgs.forward ? repeat : -repeat), 'line', vim.lastHSPos);
  2162. var hasMarkedText = motionArgs.forward ? posV.line > line : posV.line < line;
  2163. if (hasMarkedText) {
  2164. line = posV.line;
  2165. endCh = posV.ch;
  2166. }
  2167. // Vim go to line begin or line end when cursor at first/last line and
  2168. // move to previous/next line is triggered.
  2169. if (line < first && cur.line == first){
  2170. return this.moveToStartOfLine(cm, head, motionArgs, vim);
  2171. } else if (line > last && cur.line == last){
  2172. return moveToEol(cm, head, motionArgs, vim, true);
  2173. }
  2174. if (motionArgs.toFirstChar){
  2175. endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));
  2176. vim.lastHPos = endCh;
  2177. }
  2178. vim.lastHSPos = cm.charCoords(new Pos(line, endCh),'div').left;
  2179. return new Pos(line, endCh);
  2180. },
  2181. moveByDisplayLines: function(cm, head, motionArgs, vim) {
  2182. var cur = head;
  2183. switch (vim.lastMotion) {
  2184. case this.moveByDisplayLines:
  2185. case this.moveByScroll:
  2186. case this.moveByLines:
  2187. case this.moveToColumn:
  2188. case this.moveToEol:
  2189. break;
  2190. default:
  2191. vim.lastHSPos = cm.charCoords(cur,'div').left;
  2192. }
  2193. var repeat = motionArgs.repeat;
  2194. var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos);
  2195. if (res.hitSide) {
  2196. if (motionArgs.forward) {
  2197. var lastCharCoords = cm.charCoords(res, 'div');
  2198. var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos };
  2199. res = cm.coordsChar(goalCoords, 'div');
  2200. } else {
  2201. var resCoords = cm.charCoords(new Pos(cm.firstLine(), 0), 'div');
  2202. resCoords.left = vim.lastHSPos;
  2203. res = cm.coordsChar(resCoords, 'div');
  2204. }
  2205. }
  2206. vim.lastHPos = res.ch;
  2207. return res;
  2208. },
  2209. moveByPage: function(cm, head, motionArgs) {
  2210. // CodeMirror only exposes functions that move the cursor page down, so
  2211. // doing this bad hack to move the cursor and move it back. evalInput
  2212. // will move the cursor to where it should be in the end.
  2213. var curStart = head;
  2214. var repeat = motionArgs.repeat;
  2215. return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page');
  2216. },
  2217. moveByParagraph: function(cm, head, motionArgs) {
  2218. var dir = motionArgs.forward ? 1 : -1;
  2219. return findParagraph(cm, head, motionArgs.repeat, dir).start;
  2220. },
  2221. moveBySentence: function(cm, head, motionArgs) {
  2222. var dir = motionArgs.forward ? 1 : -1;
  2223. return findSentence(cm, head, motionArgs.repeat, dir);
  2224. },
  2225. moveByScroll: function(cm, head, motionArgs, vim) {
  2226. var scrollbox = cm.getScrollInfo();
  2227. var curEnd = null;
  2228. var repeat = motionArgs.repeat;
  2229. if (!repeat) {
  2230. repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
  2231. }
  2232. var orig = cm.charCoords(head, 'local');
  2233. motionArgs.repeat = repeat;
  2234. curEnd = motions.moveByDisplayLines(cm, head, motionArgs, vim);
  2235. if (!curEnd) {
  2236. return null;
  2237. }
  2238. var dest = cm.charCoords(curEnd, 'local');
  2239. cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
  2240. return curEnd;
  2241. },
  2242. moveByWords: function(cm, head, motionArgs) {
  2243. return moveToWord(cm, head, motionArgs.repeat, !!motionArgs.forward,
  2244. !!motionArgs.wordEnd, !!motionArgs.bigWord);
  2245. },
  2246. moveTillCharacter: function(cm, head, motionArgs) {
  2247. var repeat = motionArgs.repeat;
  2248. var curEnd = moveToCharacter(cm, repeat, motionArgs.forward,
  2249. motionArgs.selectedCharacter, head);
  2250. var increment = motionArgs.forward ? -1 : 1;
  2251. recordLastCharacterSearch(increment, motionArgs);
  2252. if (!curEnd) return null;
  2253. curEnd.ch += increment;
  2254. return curEnd;
  2255. },
  2256. moveToCharacter: function(cm, head, motionArgs) {
  2257. var repeat = motionArgs.repeat;
  2258. recordLastCharacterSearch(0, motionArgs);
  2259. return moveToCharacter(cm, repeat, motionArgs.forward,
  2260. motionArgs.selectedCharacter, head) || head;
  2261. },
  2262. moveToSymbol: function(cm, head, motionArgs) {
  2263. var repeat = motionArgs.repeat;
  2264. return motionArgs.selectedCharacter
  2265. && findSymbol(cm, repeat, motionArgs.forward,
  2266. motionArgs.selectedCharacter) || head;
  2267. },
  2268. moveToColumn: function(cm, head, motionArgs, vim) {
  2269. var repeat = motionArgs.repeat;
  2270. // repeat is equivalent to which column we want to move to!
  2271. vim.lastHPos = repeat - 1;
  2272. vim.lastHSPos = cm.charCoords(head,'div').left;
  2273. return moveToColumn(cm, repeat);
  2274. },
  2275. moveToEol: function(cm, head, motionArgs, vim) {
  2276. return moveToEol(cm, head, motionArgs, vim, false);
  2277. },
  2278. moveToFirstNonWhiteSpaceCharacter: function(cm, head) {
  2279. // Go to the start of the line where the text begins, or the end for
  2280. // whitespace-only lines
  2281. var cursor = head;
  2282. return new Pos(cursor.line,
  2283. findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)));
  2284. },
  2285. moveToMatchedSymbol: function(cm, head) {
  2286. var cursor = head;
  2287. var line = cursor.line;
  2288. var ch = cursor.ch;
  2289. var lineText = cm.getLine(line);
  2290. var symbol;
  2291. for (; ch < lineText.length; ch++) {
  2292. symbol = lineText.charAt(ch);
  2293. if (symbol && isMatchableSymbol(symbol)) {
  2294. var style = cm.getTokenTypeAt(new Pos(line, ch + 1));
  2295. if (style !== "string" && style !== "comment") {
  2296. break;
  2297. }
  2298. }
  2299. }
  2300. if (ch < lineText.length) {
  2301. // Only include angle brackets in analysis if they are being matched.
  2302. var re = (symbol === '<' || symbol === '>') ? /[(){}[\]<>]/ : /[(){}[\]]/;
  2303. var matched = cm.findMatchingBracket(new Pos(line, ch), {bracketRegex: re});
  2304. return matched.to;
  2305. } else {
  2306. return cursor;
  2307. }
  2308. },
  2309. moveToStartOfLine: function(_cm, head) {
  2310. return new Pos(head.line, 0);
  2311. },
  2312. moveToLineOrEdgeOfDocument: function(cm, _head, motionArgs) {
  2313. var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine();
  2314. if (motionArgs.repeatIsExplicit) {
  2315. lineNum = motionArgs.repeat - cm.getOption('firstLineNumber');
  2316. }
  2317. return new Pos(lineNum,
  2318. findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)));
  2319. },
  2320. moveToStartOfDisplayLine: function(cm) {
  2321. cm.execCommand("goLineLeft");
  2322. return cm.getCursor();
  2323. },
  2324. moveToEndOfDisplayLine: function(cm) {
  2325. cm.execCommand("goLineRight");
  2326. var head = cm.getCursor();
  2327. if (head.sticky == "before") head.ch--;
  2328. return head;
  2329. },
  2330. textObjectManipulation: function(cm, head, motionArgs, vim) {
  2331. // TODO: lots of possible exceptions that can be thrown here. Try da(
  2332. // outside of a () block.
  2333. /** @type{Object<string, string>} */
  2334. var mirroredPairs = {'(': ')', ')': '(',
  2335. '{': '}', '}': '{',
  2336. '[': ']', ']': '[',
  2337. '<': '>', '>': '<'};
  2338. /** @type{Object<string, boolean>} */
  2339. var selfPaired = {'\'': true, '"': true, '`': true};
  2340. var character = motionArgs.selectedCharacter || "";
  2341. // 'b' refers to '()' block.
  2342. // 'B' refers to '{}' block.
  2343. if (character == 'b') {
  2344. character = '(';
  2345. } else if (character == 'B') {
  2346. character = '{';
  2347. }
  2348. // Inclusive is the difference between a and i
  2349. // TODO: Instead of using the additional text object map to perform text
  2350. // object operations, merge the map into the defaultKeyMap and use
  2351. // motionArgs to define behavior. Define separate entries for 'aw',
  2352. // 'iw', 'a[', 'i[', etc.
  2353. var inclusive = !motionArgs.textObjectInner;
  2354. var tmp, move;
  2355. if (mirroredPairs[character]) {
  2356. move = true;
  2357. tmp = selectCompanionObject(cm, head, character, inclusive);
  2358. if (!tmp) {
  2359. var sc = cm.getSearchCursor(new RegExp("\\" + character, "g"), head)
  2360. if (sc.find()) {
  2361. // @ts-ignore
  2362. tmp = selectCompanionObject(cm, sc.from(), character, inclusive);
  2363. }
  2364. }
  2365. } else if (selfPaired[character]) {
  2366. move = true;
  2367. tmp = findBeginningAndEnd(cm, head, character, inclusive);
  2368. } else if (character === 'W' || character === 'w') {
  2369. var repeat = motionArgs.repeat || 1;
  2370. while (repeat-- > 0) {
  2371. var repeated = expandWordUnderCursor(cm, {
  2372. inclusive,
  2373. innerWord: !inclusive,
  2374. bigWord: character === 'W',
  2375. noSymbol: character === 'W',
  2376. multiline: true
  2377. }, tmp && tmp.end);
  2378. if (repeated) {
  2379. if (!tmp) tmp = repeated;
  2380. tmp.end = repeated.end;
  2381. }
  2382. }
  2383. } else if (character === 'p') {
  2384. tmp = findParagraph(cm, head, motionArgs.repeat, 0, inclusive);
  2385. motionArgs.linewise = true;
  2386. if (vim.visualMode) {
  2387. if (!vim.visualLine) { vim.visualLine = true; }
  2388. } else {
  2389. var operatorArgs = vim.inputState.operatorArgs;
  2390. if (operatorArgs) { operatorArgs.linewise = true; }
  2391. tmp.end.line--;
  2392. }
  2393. } else if (character === 't') {
  2394. tmp = expandTagUnderCursor(cm, head, inclusive);
  2395. } else if (character === 's') {
  2396. // account for cursor on end of sentence symbol
  2397. var content = cm.getLine(head.line);
  2398. if (head.ch > 0 && isEndOfSentenceSymbol(content[head.ch])) {
  2399. head.ch -= 1;
  2400. }
  2401. var end = getSentence(cm, head, motionArgs.repeat, 1, inclusive)
  2402. var start = getSentence(cm, head, motionArgs.repeat, -1, inclusive)
  2403. // closer vim behaviour, 'a' only takes the space after the sentence if there is one before and after
  2404. if (isWhiteSpaceString(cm.getLine(start.line)[start.ch])
  2405. && isWhiteSpaceString(cm.getLine(end.line)[end.ch -1])) {
  2406. start = {line: start.line, ch: start.ch + 1}
  2407. }
  2408. tmp = {start: start, end: end};
  2409. }
  2410. if (!tmp) {
  2411. // No valid text object, don't move.
  2412. return null;
  2413. }
  2414. if (!cm.state.vim.visualMode) {
  2415. return [tmp.start, tmp.end];
  2416. } else {
  2417. return expandSelection(cm, tmp.start, tmp.end, move);
  2418. }
  2419. },
  2420. repeatLastCharacterSearch: function(cm, head, motionArgs) {
  2421. var lastSearch = vimGlobalState.lastCharacterSearch;
  2422. var repeat = motionArgs.repeat;
  2423. var forward = motionArgs.forward === lastSearch.forward;
  2424. var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1);
  2425. cm.moveH(-increment, 'char');
  2426. motionArgs.inclusive = forward ? true : false;
  2427. var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);
  2428. if (!curEnd) {
  2429. cm.moveH(increment, 'char');
  2430. return head;
  2431. }
  2432. curEnd.ch += increment;
  2433. return curEnd;
  2434. }
  2435. };
  2436. /** @arg {string} name @arg {import("./types").MotionFn} fn */
  2437. function defineMotion(name, fn) {
  2438. motions[name] = fn;
  2439. }
  2440. /** @arg {string} val @arg {number} times */
  2441. function fillArray(val, times) {
  2442. var arr = [];
  2443. for (var i = 0; i < times; i++) {
  2444. arr.push(val);
  2445. }
  2446. return arr;
  2447. }
  2448. /**
  2449. * An operator acts on a text selection. It receives the list of selections
  2450. * as input. The corresponding CodeMirror selection is guaranteed to
  2451. * match the input selection.
  2452. */
  2453. /** @type {import("./types").vimOperators} */
  2454. var operators = {
  2455. change: function(cm, args, ranges) {
  2456. var finalHead, text;
  2457. var vim = cm.state.vim;
  2458. var anchor = ranges[0].anchor,
  2459. head = ranges[0].head;
  2460. if (!vim.visualMode) {
  2461. text = cm.getRange(anchor, head);
  2462. var lastState = vim.lastEditInputState;
  2463. if (lastState?.motion == "moveByWords" && !isWhiteSpaceString(text)) {
  2464. // Exclude trailing whitespace if the range is not all whitespace.
  2465. var match = (/\s+$/).exec(text);
  2466. if (match && lastState.motionArgs && lastState.motionArgs.forward) {
  2467. head = offsetCursor(head, 0, - match[0].length);
  2468. text = text.slice(0, - match[0].length);
  2469. }
  2470. }
  2471. if (args.linewise) {
  2472. anchor = new Pos(anchor.line, findFirstNonWhiteSpaceCharacter(cm.getLine(anchor.line)));
  2473. if (head.line > anchor.line) {
  2474. head = new Pos(head.line - 1, Number.MAX_VALUE)
  2475. }
  2476. }
  2477. cm.replaceRange('', anchor, head);
  2478. finalHead = anchor;
  2479. } else if (args.fullLine) {
  2480. head.ch = Number.MAX_VALUE;
  2481. head.line--;
  2482. cm.setSelection(anchor, head)
  2483. text = cm.getSelection();
  2484. cm.replaceSelection("");
  2485. finalHead = anchor;
  2486. } else {
  2487. text = cm.getSelection();
  2488. var replacement = fillArray('', ranges.length);
  2489. cm.replaceSelections(replacement);
  2490. finalHead = cursorMin(ranges[0].head, ranges[0].anchor);
  2491. }
  2492. vimGlobalState.registerController.pushText(
  2493. args.registerName, 'change', text,
  2494. args.linewise, ranges.length > 1);
  2495. actions.enterInsertMode(cm, {head: finalHead}, cm.state.vim);
  2496. },
  2497. delete: function(cm, args, ranges) {
  2498. var finalHead, text;
  2499. var vim = cm.state.vim;
  2500. if (!vim.visualBlock) {
  2501. var anchor = ranges[0].anchor,
  2502. head = ranges[0].head;
  2503. if (args.linewise &&
  2504. head.line != cm.firstLine() &&
  2505. anchor.line == cm.lastLine() &&
  2506. anchor.line == head.line - 1) {
  2507. // Special case for dd on last line (and first line).
  2508. if (anchor.line == cm.firstLine()) {
  2509. anchor.ch = 0;
  2510. } else {
  2511. anchor = new Pos(anchor.line - 1, lineLength(cm, anchor.line - 1));
  2512. }
  2513. }
  2514. text = cm.getRange(anchor, head);
  2515. cm.replaceRange('', anchor, head);
  2516. finalHead = anchor;
  2517. if (args.linewise) {
  2518. finalHead = motions.moveToFirstNonWhiteSpaceCharacter(cm, anchor);
  2519. }
  2520. } else {
  2521. text = cm.getSelection();
  2522. var replacement = fillArray('', ranges.length);
  2523. cm.replaceSelections(replacement);
  2524. finalHead = cursorMin(ranges[0].head, ranges[0].anchor);
  2525. }
  2526. vimGlobalState.registerController.pushText(
  2527. args.registerName, 'delete', text,
  2528. args.linewise, vim.visualBlock);
  2529. return clipCursorToContent(cm, finalHead);
  2530. },
  2531. indent: function(cm, args, ranges) {
  2532. var vim = cm.state.vim;
  2533. var repeat = (vim.visualMode) ? args.repeat : 1;
  2534. if (cm.indentMore) {
  2535. for (var j = 0; j < repeat; j++) {
  2536. if (args.indentRight) cm.indentMore();
  2537. else cm.indentLess();
  2538. }
  2539. } else {
  2540. var startLine = ranges[0].anchor.line;
  2541. var endLine = vim.visualBlock ?
  2542. ranges[ranges.length - 1].anchor.line :
  2543. ranges[0].head.line;
  2544. // In visual mode, n> shifts the selection right n times, instead of
  2545. // shifting n lines right once.
  2546. if (args.linewise) {
  2547. // The only way to delete a newline is to delete until the start of
  2548. // the next line, so in linewise mode evalInput will include the next
  2549. // line. We don't want this in indent, so we go back a line.
  2550. endLine--;
  2551. }
  2552. for (var i = startLine; i <= endLine; i++) {
  2553. for (var j = 0; j < repeat; j++) {
  2554. cm.indentLine(i, args.indentRight);
  2555. }
  2556. }
  2557. }
  2558. return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);
  2559. },
  2560. indentAuto: function(cm, _args, ranges) {
  2561. cm.execCommand("indentAuto");
  2562. return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);
  2563. },
  2564. hardWrap: function(cm, operatorArgs, ranges, oldAnchor) {
  2565. if (!cm.hardWrap) return;
  2566. var from = ranges[0].anchor.line;
  2567. var to = ranges[0].head.line;
  2568. if (operatorArgs.linewise) to--;
  2569. var endRow = cm.hardWrap({from: from, to: to});
  2570. if (endRow > from && operatorArgs.linewise) endRow--;
  2571. return operatorArgs.keepCursor ? oldAnchor : new Pos(endRow, 0);
  2572. },
  2573. changeCase: function(cm, args, ranges, oldAnchor, newHead) {
  2574. var selections = cm.getSelections();
  2575. var swapped = [];
  2576. var toLower = args.toLower;
  2577. for (var j = 0; j < selections.length; j++) {
  2578. var toSwap = selections[j];
  2579. var text = '';
  2580. if (toLower === true) {
  2581. text = toSwap.toLowerCase();
  2582. } else if (toLower === false) {
  2583. text = toSwap.toUpperCase();
  2584. } else {
  2585. for (var i = 0; i < toSwap.length; i++) {
  2586. var character = toSwap.charAt(i);
  2587. text += isUpperCase(character) ? character.toLowerCase() :
  2588. character.toUpperCase();
  2589. }
  2590. }
  2591. swapped.push(text);
  2592. }
  2593. cm.replaceSelections(swapped);
  2594. if (args.shouldMoveCursor){
  2595. return newHead;
  2596. } else if (!cm.state.vim.visualMode && args.linewise && ranges[0].anchor.line + 1 == ranges[0].head.line) {
  2597. return motions.moveToFirstNonWhiteSpaceCharacter(cm, oldAnchor);
  2598. } else if (args.linewise){
  2599. return oldAnchor;
  2600. } else {
  2601. return cursorMin(ranges[0].anchor, ranges[0].head);
  2602. }
  2603. },
  2604. yank: function(cm, args, ranges, oldAnchor) {
  2605. var vim = cm.state.vim;
  2606. var text = cm.getSelection();
  2607. var endPos = vim.visualMode
  2608. ? cursorMin(vim.sel.anchor, vim.sel.head, ranges[0].head, ranges[0].anchor)
  2609. : oldAnchor;
  2610. vimGlobalState.registerController.pushText(
  2611. args.registerName, 'yank',
  2612. text, args.linewise, vim.visualBlock);
  2613. return endPos;
  2614. }
  2615. };
  2616. /** @arg {string} name @arg {import("./types").OperatorFn} fn */
  2617. function defineOperator(name, fn) {
  2618. operators[name] = fn;
  2619. }
  2620. /** @type {import("./types").vimActions} */
  2621. var actions = {
  2622. jumpListWalk: function(cm, actionArgs, vim) {
  2623. if (vim.visualMode) {
  2624. return;
  2625. }
  2626. var repeat = actionArgs.repeat || 1;
  2627. var forward = actionArgs.forward;
  2628. var jumpList = vimGlobalState.jumpList;
  2629. var mark = jumpList.move(cm, forward ? repeat : -repeat);
  2630. var markPos = mark ? mark.find() : undefined;
  2631. markPos = markPos ? markPos : cm.getCursor();
  2632. cm.setCursor(markPos);
  2633. },
  2634. scroll: function(cm, actionArgs, vim) {
  2635. if (vim.visualMode) {
  2636. return;
  2637. }
  2638. var repeat = actionArgs.repeat || 1;
  2639. var lineHeight = cm.defaultTextHeight();
  2640. var top = cm.getScrollInfo().top;
  2641. var delta = lineHeight * repeat;
  2642. var newPos = actionArgs.forward ? top + delta : top - delta;
  2643. var cursor = copyCursor(cm.getCursor());
  2644. var cursorCoords = cm.charCoords(cursor, 'local');
  2645. if (actionArgs.forward) {
  2646. if (newPos > cursorCoords.top) {
  2647. cursor.line += (newPos - cursorCoords.top) / lineHeight;
  2648. cursor.line = Math.ceil(cursor.line);
  2649. cm.setCursor(cursor);
  2650. cursorCoords = cm.charCoords(cursor, 'local');
  2651. cm.scrollTo(null, cursorCoords.top);
  2652. } else {
  2653. // Cursor stays within bounds. Just reposition the scroll window.
  2654. cm.scrollTo(null, newPos);
  2655. }
  2656. } else {
  2657. var newBottom = newPos + cm.getScrollInfo().clientHeight;
  2658. if (newBottom < cursorCoords.bottom) {
  2659. cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight;
  2660. cursor.line = Math.floor(cursor.line);
  2661. cm.setCursor(cursor);
  2662. cursorCoords = cm.charCoords(cursor, 'local');
  2663. cm.scrollTo(
  2664. null, cursorCoords.bottom - cm.getScrollInfo().clientHeight);
  2665. } else {
  2666. // Cursor stays within bounds. Just reposition the scroll window.
  2667. cm.scrollTo(null, newPos);
  2668. }
  2669. }
  2670. },
  2671. scrollToCursor: function(cm, actionArgs) {
  2672. var lineNum = cm.getCursor().line;
  2673. var charCoords = cm.charCoords(new Pos(lineNum, 0), 'local');
  2674. var height = cm.getScrollInfo().clientHeight;
  2675. var y = charCoords.top;
  2676. switch (actionArgs.position) {
  2677. case 'center': y = charCoords.bottom - height / 2;
  2678. break;
  2679. case 'bottom':
  2680. var lineLastCharPos = new Pos(lineNum, cm.getLine(lineNum).length - 1);
  2681. var lineLastCharCoords = cm.charCoords(lineLastCharPos, 'local');
  2682. var lineHeight = lineLastCharCoords.bottom - y;
  2683. y = y - height + lineHeight
  2684. break;
  2685. }
  2686. cm.scrollTo(null, y);
  2687. },
  2688. replayMacro: function(cm, actionArgs, vim) {
  2689. var registerName = actionArgs.selectedCharacter || "";
  2690. var repeat = actionArgs.repeat || 1;
  2691. var macroModeState = vimGlobalState.macroModeState;
  2692. if (registerName == '@') {
  2693. registerName = macroModeState.latestRegister;
  2694. } else {
  2695. macroModeState.latestRegister = registerName;
  2696. }
  2697. while(repeat--){
  2698. executeMacroRegister(cm, vim, macroModeState, registerName);
  2699. }
  2700. },
  2701. enterMacroRecordMode: function(cm, actionArgs) {
  2702. var macroModeState = vimGlobalState.macroModeState;
  2703. var registerName = actionArgs.selectedCharacter;
  2704. if (vimGlobalState.registerController.isValidRegister(registerName)) {
  2705. macroModeState.enterMacroRecordMode(cm, registerName);
  2706. }
  2707. },
  2708. toggleOverwrite: function(cm) {
  2709. if (!cm.state.overwrite) {
  2710. cm.toggleOverwrite(true);
  2711. cm.setOption('keyMap', 'vim-replace');
  2712. CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
  2713. } else {
  2714. cm.toggleOverwrite(false);
  2715. cm.setOption('keyMap', 'vim-insert');
  2716. CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
  2717. }
  2718. },
  2719. enterInsertMode: function(cm, actionArgs, vim) {
  2720. if (cm.getOption('readOnly')) { return; }
  2721. vim.insertMode = true;
  2722. vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1;
  2723. var insertAt = (actionArgs) ? actionArgs.insertAt : null;
  2724. var sel = vim.sel;
  2725. var head = actionArgs.head || cm.getCursor('head');
  2726. var height = cm.listSelections().length;
  2727. if (insertAt == 'eol') {
  2728. head = new Pos(head.line, lineLength(cm, head.line));
  2729. } else if (insertAt == 'bol') {
  2730. head = new Pos(head.line, 0);
  2731. } else if (insertAt == 'charAfter') {
  2732. var newPosition = updateSelectionForSurrogateCharacters(cm, head, offsetCursor(head, 0, 1));
  2733. head = newPosition.end;
  2734. } else if (insertAt == 'firstNonBlank') {
  2735. var newPosition = updateSelectionForSurrogateCharacters(cm, head, motions.moveToFirstNonWhiteSpaceCharacter(cm, head));
  2736. head = newPosition.end;
  2737. } else if (insertAt == 'startOfSelectedArea') {
  2738. if (!vim.visualMode)
  2739. return;
  2740. if (!vim.visualBlock) {
  2741. if (sel.head.line < sel.anchor.line) {
  2742. head = sel.head;
  2743. } else {
  2744. head = new Pos(sel.anchor.line, 0);
  2745. }
  2746. } else {
  2747. head = new Pos(
  2748. Math.min(sel.head.line, sel.anchor.line),
  2749. Math.min(sel.head.ch, sel.anchor.ch));
  2750. height = Math.abs(sel.head.line - sel.anchor.line) + 1;
  2751. }
  2752. } else if (insertAt == 'endOfSelectedArea') {
  2753. if (!vim.visualMode)
  2754. return;
  2755. if (!vim.visualBlock) {
  2756. if (sel.head.line >= sel.anchor.line) {
  2757. head = offsetCursor(sel.head, 0, 1);
  2758. } else {
  2759. head = new Pos(sel.anchor.line, 0);
  2760. }
  2761. } else {
  2762. head = new Pos(
  2763. Math.min(sel.head.line, sel.anchor.line),
  2764. Math.max(sel.head.ch, sel.anchor.ch) + 1);
  2765. height = Math.abs(sel.head.line - sel.anchor.line) + 1;
  2766. }
  2767. } else if (insertAt == 'inplace') {
  2768. if (vim.visualMode){
  2769. return;
  2770. }
  2771. } else if (insertAt == 'lastEdit') {
  2772. head = getLastEditPos(cm) || head;
  2773. }
  2774. cm.setOption('disableInput', false);
  2775. if (actionArgs && actionArgs.replace) {
  2776. // Handle Replace-mode as a special case of insert mode.
  2777. cm.toggleOverwrite(true);
  2778. cm.setOption('keyMap', 'vim-replace');
  2779. CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
  2780. } else {
  2781. cm.toggleOverwrite(false);
  2782. cm.setOption('keyMap', 'vim-insert');
  2783. CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
  2784. }
  2785. if (!vimGlobalState.macroModeState.isPlaying) {
  2786. // Only record if not replaying.
  2787. cm.on('change', onChange);
  2788. if (vim.insertEnd) vim.insertEnd.clear();
  2789. vim.insertEnd = cm.setBookmark(head, {insertLeft: true});
  2790. CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
  2791. }
  2792. if (vim.visualMode) {
  2793. exitVisualMode(cm);
  2794. }
  2795. selectForInsert(cm, head, height);
  2796. },
  2797. toggleVisualMode: function(cm, actionArgs, vim) {
  2798. var repeat = actionArgs.repeat;
  2799. var anchor = cm.getCursor();
  2800. var head;
  2801. // TODO: The repeat should actually select number of characters/lines
  2802. // equal to the repeat times the size of the previous visual
  2803. // operation.
  2804. if (!vim.visualMode) {
  2805. // Entering visual mode
  2806. vim.visualMode = true;
  2807. vim.visualLine = !!actionArgs.linewise;
  2808. vim.visualBlock = !!actionArgs.blockwise;
  2809. head = clipCursorToContent(
  2810. cm, new Pos(anchor.line, anchor.ch + repeat - 1));
  2811. var newPosition = updateSelectionForSurrogateCharacters(cm, anchor, head)
  2812. vim.sel = {
  2813. anchor: newPosition.start,
  2814. head: newPosition.end
  2815. };
  2816. CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
  2817. updateCmSelection(cm);
  2818. updateMark(cm, vim, '<', cursorMin(anchor, head));
  2819. updateMark(cm, vim, '>', cursorMax(anchor, head));
  2820. } else if (vim.visualLine != !!actionArgs.linewise ||
  2821. vim.visualBlock != !!actionArgs.blockwise) {
  2822. // Toggling between modes
  2823. vim.visualLine = !!actionArgs.linewise;
  2824. vim.visualBlock = !!actionArgs.blockwise;
  2825. CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
  2826. updateCmSelection(cm);
  2827. } else {
  2828. exitVisualMode(cm);
  2829. }
  2830. },
  2831. reselectLastSelection: function(cm, _actionArgs, vim) {
  2832. var lastSelection = vim.lastSelection;
  2833. if (vim.visualMode) {
  2834. updateLastSelection(cm, vim);
  2835. }
  2836. if (lastSelection) {
  2837. var anchor = lastSelection.anchorMark.find();
  2838. var head = lastSelection.headMark.find();
  2839. if (!anchor || !head) {
  2840. // If the marks have been destroyed due to edits, do nothing.
  2841. return;
  2842. }
  2843. vim.sel = {
  2844. anchor: anchor,
  2845. head: head
  2846. };
  2847. vim.visualMode = true;
  2848. vim.visualLine = lastSelection.visualLine;
  2849. vim.visualBlock = lastSelection.visualBlock;
  2850. updateCmSelection(cm);
  2851. updateMark(cm, vim, '<', cursorMin(anchor, head));
  2852. updateMark(cm, vim, '>', cursorMax(anchor, head));
  2853. CodeMirror.signal(cm, 'vim-mode-change', {
  2854. mode: 'visual',
  2855. subMode: vim.visualLine ? 'linewise' :
  2856. vim.visualBlock ? 'blockwise' : ''});
  2857. }
  2858. },
  2859. joinLines: function(cm, actionArgs, vim) {
  2860. var curStart, curEnd;
  2861. if (vim.visualMode) {
  2862. curStart = cm.getCursor('anchor');
  2863. curEnd = cm.getCursor('head');
  2864. if (cursorIsBefore(curEnd, curStart)) {
  2865. var tmp = curEnd;
  2866. curEnd = curStart;
  2867. curStart = tmp;
  2868. }
  2869. curEnd.ch = lineLength(cm, curEnd.line) - 1;
  2870. } else {
  2871. // Repeat is the number of lines to join. Minimum 2 lines.
  2872. var repeat = Math.max(actionArgs.repeat, 2);
  2873. curStart = cm.getCursor();
  2874. curEnd = clipCursorToContent(cm, new Pos(curStart.line + repeat - 1,
  2875. Infinity));
  2876. }
  2877. var finalCh = 0;
  2878. for (var i = curStart.line; i < curEnd.line; i++) {
  2879. finalCh = lineLength(cm, curStart.line);
  2880. var text = '';
  2881. var nextStartCh = 0;
  2882. if (!actionArgs.keepSpaces) {
  2883. var nextLine = cm.getLine(curStart.line + 1);
  2884. nextStartCh = nextLine.search(/\S/);
  2885. if (nextStartCh == -1) {
  2886. nextStartCh = nextLine.length;
  2887. } else {
  2888. text = " ";
  2889. }
  2890. }
  2891. cm.replaceRange(text,
  2892. new Pos(curStart.line, finalCh),
  2893. new Pos(curStart.line + 1, nextStartCh));
  2894. }
  2895. var curFinalPos = clipCursorToContent(cm, new Pos(curStart.line, finalCh));
  2896. if (vim.visualMode) {
  2897. exitVisualMode(cm, false);
  2898. }
  2899. cm.setCursor(curFinalPos);
  2900. },
  2901. newLineAndEnterInsertMode: function(cm, actionArgs, vim) {
  2902. vim.insertMode = true;
  2903. var insertAt = copyCursor(cm.getCursor());
  2904. if (insertAt.line === cm.firstLine() && !actionArgs.after) {
  2905. // Special case for inserting newline before start of document.
  2906. cm.replaceRange('\n', new Pos(cm.firstLine(), 0));
  2907. cm.setCursor(cm.firstLine(), 0);
  2908. } else {
  2909. insertAt.line = (actionArgs.after) ? insertAt.line :
  2910. insertAt.line - 1;
  2911. insertAt.ch = lineLength(cm, insertAt.line);
  2912. cm.setCursor(insertAt);
  2913. var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||
  2914. CodeMirror.commands.newlineAndIndent;
  2915. newlineFn(cm);
  2916. }
  2917. this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim);
  2918. },
  2919. paste: function(cm, actionArgs, vim) {
  2920. var register = vimGlobalState.registerController.getRegister(
  2921. actionArgs.registerName);
  2922. if (actionArgs.registerName === '+') {
  2923. navigator.clipboard.readText().then((value) => {
  2924. this.continuePaste(cm, actionArgs, vim, value, register);
  2925. })
  2926. } else {
  2927. var text = register.toString();
  2928. this.continuePaste(cm, actionArgs, vim, text, register);
  2929. }
  2930. },
  2931. continuePaste: function(cm, actionArgs, vim, text, register) {
  2932. var cur = copyCursor(cm.getCursor());
  2933. if (!text) {
  2934. return;
  2935. }
  2936. if (actionArgs.matchIndent) {
  2937. var tabSize = cm.getOption("tabSize");
  2938. // length that considers tabs and tabSize
  2939. var whitespaceLength = function(/** @type {string} */ str) {
  2940. var tabs = (str.split("\t").length - 1);
  2941. var spaces = (str.split(" ").length - 1);
  2942. return tabs * tabSize + spaces * 1;
  2943. };
  2944. var currentLine = cm.getLine(cm.getCursor().line);
  2945. // @ts-ignore
  2946. var indent = whitespaceLength(currentLine.match(/^\s*/)[0]);
  2947. // chomp last newline b/c don't want it to match /^\s*/gm
  2948. var chompedText = text.replace(/\n$/, '');
  2949. var wasChomped = text !== chompedText;
  2950. // @ts-ignore
  2951. var firstIndent = whitespaceLength(text.match(/^\s*/)[0]);
  2952. var text = chompedText.replace(/^\s*/gm, function(wspace) {
  2953. var newIndent = indent + (whitespaceLength(wspace) - firstIndent);
  2954. if (newIndent < 0) {
  2955. return "";
  2956. }
  2957. else if (cm.getOption("indentWithTabs")) {
  2958. var quotient = Math.floor(newIndent / tabSize);
  2959. return Array(quotient + 1).join('\t');
  2960. }
  2961. else {
  2962. return Array(newIndent + 1).join(' ');
  2963. }
  2964. });
  2965. text += wasChomped ? "\n" : "";
  2966. }
  2967. if (actionArgs.repeat > 1) {
  2968. var text = Array(actionArgs.repeat + 1).join(text);
  2969. }
  2970. var linewise = register.linewise;
  2971. var blockwise = register.blockwise;
  2972. if (blockwise) {
  2973. // @ts-ignore
  2974. text = text.split('\n');
  2975. if (linewise) {
  2976. // @ts-ignore
  2977. text.pop();
  2978. }
  2979. for (var i = 0; i < text.length; i++) {
  2980. // @ts-ignore
  2981. text[i] = (text[i] == '') ? ' ' : text[i];
  2982. }
  2983. cur.ch += actionArgs.after ? 1 : 0;
  2984. cur.ch = Math.min(lineLength(cm, cur.line), cur.ch);
  2985. } else if (linewise) {
  2986. if(vim.visualMode) {
  2987. text = vim.visualLine ? text.slice(0, -1) : '\n' + text.slice(0, text.length - 1) + '\n';
  2988. } else if (actionArgs.after) {
  2989. // Move the newline at the end to the start instead, and paste just
  2990. // before the newline character of the line we are on right now.
  2991. text = '\n' + text.slice(0, text.length - 1);
  2992. cur.ch = lineLength(cm, cur.line);
  2993. } else {
  2994. cur.ch = 0;
  2995. }
  2996. } else {
  2997. cur.ch += actionArgs.after ? 1 : 0;
  2998. }
  2999. var curPosFinal;
  3000. if (vim.visualMode) {
  3001. // save the pasted text for reselection if the need arises
  3002. vim.lastPastedText = text;
  3003. var lastSelectionCurEnd;
  3004. var selectedArea = getSelectedAreaRange(cm, vim);
  3005. var selectionStart = selectedArea[0];
  3006. var selectionEnd = selectedArea[1];
  3007. var selectedText = cm.getSelection();
  3008. var selections = cm.listSelections();
  3009. var emptyStrings = new Array(selections.length).join('1').split('1');
  3010. // save the curEnd marker before it get cleared due to cm.replaceRange.
  3011. if (vim.lastSelection) {
  3012. lastSelectionCurEnd = vim.lastSelection.headMark.find();
  3013. }
  3014. // push the previously selected text to unnamed register
  3015. vimGlobalState.registerController.unnamedRegister.setText(selectedText);
  3016. if (blockwise) {
  3017. // first delete the selected text
  3018. cm.replaceSelections(emptyStrings);
  3019. // Set new selections as per the block length of the yanked text
  3020. selectionEnd = new Pos(selectionStart.line + text.length-1, selectionStart.ch);
  3021. cm.setCursor(selectionStart);
  3022. selectBlock(cm, selectionEnd);
  3023. // @ts-ignore
  3024. cm.replaceSelections(text);
  3025. curPosFinal = selectionStart;
  3026. } else if (vim.visualBlock) {
  3027. cm.replaceSelections(emptyStrings);
  3028. cm.setCursor(selectionStart);
  3029. cm.replaceRange(text, selectionStart, selectionStart);
  3030. curPosFinal = selectionStart;
  3031. } else {
  3032. cm.replaceRange(text, selectionStart, selectionEnd);
  3033. curPosFinal = cm.posFromIndex(cm.indexFromPos(selectionStart) + text.length - 1);
  3034. }
  3035. // restore the curEnd marker
  3036. if(lastSelectionCurEnd) {
  3037. vim.lastSelection.headMark = cm.setBookmark(lastSelectionCurEnd);
  3038. }
  3039. if (linewise) {
  3040. curPosFinal.ch=0;
  3041. }
  3042. } else {
  3043. if (blockwise) {
  3044. cm.setCursor(cur);
  3045. for (var i = 0; i < text.length; i++) {
  3046. var line = cur.line+i;
  3047. if (line > cm.lastLine()) {
  3048. cm.replaceRange('\n', new Pos(line, 0));
  3049. }
  3050. var lastCh = lineLength(cm, line);
  3051. if (lastCh < cur.ch) {
  3052. extendLineToColumn(cm, line, cur.ch);
  3053. }
  3054. }
  3055. cm.setCursor(cur);
  3056. selectBlock(cm, new Pos(cur.line + text.length-1, cur.ch));
  3057. // @ts-ignore
  3058. cm.replaceSelections(text);
  3059. curPosFinal = cur;
  3060. } else {
  3061. cm.replaceRange(text, cur);
  3062. // Now fine tune the cursor to where we want it.
  3063. if (linewise) {
  3064. var line = actionArgs.after ? cur.line + 1 : cur.line;
  3065. curPosFinal = new Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
  3066. } else {
  3067. curPosFinal = copyCursor(cur);
  3068. if (!/\n/.test(text)) {
  3069. curPosFinal.ch += text.length - (actionArgs.after ? 1 : 0);
  3070. }
  3071. }
  3072. }
  3073. }
  3074. if (vim.visualMode) {
  3075. exitVisualMode(cm, false);
  3076. }
  3077. cm.setCursor(curPosFinal);
  3078. },
  3079. undo: function(cm, actionArgs) {
  3080. cm.operation(function() {
  3081. repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();
  3082. cm.setCursor(clipCursorToContent(cm, cm.getCursor('start')));
  3083. });
  3084. },
  3085. redo: function(cm, actionArgs) {
  3086. repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();
  3087. },
  3088. setRegister: function(_cm, actionArgs, vim) {
  3089. vim.inputState.registerName = actionArgs.selectedCharacter;
  3090. },
  3091. insertRegister: function(cm, actionArgs, vim) {
  3092. var registerName = actionArgs.selectedCharacter;
  3093. var register = vimGlobalState.registerController.getRegister(registerName);
  3094. var text = register && register.toString();
  3095. if (text) {
  3096. cm.replaceSelection(text);
  3097. }
  3098. },
  3099. oneNormalCommand: function(cm, actionArgs, vim) {
  3100. exitInsertMode(cm, true);
  3101. vim.insertModeReturn = true;
  3102. CodeMirror.on(cm, 'vim-command-done', function handler() {
  3103. if (vim.visualMode) return;
  3104. if (vim.insertModeReturn) {
  3105. vim.insertModeReturn = false;
  3106. if (!vim.insertMode) {
  3107. actions.enterInsertMode(cm, {}, vim);
  3108. }
  3109. }
  3110. CodeMirror.off(cm, 'vim-command-done', handler);
  3111. });
  3112. },
  3113. setMark: function(cm, actionArgs, vim) {
  3114. var markName = actionArgs.selectedCharacter;
  3115. if (markName) updateMark(cm, vim, markName, cm.getCursor());
  3116. },
  3117. replace: function(cm, actionArgs, vim) {
  3118. var replaceWith = actionArgs.selectedCharacter || "";
  3119. var curStart = cm.getCursor();
  3120. var replaceTo;
  3121. var curEnd;
  3122. var selections = cm.listSelections();
  3123. if (vim.visualMode) {
  3124. curStart = cm.getCursor('start');
  3125. curEnd = cm.getCursor('end');
  3126. } else {
  3127. var line = cm.getLine(curStart.line);
  3128. replaceTo = curStart.ch + actionArgs.repeat;
  3129. if (replaceTo > line.length) {
  3130. replaceTo=line.length;
  3131. }
  3132. curEnd = new Pos(curStart.line, replaceTo);
  3133. }
  3134. var newPositions = updateSelectionForSurrogateCharacters(cm, curStart, curEnd);
  3135. curStart = newPositions.start;
  3136. curEnd = newPositions.end;
  3137. if (replaceWith=='\n') {
  3138. if (!vim.visualMode) cm.replaceRange('', curStart, curEnd);
  3139. // special case, where vim help says to replace by just one line-break
  3140. (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm);
  3141. } else {
  3142. var replaceWithStr = cm.getRange(curStart, curEnd);
  3143. // replace all surrogate characters with selected character
  3144. replaceWithStr = replaceWithStr.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, replaceWith);
  3145. //replace all characters in range by selected, but keep linebreaks
  3146. replaceWithStr = replaceWithStr.replace(/[^\n]/g, replaceWith);
  3147. if (vim.visualBlock) {
  3148. // Tabs are split in visua block before replacing
  3149. var spaces = new Array(cm.getOption("tabSize")+1).join(' ');
  3150. replaceWithStr = cm.getSelection();
  3151. replaceWithStr = replaceWithStr.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, replaceWith);
  3152. var replaceWithStrings = replaceWithStr.replace(/\t/g, spaces).replace(/[^\n]/g, replaceWith).split('\n');
  3153. cm.replaceSelections(replaceWithStrings);
  3154. } else {
  3155. cm.replaceRange(replaceWithStr, curStart, curEnd);
  3156. }
  3157. if (vim.visualMode) {
  3158. curStart = cursorIsBefore(selections[0].anchor, selections[0].head) ?
  3159. selections[0].anchor : selections[0].head;
  3160. cm.setCursor(curStart);
  3161. exitVisualMode(cm, false);
  3162. } else {
  3163. cm.setCursor(offsetCursor(curEnd, 0, -1));
  3164. }
  3165. }
  3166. },
  3167. incrementNumberToken: function(cm, actionArgs) {
  3168. var cur = cm.getCursor();
  3169. var lineStr = cm.getLine(cur.line);
  3170. var re = /(-?)(?:(0x)([\da-f]+)|(0b|0|)(\d+))/gi;
  3171. var match;
  3172. var start;
  3173. var end;
  3174. var numberStr;
  3175. while ((match = re.exec(lineStr)) !== null) {
  3176. start = match.index;
  3177. end = start + match[0].length;
  3178. if (cur.ch < end)break;
  3179. }
  3180. // @ts-ignore
  3181. if (!actionArgs.backtrack && (end <= cur.ch))return;
  3182. if (match) {
  3183. var baseStr = match[2] || match[4]
  3184. var digits = match[3] || match[5]
  3185. var increment = actionArgs.increase ? 1 : -1;
  3186. var base = {'0b': 2, '0': 8, '': 10, '0x': 16}[baseStr.toLowerCase()];
  3187. var number = parseInt(match[1] + digits, base) + (increment * actionArgs.repeat);
  3188. numberStr = number.toString(base);
  3189. var zeroPadding = baseStr ? new Array(digits.length - numberStr.length + 1 + match[1].length).join('0') : ''
  3190. if (numberStr.charAt(0) === '-') {
  3191. numberStr = '-' + baseStr + zeroPadding + numberStr.substr(1);
  3192. } else {
  3193. numberStr = baseStr + zeroPadding + numberStr;
  3194. }
  3195. // @ts-ignore
  3196. var from = new Pos(cur.line, start);
  3197. // @ts-ignore
  3198. var to = new Pos(cur.line, end);
  3199. cm.replaceRange(numberStr, from, to);
  3200. } else {
  3201. return;
  3202. }
  3203. // @ts-ignore
  3204. cm.setCursor(new Pos(cur.line, start + numberStr.length - 1));
  3205. },
  3206. repeatLastEdit: function(cm, actionArgs, vim) {
  3207. var lastEditInputState = vim.lastEditInputState;
  3208. if (!lastEditInputState) { return; }
  3209. var repeat = actionArgs.repeat;
  3210. if (repeat && actionArgs.repeatIsExplicit) {
  3211. lastEditInputState.repeatOverride = repeat;
  3212. } else {
  3213. repeat = lastEditInputState.repeatOverride || repeat;
  3214. }
  3215. repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);
  3216. },
  3217. indent: function(cm, actionArgs) {
  3218. cm.indentLine(cm.getCursor().line, actionArgs.indentRight);
  3219. },
  3220. exitInsertMode: function(cm, actionArgs) {
  3221. exitInsertMode(cm);
  3222. }
  3223. };
  3224. /** @arg {string } name @arg {import("./types").ActionFn} fn */
  3225. function defineAction(name, fn) {
  3226. actions[name] = fn;
  3227. }
  3228. /*
  3229. * Below are miscellaneous utility functions used by vim.js
  3230. */
  3231. /**
  3232. * Clips cursor to ensure that line is within the buffer's range
  3233. * and is not inside surrogate pair
  3234. * If includeLineBreak is true, then allow cur.ch == lineLength.
  3235. * @arg {CodeMirrorV} cm
  3236. * @arg {Pos} cur
  3237. * @arg {Pos} [oldCur]
  3238. * @return {Pos}
  3239. */
  3240. function clipCursorToContent(cm, cur, oldCur) {
  3241. var vim = cm.state.vim;
  3242. var includeLineBreak = vim.insertMode || vim.visualMode;
  3243. var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() );
  3244. var text = cm.getLine(line);
  3245. var maxCh = text.length - 1 + Number(!!includeLineBreak);
  3246. var ch = Math.min(Math.max(0, cur.ch), maxCh);
  3247. // prevent cursor from entering surrogate pair
  3248. var charCode = text.charCodeAt(ch);
  3249. if (0xDC00 <= charCode && charCode <= 0xDFFF) {
  3250. var direction = 1;
  3251. if (oldCur && oldCur.line == line && oldCur.ch > ch) {
  3252. direction = -1;
  3253. }
  3254. ch +=direction;
  3255. if (ch > maxCh) ch -=2;
  3256. }
  3257. return new Pos(line, ch);
  3258. }
  3259. function copyArgs(args) {
  3260. var ret = {};
  3261. for (var prop in args) {
  3262. if (args.hasOwnProperty(prop)) {
  3263. ret[prop] = args[prop];
  3264. }
  3265. }
  3266. return ret;
  3267. }
  3268. function offsetCursor(cur, offsetLine, offsetCh) {
  3269. if (typeof offsetLine === 'object') {
  3270. offsetCh = offsetLine.ch;
  3271. offsetLine = offsetLine.line;
  3272. }
  3273. return new Pos(cur.line + offsetLine, cur.ch + offsetCh);
  3274. }
  3275. function commandMatches(keys, keyMap, context, inputState) {
  3276. // Partial matches are not applied. They inform the key handler
  3277. // that the current key sequence is a subsequence of a valid key
  3278. // sequence, so that the key buffer is not cleared.
  3279. if (inputState.operator) context = "operatorPending";
  3280. var match, partial = [], full = [];
  3281. // if currently expanded key comes from a noremap, searcg only in default keys
  3282. var startIndex = noremap ? keyMap.length - defaultKeymapLength : 0;
  3283. for (var i = startIndex; i < keyMap.length; i++) {
  3284. var command = keyMap[i];
  3285. if (context == 'insert' && command.context != 'insert' ||
  3286. (command.context && command.context != context) ||
  3287. inputState.operator && command.type == 'action' ||
  3288. !(match = commandMatch(keys, command.keys))) { continue; }
  3289. if (match == 'partial') { partial.push(command); }
  3290. if (match == 'full') { full.push(command); }
  3291. }
  3292. return {
  3293. partial: partial.length && partial,
  3294. full: full.length && full
  3295. };
  3296. }
  3297. /** @arg {string} pressed @arg {string} mapped @return {'full'|'partial'|false}*/
  3298. function commandMatch(pressed, mapped) {
  3299. const isLastCharacter = mapped.slice(-11) == '<character>';
  3300. const isLastRegister = mapped.slice(-10) == '<register>';
  3301. if (isLastCharacter || isLastRegister) {
  3302. // Last character matches anything.
  3303. var prefixLen = mapped.length - (isLastCharacter ? 11 : 10);
  3304. var pressedPrefix = pressed.slice(0, prefixLen);
  3305. var mappedPrefix = mapped.slice(0, prefixLen);
  3306. return pressedPrefix == mappedPrefix && pressed.length > prefixLen ? 'full' :
  3307. mappedPrefix.indexOf(pressedPrefix) == 0 ? 'partial' : false;
  3308. } else {
  3309. return pressed == mapped ? 'full' :
  3310. mapped.indexOf(pressed) == 0 ? 'partial' : false;
  3311. }
  3312. }
  3313. /** @arg {string} keys */
  3314. function lastChar(keys) {
  3315. var match = /^.*(<[^>]+>)$/.exec(keys);
  3316. var selectedCharacter = match ? match[1] : keys.slice(-1);
  3317. if (selectedCharacter.length > 1){
  3318. switch(selectedCharacter){
  3319. case '<CR>':
  3320. selectedCharacter='\n';
  3321. break;
  3322. case '<Space>':
  3323. selectedCharacter=' ';
  3324. break;
  3325. default:
  3326. selectedCharacter='';
  3327. break;
  3328. }
  3329. }
  3330. return selectedCharacter;
  3331. }
  3332. /** @arg {CodeMirror} cm @arg {{ (cm: CodeMirror): void }} fn @arg {number} repeat */
  3333. function repeatFn(cm, fn, repeat) {
  3334. return function() {
  3335. for (var i = 0; i < repeat; i++) {
  3336. fn(cm);
  3337. }
  3338. };
  3339. }
  3340. /** @arg {Pos} cur @return {Pos}*/
  3341. function copyCursor(cur) {
  3342. return new Pos(cur.line, cur.ch);
  3343. }
  3344. /** @arg {Pos} cur1 @arg {Pos} cur2 @return {boolean} */
  3345. function cursorEqual(cur1, cur2) {
  3346. return cur1.ch == cur2.ch && cur1.line == cur2.line;
  3347. }
  3348. /** @arg {Pos} cur1 @arg {Pos} cur2 @return {boolean}*/
  3349. function cursorIsBefore(cur1, cur2) {
  3350. if (cur1.line < cur2.line) {
  3351. return true;
  3352. }
  3353. if (cur1.line == cur2.line && cur1.ch < cur2.ch) {
  3354. return true;
  3355. }
  3356. return false;
  3357. }
  3358. /** @arg {Pos} cur1 @arg {Pos} cur2 @return {Pos}*/
  3359. function cursorMin(cur1, cur2) {
  3360. if (arguments.length > 2) {
  3361. // @ts-ignore
  3362. cur2 = cursorMin.apply(undefined, Array.prototype.slice.call(arguments, 1));
  3363. }
  3364. return cursorIsBefore(cur1, cur2) ? cur1 : cur2;
  3365. }
  3366. /** @arg {Pos} cur1 @arg {Pos} cur2 @return {Pos} */
  3367. function cursorMax(cur1, cur2) {
  3368. if (arguments.length > 2) {
  3369. // @ts-ignore
  3370. cur2 = cursorMax.apply(undefined, Array.prototype.slice.call(arguments, 1));
  3371. }
  3372. return cursorIsBefore(cur1, cur2) ? cur2 : cur1;
  3373. }
  3374. /** @arg {Pos} cur1 @arg {Pos} cur2 @arg {Pos} cur3 @return {boolean}*/
  3375. function cursorIsBetween(cur1, cur2, cur3) {
  3376. // returns true if cur2 is between cur1 and cur3.
  3377. var cur1before2 = cursorIsBefore(cur1, cur2);
  3378. var cur2before3 = cursorIsBefore(cur2, cur3);
  3379. return cur1before2 && cur2before3;
  3380. }
  3381. /** @arg {CodeMirror} cm @arg {number} lineNum */
  3382. function lineLength(cm, lineNum) {
  3383. return cm.getLine(lineNum).length;
  3384. }
  3385. /** @arg {string} s */
  3386. function trim(s) {
  3387. if (s.trim) {
  3388. return s.trim();
  3389. }
  3390. return s.replace(/^\s+|\s+$/g, '');
  3391. }
  3392. /** @arg {string} s */
  3393. function escapeRegex(s) {
  3394. return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1');
  3395. }
  3396. /** @arg {CodeMirror} cm @arg {number} lineNum @arg {number} column */
  3397. function extendLineToColumn(cm, lineNum, column) {
  3398. var endCh = lineLength(cm, lineNum);
  3399. var spaces = new Array(column-endCh+1).join(' ');
  3400. cm.setCursor(new Pos(lineNum, endCh));
  3401. cm.replaceRange(spaces, cm.getCursor());
  3402. }
  3403. // This functions selects a rectangular block
  3404. // of text with selectionEnd as any of its corner
  3405. // Height of block:
  3406. // Difference in selectionEnd.line and first/last selection.line
  3407. // Width of the block:
  3408. // Distance between selectionEnd.ch and any(first considered here) selection.ch
  3409. /** @arg {CodeMirror} cm @arg {Pos} selectionEnd */
  3410. function selectBlock(cm, selectionEnd) {
  3411. var selections = [], ranges = cm.listSelections();
  3412. var head = copyCursor(cm.clipPos(selectionEnd));
  3413. var isClipped = !cursorEqual(selectionEnd, head);
  3414. var curHead = cm.getCursor('head');
  3415. var primIndex = getIndex(ranges, curHead);
  3416. var wasClipped = cursorEqual(ranges[primIndex].head, ranges[primIndex].anchor);
  3417. var max = ranges.length - 1;
  3418. var index = max - primIndex > primIndex ? max : 0;
  3419. var base = ranges[index].anchor;
  3420. var firstLine = Math.min(base.line, head.line);
  3421. var lastLine = Math.max(base.line, head.line);
  3422. var baseCh = base.ch, headCh = head.ch;
  3423. var dir = ranges[index].head.ch - baseCh;
  3424. var newDir = headCh - baseCh;
  3425. if (dir > 0 && newDir <= 0) {
  3426. baseCh++;
  3427. if (!isClipped) { headCh--; }
  3428. } else if (dir < 0 && newDir >= 0) {
  3429. baseCh--;
  3430. if (!wasClipped) { headCh++; }
  3431. } else if (dir < 0 && newDir == -1) {
  3432. baseCh--;
  3433. headCh++;
  3434. }
  3435. for (var line = firstLine; line <= lastLine; line++) {
  3436. var range = {anchor: new Pos(line, baseCh), head: new Pos(line, headCh)};
  3437. selections.push(range);
  3438. }
  3439. cm.setSelections(selections);
  3440. selectionEnd.ch = headCh;
  3441. base.ch = baseCh;
  3442. return base;
  3443. }
  3444. /** @arg {CodeMirror} cm @arg {any} head @arg {number} height */
  3445. function selectForInsert(cm, head, height) {
  3446. var sel = [];
  3447. for (var i = 0; i < height; i++) {
  3448. var lineHead = offsetCursor(head, i, 0);
  3449. sel.push({anchor: lineHead, head: lineHead});
  3450. }
  3451. cm.setSelections(sel, 0);
  3452. }
  3453. // getIndex returns the index of the cursor in the selections.
  3454. /** @arg {string | any[]} ranges @arg {any} cursor @arg {string | undefined} [end] */
  3455. function getIndex(ranges, cursor, end) {
  3456. for (var i = 0; i < ranges.length; i++) {
  3457. var atAnchor = end != 'head' && cursorEqual(ranges[i].anchor, cursor);
  3458. var atHead = end != 'anchor' && cursorEqual(ranges[i].head, cursor);
  3459. if (atAnchor || atHead) {
  3460. return i;
  3461. }
  3462. }
  3463. return -1;
  3464. }
  3465. /** @arg {CodeMirror} cm @arg {vimState} vim */
  3466. function getSelectedAreaRange(cm, vim) {
  3467. var lastSelection = vim.lastSelection;
  3468. /** @return {[Pos,Pos]} */
  3469. var getCurrentSelectedAreaRange = function() {
  3470. var selections = cm.listSelections();
  3471. var start = selections[0];
  3472. var end = selections[selections.length-1];
  3473. var selectionStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head;
  3474. var selectionEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor;
  3475. return [selectionStart, selectionEnd];
  3476. };
  3477. var getLastSelectedAreaRange = function() {
  3478. var selectionStart = cm.getCursor();
  3479. var selectionEnd = cm.getCursor();
  3480. var block = lastSelection.visualBlock;
  3481. if (block) {
  3482. var width = block.width;
  3483. var height = block.height;
  3484. selectionEnd = new Pos(selectionStart.line + height, selectionStart.ch + width);
  3485. var selections = [];
  3486. // selectBlock creates a 'proper' rectangular block.
  3487. // We do not want that in all cases, so we manually set selections.
  3488. for (var i = selectionStart.line; i < selectionEnd.line; i++) {
  3489. var anchor = new Pos(i, selectionStart.ch);
  3490. var head = new Pos(i, selectionEnd.ch);
  3491. var range = {anchor: anchor, head: head};
  3492. selections.push(range);
  3493. }
  3494. cm.setSelections(selections);
  3495. } else {
  3496. var start = lastSelection.anchorMark.find();
  3497. var end = lastSelection.headMark.find();
  3498. var line = end.line - start.line;
  3499. var ch = end.ch - start.ch;
  3500. selectionEnd = {line: selectionEnd.line + line, ch: line ? selectionEnd.ch : ch + selectionEnd.ch};
  3501. if (lastSelection.visualLine) {
  3502. selectionStart = new Pos(selectionStart.line, 0);
  3503. selectionEnd = new Pos(selectionEnd.line, lineLength(cm, selectionEnd.line));
  3504. }
  3505. cm.setSelection(selectionStart, selectionEnd);
  3506. }
  3507. return [selectionStart, selectionEnd];
  3508. };
  3509. if (!vim.visualMode) {
  3510. // In case of replaying the action.
  3511. return getLastSelectedAreaRange();
  3512. } else {
  3513. return getCurrentSelectedAreaRange();
  3514. }
  3515. }
  3516. // Updates the previous selection with the current selection's values. This
  3517. // should only be called in visual mode.
  3518. /** @arg {CodeMirror} cm @arg {vimState} vim */
  3519. function updateLastSelection(cm, vim) {
  3520. var anchor = vim.sel.anchor;
  3521. var head = vim.sel.head;
  3522. // To accommodate the effect of lastPastedText in the last selection
  3523. if (vim.lastPastedText) {
  3524. head = cm.posFromIndex(cm.indexFromPos(anchor) + vim.lastPastedText.length);
  3525. vim.lastPastedText = null;
  3526. }
  3527. vim.lastSelection = {'anchorMark': cm.setBookmark(anchor),
  3528. 'headMark': cm.setBookmark(head),
  3529. 'anchor': copyCursor(anchor),
  3530. 'head': copyCursor(head),
  3531. 'visualMode': vim.visualMode,
  3532. 'visualLine': vim.visualLine,
  3533. 'visualBlock': vim.visualBlock};
  3534. }
  3535. /** @arg {CodeMirrorV} cm @arg {Pos} start @arg {Pos} end @returns {[Pos, Pos]} */
  3536. function expandSelection(cm, start, end, move) {
  3537. var sel = cm.state.vim.sel;
  3538. var head = move ? start: sel.head;
  3539. var anchor = move ? start: sel.anchor;
  3540. var tmp;
  3541. if (cursorIsBefore(end, start)) {
  3542. tmp = end;
  3543. end = start;
  3544. start = tmp;
  3545. }
  3546. if (cursorIsBefore(head, anchor)) {
  3547. head = cursorMin(start, head);
  3548. anchor = cursorMax(anchor, end);
  3549. } else {
  3550. anchor = cursorMin(start, anchor);
  3551. head = cursorMax(head, end);
  3552. head = offsetCursor(head, 0, -1);
  3553. if (head.ch == -1 && head.line != cm.firstLine()) {
  3554. head = new Pos(head.line - 1, lineLength(cm, head.line - 1));
  3555. }
  3556. }
  3557. return [anchor, head];
  3558. }
  3559. /**
  3560. * Updates the CodeMirror selection to match the provided vim selection.
  3561. * If no arguments are given, it uses the current vim selection state.
  3562. * @arg {CodeMirrorV} cm
  3563. * @arg {vimState["sel"]} [sel]
  3564. * @arg {"char"|"line"|"block" | undefined} [mode]
  3565. */
  3566. function updateCmSelection(cm, sel, mode) {
  3567. var vim = cm.state.vim;
  3568. sel = sel || vim.sel;
  3569. if (!mode) {
  3570. mode = vim.visualLine ? 'line' : vim.visualBlock ? 'block' : 'char';
  3571. }
  3572. var cmSel = makeCmSelection(cm, sel, mode);
  3573. cm.setSelections(cmSel.ranges, cmSel.primary);
  3574. }
  3575. /**
  3576. * @arg {CodeMirror} cm
  3577. * @arg {import("./types").CM5RangeInterface} sel
  3578. * @arg {"char"|"line"|"block"} mode
  3579. * @arg {boolean|undefined} [exclusive]
  3580. * @return {{ranges: any, primary: number}}
  3581. */
  3582. function makeCmSelection(cm, sel, mode, exclusive) {
  3583. var head = copyCursor(sel.head);
  3584. var anchor = copyCursor(sel.anchor);
  3585. if (mode == 'char') {
  3586. var headOffset = !exclusive && !cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
  3587. var anchorOffset = cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
  3588. head = offsetCursor(sel.head, 0, headOffset);
  3589. anchor = offsetCursor(sel.anchor, 0, anchorOffset);
  3590. return {
  3591. ranges: [{anchor: anchor, head: head}],
  3592. primary: 0
  3593. };
  3594. } else if (mode == 'line') {
  3595. if (!cursorIsBefore(sel.head, sel.anchor)) {
  3596. anchor.ch = 0;
  3597. var lastLine = cm.lastLine();
  3598. if (head.line > lastLine) {
  3599. head.line = lastLine;
  3600. }
  3601. head.ch = lineLength(cm, head.line);
  3602. } else {
  3603. head.ch = 0;
  3604. anchor.ch = lineLength(cm, anchor.line);
  3605. }
  3606. return {
  3607. ranges: [{anchor: anchor, head: head}],
  3608. primary: 0
  3609. };
  3610. } else if (mode == 'block') {
  3611. var top = Math.min(anchor.line, head.line),
  3612. fromCh = anchor.ch,
  3613. bottom = Math.max(anchor.line, head.line),
  3614. toCh = head.ch;
  3615. if (fromCh < toCh) { toCh += 1 }
  3616. else { fromCh += 1 };
  3617. var height = bottom - top + 1;
  3618. var primary = head.line == top ? 0 : height - 1;
  3619. var ranges = [];
  3620. for (var i = 0; i < height; i++) {
  3621. ranges.push({
  3622. anchor: new Pos(top + i, fromCh),
  3623. head: new Pos(top + i, toCh)
  3624. });
  3625. }
  3626. return {
  3627. ranges: ranges,
  3628. primary: primary
  3629. };
  3630. }
  3631. throw "never happens";
  3632. }
  3633. /** @arg {CodeMirror} cm */
  3634. function getHead(cm) {
  3635. var cur = cm.getCursor('head');
  3636. if (cm.getSelection().length == 1) {
  3637. // Small corner case when only 1 character is selected. The "real"
  3638. // head is the left of head and anchor.
  3639. cur = cursorMin(cur, cm.getCursor('anchor'));
  3640. }
  3641. return cur;
  3642. }
  3643. /**
  3644. * If moveHead is set to false, the CodeMirror selection will not be
  3645. * touched. The caller assumes the responsibility of putting the cursor
  3646. * in the right place.
  3647. * @arg {CodeMirrorV} cm
  3648. * @arg {boolean} [moveHead]
  3649. */
  3650. function exitVisualMode(cm, moveHead) {
  3651. var vim = cm.state.vim;
  3652. if (moveHead !== false) {
  3653. cm.setCursor(clipCursorToContent(cm, vim.sel.head));
  3654. }
  3655. updateLastSelection(cm, vim);
  3656. vim.visualMode = false;
  3657. vim.visualLine = false;
  3658. vim.visualBlock = false;
  3659. if (!vim.insertMode) CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
  3660. }
  3661. /**
  3662. * Remove any trailing newlines from the selection. For
  3663. * example, with the caret at the start of the last word on the line,
  3664. * 'dw' should word, but not the newline, while 'w' should advance the
  3665. * caret to the first character of the next line.
  3666. * @arg {CodeMirror} cm
  3667. * @arg {Pos} curStart
  3668. * @arg {Pos} curEnd
  3669. */
  3670. function clipToLine(cm, curStart, curEnd) {
  3671. var selection = cm.getRange(curStart, curEnd);
  3672. // Only clip if the selection ends with trailing newline + whitespace
  3673. if (/\n\s*$/.test(selection)) {
  3674. var lines = selection.split('\n');
  3675. // We know this is all whitespace.
  3676. lines.pop();
  3677. // Cases:
  3678. // 1. Last word is an empty line - do not clip the trailing '\n'
  3679. // 2. Last word is not an empty line - clip the trailing '\n'
  3680. // Find the line containing the last word, and clip all whitespace up
  3681. // to it.
  3682. for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {
  3683. curEnd.line--;
  3684. curEnd.ch = 0;
  3685. }
  3686. // If the last word is not an empty line, clip an additional newline
  3687. if (line) {
  3688. curEnd.line--;
  3689. curEnd.ch = lineLength(cm, curEnd.line);
  3690. } else {
  3691. curEnd.ch = 0;
  3692. }
  3693. }
  3694. }
  3695. // Expand the selection to line ends.
  3696. /** @arg {CodeMirror} _cm @arg {Pos} curStart @arg {Pos} curEnd */
  3697. function expandSelectionToLine(_cm, curStart, curEnd) {
  3698. curStart.ch = 0;
  3699. curEnd.ch = 0;
  3700. curEnd.line++;
  3701. }
  3702. /** @arg {string} [text] */
  3703. function findFirstNonWhiteSpaceCharacter(text) {
  3704. if (!text) {
  3705. return 0;
  3706. }
  3707. var firstNonWS = text.search(/\S/);
  3708. return firstNonWS == -1 ? text.length : firstNonWS;
  3709. }
  3710. /**
  3711. * @arg {CodeMirror} cm
  3712. * @arg {{inclusive?: boolean, innerWord?: boolean, bigWord?: boolean, noSymbol?: boolean, multiline?: boolean}} options
  3713. * @arg {Pos} [cursor]
  3714. **/
  3715. function expandWordUnderCursor(cm, {inclusive, innerWord, bigWord, noSymbol, multiline}, cursor) {
  3716. var cur = cursor || getHead(cm);
  3717. var line = cm.getLine(cur.line);
  3718. var endLine = line;
  3719. var startLineNumber = cur.line
  3720. var endLineNumber = startLineNumber;
  3721. var idx = cur.ch;
  3722. var wordOnNextLine;
  3723. // Seek to first word or non-whitespace character, depending on if
  3724. // noSymbol is true.
  3725. var test = noSymbol ? wordCharTest[0] : bigWordCharTest [0];
  3726. if (innerWord && /\s/.test(line.charAt(idx))) {
  3727. test = function(/** @type {string} */ ch) { return /\s/.test(ch); };
  3728. } else {
  3729. while (!test(line.charAt(idx))) {
  3730. idx++;
  3731. if (idx >= line.length) {
  3732. if (!multiline) return null;
  3733. idx--;
  3734. wordOnNextLine = findWord(cm, cur, true, bigWord, true);
  3735. break
  3736. }
  3737. }
  3738. if (bigWord) {
  3739. test = bigWordCharTest[0];
  3740. } else {
  3741. test = wordCharTest[0];
  3742. if (!test(line.charAt(idx))) {
  3743. test = wordCharTest[1];
  3744. }
  3745. }
  3746. }
  3747. var end = idx, start = idx;
  3748. while (test(line.charAt(start)) && start >= 0) { start--; }
  3749. start++;
  3750. if (wordOnNextLine) {
  3751. end = wordOnNextLine.to;
  3752. endLineNumber = wordOnNextLine.line;
  3753. endLine = cm.getLine(endLineNumber);
  3754. if (!endLine && end == 0) end++;
  3755. } else {
  3756. while (test(line.charAt(end)) && end < line.length) { end++; }
  3757. }
  3758. if (inclusive) {
  3759. // If present, include all whitespace after word.
  3760. // Otherwise, include all whitespace before word, except indentation.
  3761. var wordEnd = end;
  3762. var startsWithSpace = cur.ch <= start && /\s/.test(line.charAt(cur.ch));
  3763. if (!startsWithSpace) {
  3764. while (/\s/.test(endLine.charAt(end)) && end < endLine.length) { end++; }
  3765. }
  3766. if (wordEnd == end || startsWithSpace) {
  3767. var wordStart = start;
  3768. while (/\s/.test(line.charAt(start - 1)) && start > 0) { start--; }
  3769. if (!start && !startsWithSpace) { start = wordStart; }
  3770. }
  3771. }
  3772. return { start: new Pos(startLineNumber, start), end: new Pos(endLineNumber, end) };
  3773. }
  3774. /**
  3775. * Depends on the following:
  3776. *
  3777. * - editor mode should be htmlmixedmode / xml
  3778. * - mode/xml/xml.js should be loaded
  3779. * - addon/fold/xml-fold.js should be loaded
  3780. *
  3781. * If any of the above requirements are not true, this function noops.
  3782. *
  3783. * This is _NOT_ a 100% accurate implementation of vim tag text objects.
  3784. * The following caveats apply (based off cursory testing, I'm sure there
  3785. * are other discrepancies):
  3786. *
  3787. * - Does not work inside comments:
  3788. * ```
  3789. * <!-- <div>broken</div> -->
  3790. * ```
  3791. * - Does not work when tags have different cases:
  3792. * ```
  3793. * <div>broken</DIV>
  3794. * ```
  3795. * - Does not work when cursor is inside a broken tag:
  3796. * ```
  3797. * <div><brok><en></div>
  3798. * ```
  3799. * @arg {CodeMirror} cm
  3800. * @arg {Pos} head
  3801. * @arg {boolean} [inclusive]
  3802. */
  3803. function expandTagUnderCursor(cm, head, inclusive) {
  3804. var cur = head;
  3805. if (!CodeMirror.findMatchingTag || !CodeMirror.findEnclosingTag) {
  3806. return { start: cur, end: cur };
  3807. }
  3808. var tags = CodeMirror.findMatchingTag(cm, head) || CodeMirror.findEnclosingTag(cm, head);
  3809. if (!tags || !tags.open || !tags.close) {
  3810. return { start: cur, end: cur };
  3811. }
  3812. if (inclusive) {
  3813. return { start: tags.open.from, end: tags.close.to };
  3814. }
  3815. return { start: tags.open.to, end: tags.close.from };
  3816. }
  3817. /** @arg {CodeMirror} cm @arg {Pos} oldCur @arg {Pos} newCur */
  3818. function recordJumpPosition(cm, oldCur, newCur) {
  3819. if (!cursorEqual(oldCur, newCur)) {
  3820. vimGlobalState.jumpList.add(cm, oldCur, newCur);
  3821. }
  3822. }
  3823. /** @arg {number} increment @arg {{ forward?: any; selectedCharacter?: any; }} args */
  3824. function recordLastCharacterSearch(increment, args) {
  3825. vimGlobalState.lastCharacterSearch.increment = increment;
  3826. vimGlobalState.lastCharacterSearch.forward = args.forward;
  3827. vimGlobalState.lastCharacterSearch.selectedCharacter = args.selectedCharacter;
  3828. }
  3829. var symbolToMode = {
  3830. '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',
  3831. '[': 'section', ']': 'section',
  3832. '*': 'comment', '/': 'comment',
  3833. 'm': 'method', 'M': 'method',
  3834. '#': 'preprocess'
  3835. };
  3836. var findSymbolModes = {
  3837. bracket: {
  3838. isComplete: function(state) {
  3839. if (state.nextCh === state.symb) {
  3840. state.depth++;
  3841. if (state.depth >= 1)return true;
  3842. } else if (state.nextCh === state.reverseSymb) {
  3843. state.depth--;
  3844. }
  3845. return false;
  3846. }
  3847. },
  3848. section: {
  3849. init: function(state) {
  3850. state.curMoveThrough = true;
  3851. state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';
  3852. },
  3853. isComplete: function(state) {
  3854. return state.index === 0 && state.nextCh === state.symb;
  3855. }
  3856. },
  3857. comment: {
  3858. isComplete: function(state) {
  3859. var found = state.lastCh === '*' && state.nextCh === '/';
  3860. state.lastCh = state.nextCh;
  3861. return found;
  3862. }
  3863. },
  3864. // TODO: The original Vim implementation only operates on level 1 and 2.
  3865. // The current implementation doesn't check for code block level and
  3866. // therefore it operates on any levels.
  3867. method: {
  3868. init: function(state) {
  3869. state.symb = (state.symb === 'm' ? '{' : '}');
  3870. state.reverseSymb = state.symb === '{' ? '}' : '{';
  3871. },
  3872. isComplete: function(state) {
  3873. if (state.nextCh === state.symb)return true;
  3874. return false;
  3875. }
  3876. },
  3877. preprocess: {
  3878. init: function(state) {
  3879. state.index = 0;
  3880. },
  3881. isComplete: function(state) {
  3882. if (state.nextCh === '#') {
  3883. var token = state.lineText.match(/^#(\w+)/)[1];
  3884. if (token === 'endif') {
  3885. if (state.forward && state.depth === 0) {
  3886. return true;
  3887. }
  3888. state.depth++;
  3889. } else if (token === 'if') {
  3890. if (!state.forward && state.depth === 0) {
  3891. return true;
  3892. }
  3893. state.depth--;
  3894. }
  3895. if (token === 'else' && state.depth === 0)return true;
  3896. }
  3897. return false;
  3898. }
  3899. }
  3900. };
  3901. /** @arg {CodeMirrorV} cm @arg {number} repeat @arg {boolean|undefined} forward @arg {string} symb */
  3902. function findSymbol(cm, repeat, forward, symb) {
  3903. var cur = copyCursor(cm.getCursor());
  3904. var increment = forward ? 1 : -1;
  3905. var endLine = forward ? cm.lineCount() : -1;
  3906. var curCh = cur.ch;
  3907. var line = cur.line;
  3908. var lineText = cm.getLine(line);
  3909. var state = {
  3910. lineText: lineText,
  3911. nextCh: lineText.charAt(curCh),
  3912. lastCh: null,
  3913. index: curCh,
  3914. symb: symb,
  3915. reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],
  3916. forward: forward,
  3917. depth: 0,
  3918. curMoveThrough: false
  3919. };
  3920. var mode = symbolToMode[symb];
  3921. if (!mode)return cur;
  3922. var init = findSymbolModes[mode].init;
  3923. var isComplete = findSymbolModes[mode].isComplete;
  3924. if (init) { init(state); }
  3925. while (line !== endLine && repeat) {
  3926. state.index += increment;
  3927. state.nextCh = state.lineText.charAt(state.index);
  3928. if (!state.nextCh) {
  3929. line += increment;
  3930. state.lineText = cm.getLine(line) || '';
  3931. if (increment > 0) {
  3932. state.index = 0;
  3933. } else {
  3934. var lineLen = state.lineText.length;
  3935. state.index = (lineLen > 0) ? (lineLen-1) : 0;
  3936. }
  3937. state.nextCh = state.lineText.charAt(state.index);
  3938. }
  3939. if (isComplete(state)) {
  3940. cur.line = line;
  3941. cur.ch = state.index;
  3942. repeat--;
  3943. }
  3944. }
  3945. if (state.nextCh || state.curMoveThrough) {
  3946. return new Pos(line, state.index);
  3947. }
  3948. return cur;
  3949. }
  3950. /*
  3951. * Returns the boundaries of the next word. If the cursor in the middle of
  3952. * the word, then returns the boundaries of the current word, starting at
  3953. * the cursor. If the cursor is at the start/end of a word, and we are going
  3954. * forward/backward, respectively, find the boundaries of the next word.
  3955. *
  3956. * @arg {CodeMirror} cm CodeMirror object.
  3957. * @arg {Cursor} cur The cursor position.
  3958. * @arg {boolean} forward True to search forward. False to search
  3959. * backward.
  3960. * @arg {boolean} bigWord True if punctuation count as part of the word.
  3961. * False if only [a-zA-Z0-9] characters count as part of the word.
  3962. * @arg {boolean} emptyLineIsWord True if empty lines should be treated
  3963. * as words.
  3964. * @return {Object{from:number, to:number, line: number}} The boundaries of
  3965. * the word, or null if there are no more words.
  3966. */
  3967. function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {
  3968. var lineNum = cur.line;
  3969. var pos = cur.ch;
  3970. var line = cm.getLine(lineNum);
  3971. var dir = forward ? 1 : -1;
  3972. var charTests = bigWord ? bigWordCharTest: wordCharTest;
  3973. if (emptyLineIsWord && line == '') {
  3974. lineNum += dir;
  3975. line = cm.getLine(lineNum);
  3976. if (!isLine(cm, lineNum)) {
  3977. return null;
  3978. }
  3979. pos = (forward) ? 0 : line.length;
  3980. }
  3981. while (true) {
  3982. if (emptyLineIsWord && line == '') {
  3983. return { from: 0, to: 0, line: lineNum };
  3984. }
  3985. var stop = (dir > 0) ? line.length : -1;
  3986. var wordStart = stop, wordEnd = stop;
  3987. // Find bounds of next word.
  3988. while (pos != stop) {
  3989. var foundWord = false;
  3990. for (var i = 0; i < charTests.length && !foundWord; ++i) {
  3991. if (charTests[i](line.charAt(pos))) {
  3992. wordStart = pos;
  3993. // Advance to end of word.
  3994. while (pos != stop && charTests[i](line.charAt(pos))) {
  3995. pos += dir;
  3996. }
  3997. wordEnd = pos;
  3998. foundWord = wordStart != wordEnd;
  3999. if (wordStart == cur.ch && lineNum == cur.line &&
  4000. wordEnd == wordStart + dir) {
  4001. // We started at the end of a word. Find the next one.
  4002. continue;
  4003. } else {
  4004. return {
  4005. from: Math.min(wordStart, wordEnd + 1),
  4006. to: Math.max(wordStart, wordEnd),
  4007. line: lineNum };
  4008. }
  4009. }
  4010. }
  4011. if (!foundWord) {
  4012. pos += dir;
  4013. }
  4014. }
  4015. // Advance to next/prev line.
  4016. lineNum += dir;
  4017. if (!isLine(cm, lineNum)) {
  4018. return null;
  4019. }
  4020. line = cm.getLine(lineNum);
  4021. pos = (dir > 0) ? 0 : line.length;
  4022. }
  4023. }
  4024. /**
  4025. * @arg {CodeMirror} cm CodeMirror object.
  4026. * @arg {Pos} cur The position to start from.
  4027. * @arg {number} repeat Number of words to move past.
  4028. * @arg {boolean} forward True to search forward. False to search
  4029. * backward.
  4030. * @arg {boolean} wordEnd True to move to end of word. False to move to
  4031. * beginning of word.
  4032. * @arg {boolean} bigWord True if punctuation count as part of the word.
  4033. * False if only alphabet characters count as part of the word.
  4034. * @return {Pos|undefined} The position the cursor should move to.
  4035. */
  4036. function moveToWord(cm, cur, repeat, forward, wordEnd, bigWord) {
  4037. var curStart = copyCursor(cur);
  4038. var words = [];
  4039. if (forward && !wordEnd || !forward && wordEnd) {
  4040. repeat++;
  4041. }
  4042. // For 'e', empty lines are not considered words, go figure.
  4043. var emptyLineIsWord = !(forward && wordEnd);
  4044. for (var i = 0; i < repeat; i++) {
  4045. var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord);
  4046. if (!word) {
  4047. var eodCh = lineLength(cm, cm.lastLine());
  4048. words.push(forward
  4049. ? {line: cm.lastLine(), from: eodCh, to: eodCh}
  4050. : {line: 0, from: 0, to: 0});
  4051. break;
  4052. }
  4053. words.push(word);
  4054. cur = new Pos(word.line, forward ? (word.to - 1) : word.from);
  4055. }
  4056. var shortCircuit = words.length != repeat;
  4057. var firstWord = words[0];
  4058. var lastWord = words.pop();
  4059. if (forward && !wordEnd) {
  4060. // w
  4061. if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) {
  4062. // We did not start in the middle of a word. Discard the extra word at the end.
  4063. lastWord = words.pop();
  4064. }
  4065. return lastWord && new Pos(lastWord.line, lastWord.from);
  4066. } else if (forward && wordEnd) {
  4067. return lastWord && new Pos(lastWord.line, lastWord.to - 1);
  4068. } else if (!forward && wordEnd) {
  4069. // ge
  4070. if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) {
  4071. // We did not start in the middle of a word. Discard the extra word at the end.
  4072. lastWord = words.pop();
  4073. }
  4074. return lastWord && new Pos(lastWord.line, lastWord.to);
  4075. } else {
  4076. // b
  4077. return lastWord && new Pos(lastWord.line, lastWord.from);
  4078. }
  4079. }
  4080. /**
  4081. * @arg {CodeMirror} cm
  4082. * @arg {Pos} head
  4083. * @arg {MotionArgs} motionArgs
  4084. * @arg {vimState} vim
  4085. * @arg {boolean} keepHPos */
  4086. function moveToEol(cm, head, motionArgs, vim, keepHPos) {
  4087. var cur = head;
  4088. var retval= new Pos(cur.line + motionArgs.repeat - 1, Infinity);
  4089. var end=cm.clipPos(retval);
  4090. end.ch--;
  4091. if (!keepHPos) {
  4092. vim.lastHPos = Infinity;
  4093. vim.lastHSPos = cm.charCoords(end,'div').left;
  4094. }
  4095. return retval;
  4096. }
  4097. /**
  4098. * @arg {CodeMirror} cm
  4099. * @arg {number} repeat
  4100. * @arg {boolean} [forward]
  4101. * @arg {string} [character]
  4102. * @arg {Pos} [head]
  4103. */
  4104. function moveToCharacter(cm, repeat, forward, character, head) {
  4105. if (!character) return;
  4106. var cur = head || cm.getCursor();
  4107. var start = cur.ch;
  4108. var idx;
  4109. for (var i = 0; i < repeat; i ++) {
  4110. var line = cm.getLine(cur.line);
  4111. idx = charIdxInLine(start, line, character, forward, true);
  4112. if (idx == -1) {
  4113. return undefined;
  4114. }
  4115. start = idx;
  4116. }
  4117. if (idx != undefined)
  4118. return new Pos(cm.getCursor().line, idx);
  4119. }
  4120. /** @arg {CodeMirrorV} cm @arg {number} repeat */
  4121. function moveToColumn(cm, repeat) {
  4122. // repeat is always >= 1, so repeat - 1 always corresponds
  4123. // to the column we want to go to.
  4124. var line = cm.getCursor().line;
  4125. return clipCursorToContent(cm, new Pos(line, repeat - 1));
  4126. }
  4127. /**
  4128. * @arg {CodeMirror} cm
  4129. * @arg {vimState} vim
  4130. * @arg {string} markName
  4131. * @arg {Pos} pos */
  4132. function updateMark(cm, vim, markName, pos) {
  4133. if (!inArray(markName, validMarks) && !latinCharRegex.test(markName)) {
  4134. return;
  4135. }
  4136. if (vim.marks[markName]) {
  4137. vim.marks[markName].clear();
  4138. }
  4139. vim.marks[markName] = cm.setBookmark(pos);
  4140. }
  4141. /**
  4142. * @arg {number} start
  4143. * @arg {string | any[]} line
  4144. * @arg {any} character
  4145. * @arg {boolean} [forward]
  4146. * @arg {boolean} [includeChar] */
  4147. function charIdxInLine(start, line, character, forward, includeChar) {
  4148. // Search for char in line.
  4149. // motion_options: {forward, includeChar}
  4150. // If includeChar = true, include it too.
  4151. // If forward = true, search forward, else search backwards.
  4152. // If char is not found on this line, do nothing
  4153. var idx;
  4154. if (forward) {
  4155. idx = line.indexOf(character, start + 1);
  4156. if (idx != -1 && !includeChar) {
  4157. idx -= 1;
  4158. }
  4159. } else {
  4160. idx = line.lastIndexOf(character, start - 1);
  4161. if (idx != -1 && !includeChar) {
  4162. idx += 1;
  4163. }
  4164. }
  4165. return idx;
  4166. }
  4167. /** @arg {CodeMirrorV} cm
  4168. * @arg {Pos} head
  4169. * @arg {number} repeat
  4170. * @arg {number} dir
  4171. * @arg {boolean} [inclusive] */
  4172. function findParagraph(cm, head, repeat, dir, inclusive) {
  4173. var line = head.line;
  4174. var min = cm.firstLine();
  4175. var max = cm.lastLine();
  4176. var start, end, i = line;
  4177. /** @arg {number} i */
  4178. function isEmpty(i) { return !cm.getLine(i); }
  4179. /** @arg {number} i @arg {number} dir @arg {boolean} [any] */
  4180. function isBoundary(i, dir, any) {
  4181. if (any) { return isEmpty(i) != isEmpty(i + dir); }
  4182. return !isEmpty(i) && isEmpty(i + dir);
  4183. }
  4184. if (dir) {
  4185. while (min <= i && i <= max && repeat > 0) {
  4186. if (isBoundary(i, dir)) { repeat--; }
  4187. i += dir;
  4188. }
  4189. return {start: new Pos(i, 0), end: head};
  4190. }
  4191. var vim = cm.state.vim;
  4192. if (vim.visualLine && isBoundary(line, 1, true)) {
  4193. var anchor = vim.sel.anchor;
  4194. if (isBoundary(anchor.line, -1, true)) {
  4195. if (!inclusive || anchor.line != line) {
  4196. line += 1;
  4197. }
  4198. }
  4199. }
  4200. var startState = isEmpty(line);
  4201. for (i = line; i <= max && repeat; i++) {
  4202. if (isBoundary(i, 1, true)) {
  4203. if (!inclusive || isEmpty(i) != startState) {
  4204. repeat--;
  4205. }
  4206. }
  4207. }
  4208. end = new Pos(i, 0);
  4209. // select boundary before paragraph for the last one
  4210. if (i > max && !startState) { startState = true; }
  4211. else { inclusive = false; }
  4212. for (i = line; i > min; i--) {
  4213. if (!inclusive || isEmpty(i) == startState || i == line) {
  4214. if (isBoundary(i, -1, true)) { break; }
  4215. }
  4216. }
  4217. start = new Pos(i, 0);
  4218. return { start: start, end: end };
  4219. }
  4220. /**
  4221. * Based on {@link findSentence}. The internal functions have the same names,
  4222. * but their behaviour is different. findSentence() crosses line breaks and
  4223. * is used for jumping to sentence beginnings before or after the current cursor position,
  4224. * whereas getSentence() is for getting the beginning or end of the sentence
  4225. * at the current cursor position, either including (a) or excluding (i) whitespace.
  4226. * @arg {CodeMirror} cm
  4227. * @arg {Pos} cur
  4228. * @arg {number} repeat
  4229. * @arg {number} dir
  4230. * @arg {boolean} inclusive
  4231. */
  4232. function getSentence(cm, cur, repeat, dir, inclusive /*includes whitespace*/) {
  4233. /*
  4234. Takes an index object
  4235. {
  4236. line: the line string,
  4237. ln: line number,
  4238. pos: index in line,
  4239. dir: direction of traversal (-1 or 1)
  4240. }
  4241. and modifies the pos member to represent the
  4242. next valid position or sets the line to null if there are
  4243. no more valid positions.
  4244. */
  4245. function nextChar(curr) {
  4246. if (curr.pos + curr.dir < 0 || curr.pos + curr.dir >= curr.line.length) {
  4247. curr.line = null;
  4248. }
  4249. else {
  4250. curr.pos += curr.dir;
  4251. }
  4252. }
  4253. /*
  4254. Performs one iteration of traversal in forward direction
  4255. Returns an index object of the sentence end
  4256. */
  4257. function forward(cm, ln, pos, dir) {
  4258. var line = cm.getLine(ln);
  4259. var curr = {
  4260. line: line,
  4261. ln: ln,
  4262. pos: pos,
  4263. dir: dir,
  4264. };
  4265. if (curr.line === "") {
  4266. return { ln: curr.ln, pos: curr.pos };
  4267. }
  4268. var lastSentencePos = curr.pos;
  4269. // Move one step to skip character we start on
  4270. nextChar(curr);
  4271. while (curr.line !== null) {
  4272. lastSentencePos = curr.pos;
  4273. if (isEndOfSentenceSymbol(curr.line[curr.pos])) {
  4274. if (!inclusive) {
  4275. return { ln: curr.ln, pos: curr.pos + 1 };
  4276. }
  4277. else {
  4278. nextChar(curr);
  4279. while (curr.line !== null ) {
  4280. if (isWhiteSpaceString(curr.line[curr.pos])) {
  4281. lastSentencePos = curr.pos;
  4282. nextChar(curr)
  4283. }
  4284. else {
  4285. break;
  4286. }
  4287. }
  4288. return { ln: curr.ln, pos: lastSentencePos + 1 };
  4289. }
  4290. }
  4291. nextChar(curr);
  4292. }
  4293. return { ln: curr.ln, pos: lastSentencePos + 1 };
  4294. }
  4295. /**
  4296. * Performs one iteration of traversal in reverse direction
  4297. * Returns an index object of the sentence start
  4298. * @arg {CodeMirror} cm
  4299. * @arg {number} ln
  4300. * @arg {number} pos
  4301. * @arg {number} dir
  4302. */
  4303. function reverse(cm, ln, pos, dir) {
  4304. var line = cm.getLine(ln);
  4305. var curr = {
  4306. line: line,
  4307. ln: ln,
  4308. pos: pos,
  4309. dir: dir,
  4310. }
  4311. if (curr.line === "") {
  4312. return { ln: curr.ln, pos: curr.pos };
  4313. }
  4314. var lastSentencePos = curr.pos;
  4315. // Move one step to skip character we start on
  4316. nextChar(curr);
  4317. while (curr.line !== null) {
  4318. if (!isWhiteSpaceString(curr.line[curr.pos]) && !isEndOfSentenceSymbol(curr.line[curr.pos])) {
  4319. lastSentencePos = curr.pos;
  4320. }
  4321. else if (isEndOfSentenceSymbol(curr.line[curr.pos]) ) {
  4322. if (!inclusive) {
  4323. return { ln: curr.ln, pos: lastSentencePos };
  4324. }
  4325. else {
  4326. if (isWhiteSpaceString(curr.line[curr.pos + 1])) {
  4327. return { ln: curr.ln, pos: curr.pos + 1 };
  4328. }
  4329. else {
  4330. return { ln: curr.ln, pos: lastSentencePos };
  4331. }
  4332. }
  4333. }
  4334. nextChar(curr);
  4335. }
  4336. curr.line = line
  4337. if (inclusive && isWhiteSpaceString(curr.line[curr.pos])) {
  4338. return { ln: curr.ln, pos: curr.pos };
  4339. }
  4340. else {
  4341. return { ln: curr.ln, pos: lastSentencePos };
  4342. }
  4343. }
  4344. var curr_index = {
  4345. ln: cur.line,
  4346. pos: cur.ch,
  4347. };
  4348. while (repeat > 0) {
  4349. if (dir < 0) {
  4350. curr_index = reverse(cm, curr_index.ln, curr_index.pos, dir);
  4351. }
  4352. else {
  4353. curr_index = forward(cm, curr_index.ln, curr_index.pos, dir);
  4354. }
  4355. repeat--;
  4356. }
  4357. return new Pos(curr_index.ln, curr_index.pos);
  4358. }
  4359. function findSentence(cm, cur, repeat, dir) {
  4360. /*
  4361. Takes an index object
  4362. {
  4363. line: the line string,
  4364. ln: line number,
  4365. pos: index in line,
  4366. dir: direction of traversal (-1 or 1)
  4367. }
  4368. and modifies the line, ln, and pos members to represent the
  4369. next valid position or sets them to null if there are
  4370. no more valid positions.
  4371. */
  4372. function nextChar(cm, idx) {
  4373. if (idx.pos + idx.dir < 0 || idx.pos + idx.dir >= idx.line.length) {
  4374. idx.ln += idx.dir;
  4375. if (!isLine(cm, idx.ln)) {
  4376. idx.line = null;
  4377. idx.ln = null;
  4378. idx.pos = null;
  4379. return;
  4380. }
  4381. idx.line = cm.getLine(idx.ln);
  4382. idx.pos = (idx.dir > 0) ? 0 : idx.line.length - 1;
  4383. }
  4384. else {
  4385. idx.pos += idx.dir;
  4386. }
  4387. }
  4388. /*
  4389. Performs one iteration of traversal in forward direction
  4390. Returns an index object of the new location
  4391. */
  4392. /** @arg {CodeMirror} cm @arg {number} ln @arg {number} pos @arg {number} dir */
  4393. function forward(cm, ln, pos, dir) {
  4394. var line = cm.getLine(ln);
  4395. var stop = (line === "");
  4396. var curr = {
  4397. line: line,
  4398. ln: ln,
  4399. pos: pos,
  4400. dir: dir,
  4401. }
  4402. var last_valid = {
  4403. ln: curr.ln,
  4404. pos: curr.pos,
  4405. }
  4406. var skip_empty_lines = (curr.line === "");
  4407. // Move one step to skip character we start on
  4408. nextChar(cm, curr);
  4409. while (curr.line !== null) {
  4410. last_valid.ln = curr.ln;
  4411. last_valid.pos = curr.pos;
  4412. if (curr.line === "" && !skip_empty_lines) {
  4413. return { ln: curr.ln, pos: curr.pos, };
  4414. }
  4415. else if (stop && curr.line !== "" && !isWhiteSpaceString(curr.line[curr.pos])) {
  4416. return { ln: curr.ln, pos: curr.pos, };
  4417. }
  4418. else if (isEndOfSentenceSymbol(curr.line[curr.pos])
  4419. && !stop
  4420. && (curr.pos === curr.line.length - 1
  4421. || isWhiteSpaceString(curr.line[curr.pos + 1]))) {
  4422. stop = true;
  4423. }
  4424. nextChar(cm, curr);
  4425. }
  4426. /*
  4427. Set the position to the last non whitespace character on the last
  4428. valid line in the case that we reach the end of the document.
  4429. */
  4430. var line = cm.getLine(last_valid.ln);
  4431. last_valid.pos = 0;
  4432. for(var i = line.length - 1; i >= 0; --i) {
  4433. if (!isWhiteSpaceString(line[i])) {
  4434. last_valid.pos = i;
  4435. break;
  4436. }
  4437. }
  4438. return last_valid;
  4439. }
  4440. /*
  4441. Performs one iteration of traversal in reverse direction
  4442. Returns an index object of the new location
  4443. */
  4444. /** @arg {CodeMirror} cm @arg {number} ln @arg {number} pos @arg {number} dir */
  4445. function reverse(cm, ln, pos, dir) {
  4446. var line = cm.getLine(ln);
  4447. var curr = {
  4448. line: line,
  4449. ln: ln,
  4450. pos: pos,
  4451. dir: dir,
  4452. }
  4453. /** @type {{ln: number, pos: number|null}} */
  4454. var last_valid = {
  4455. ln: curr.ln,
  4456. pos: null,
  4457. };
  4458. var skip_empty_lines = (curr.line === "");
  4459. // Move one step to skip character we start on
  4460. nextChar(cm, curr);
  4461. while (curr.line !== null) {
  4462. if (curr.line === "" && !skip_empty_lines) {
  4463. if (last_valid.pos !== null) {
  4464. return last_valid;
  4465. }
  4466. else {
  4467. return { ln: curr.ln, pos: curr.pos };
  4468. }
  4469. }
  4470. else if (isEndOfSentenceSymbol(curr.line[curr.pos])
  4471. && last_valid.pos !== null
  4472. && !(curr.ln === last_valid.ln && curr.pos + 1 === last_valid.pos)) {
  4473. return last_valid;
  4474. }
  4475. else if (curr.line !== "" && !isWhiteSpaceString(curr.line[curr.pos])) {
  4476. skip_empty_lines = false;
  4477. last_valid = { ln: curr.ln, pos: curr.pos }
  4478. }
  4479. nextChar(cm, curr);
  4480. }
  4481. /*
  4482. Set the position to the first non whitespace character on the last
  4483. valid line in the case that we reach the beginning of the document.
  4484. */
  4485. var line = cm.getLine(last_valid.ln);
  4486. last_valid.pos = 0;
  4487. for(var i = 0; i < line.length; ++i) {
  4488. if (!isWhiteSpaceString(line[i])) {
  4489. last_valid.pos = i;
  4490. break;
  4491. }
  4492. }
  4493. return last_valid;
  4494. }
  4495. var curr_index = {
  4496. ln: cur.line,
  4497. pos: cur.ch,
  4498. };
  4499. while (repeat > 0) {
  4500. if (dir < 0) {
  4501. curr_index = reverse(cm, curr_index.ln, curr_index.pos, dir);
  4502. }
  4503. else {
  4504. curr_index = forward(cm, curr_index.ln, curr_index.pos, dir);
  4505. }
  4506. repeat--;
  4507. }
  4508. return new Pos(curr_index.ln, curr_index.pos);
  4509. }
  4510. // TODO: perhaps this finagling of start and end positions belongs
  4511. // in codemirror/replaceRange?
  4512. /** @arg {CodeMirror} cm @arg {Pos} head @arg {string | number} symb @arg {boolean} inclusive */
  4513. function selectCompanionObject(cm, head, symb, inclusive) {
  4514. var cur = head;
  4515. var bracketRegexp = ({
  4516. '(': /[()]/, ')': /[()]/,
  4517. '[': /[[\]]/, ']': /[[\]]/,
  4518. '{': /[{}]/, '}': /[{}]/,
  4519. '<': /[<>]/, '>': /[<>]/})[symb];
  4520. var openSym = ({
  4521. '(': '(', ')': '(',
  4522. '[': '[', ']': '[',
  4523. '{': '{', '}': '{',
  4524. '<': '<', '>': '<'})[symb];
  4525. var curChar = cm.getLine(cur.line).charAt(cur.ch);
  4526. // Due to the behavior of scanForBracket, we need to add an offset if the
  4527. // cursor is on a matching open bracket.
  4528. var offset = curChar === openSym ? 1 : 0;
  4529. var startBracket = cm.scanForBracket(new Pos(cur.line, cur.ch + offset), -1, undefined, {'bracketRegex': bracketRegexp});
  4530. var endBracket = cm.scanForBracket(new Pos(cur.line, cur.ch + offset), 1, undefined, {'bracketRegex': bracketRegexp});
  4531. if (!startBracket || !endBracket) return null;
  4532. var start = startBracket.pos;
  4533. var end = endBracket.pos;
  4534. if ((start.line == end.line && start.ch > end.ch)
  4535. || (start.line > end.line)) {
  4536. var tmp = start;
  4537. start = end;
  4538. end = tmp;
  4539. }
  4540. if (inclusive) {
  4541. end.ch += 1;
  4542. } else {
  4543. start.ch += 1;
  4544. }
  4545. return { start: start, end: end };
  4546. }
  4547. // Takes in a symbol and a cursor and tries to simulate text objects that
  4548. // have identical opening and closing symbols
  4549. // TODO support across multiple lines
  4550. /** @arg {CodeMirror} cm @arg {Pos} head @arg {string} symb @arg {boolean} inclusive */
  4551. function findBeginningAndEnd(cm, head, symb, inclusive) {
  4552. var cur = copyCursor(head);
  4553. var line = cm.getLine(cur.line);
  4554. var chars = line.split('');
  4555. var start, end, i, len;
  4556. var firstIndex = chars.indexOf(symb);
  4557. // the decision tree is to always look backwards for the beginning first,
  4558. // but if the cursor is in front of the first instance of the symb,
  4559. // then move the cursor forward
  4560. if (cur.ch < firstIndex) {
  4561. cur.ch = firstIndex;
  4562. }
  4563. // otherwise if the cursor is currently on the closing symbol
  4564. else if (firstIndex < cur.ch && chars[cur.ch] == symb) {
  4565. var stringAfter = /string/.test(cm.getTokenTypeAt(offsetCursor(head, 0, 1)));
  4566. var stringBefore = /string/.test(cm.getTokenTypeAt(head));
  4567. var isStringStart = stringAfter && !stringBefore
  4568. if (!isStringStart) {
  4569. end = cur.ch; // assign end to the current cursor
  4570. --cur.ch; // make sure to look backwards
  4571. }
  4572. }
  4573. // if we're currently on the symbol, we've got a start
  4574. if (chars[cur.ch] == symb && !end) {
  4575. start = cur.ch + 1; // assign start to ahead of the cursor
  4576. } else {
  4577. // go backwards to find the start
  4578. for (i = cur.ch; i > -1 && !start; i--) {
  4579. if (chars[i] == symb) {
  4580. start = i + 1;
  4581. }
  4582. }
  4583. }
  4584. // look forwards for the end symbol
  4585. if (start && !end) {
  4586. for (i = start, len = chars.length; i < len && !end; i++) {
  4587. if (chars[i] == symb) {
  4588. end = i;
  4589. }
  4590. }
  4591. }
  4592. // nothing found
  4593. if (!start || !end) {
  4594. return { start: cur, end: cur };
  4595. }
  4596. // include the symbols
  4597. if (inclusive) {
  4598. --start; ++end;
  4599. }
  4600. return {
  4601. start: new Pos(cur.line, start),
  4602. end: new Pos(cur.line, end)
  4603. };
  4604. }
  4605. // Search functions
  4606. defineOption('pcre', true, 'boolean');
  4607. class SearchState {
  4608. getQuery() {
  4609. return vimGlobalState.query;
  4610. };
  4611. setQuery(query) {
  4612. vimGlobalState.query = query;
  4613. };
  4614. getOverlay() {
  4615. return this.searchOverlay;
  4616. };
  4617. setOverlay(overlay) {
  4618. this.searchOverlay = overlay;
  4619. };
  4620. isReversed() {
  4621. return vimGlobalState.isReversed;
  4622. };
  4623. setReversed(reversed) {
  4624. vimGlobalState.isReversed = reversed;
  4625. };
  4626. getScrollbarAnnotate() {
  4627. return this.annotate;
  4628. };
  4629. setScrollbarAnnotate(annotate) {
  4630. this.annotate = annotate;
  4631. };
  4632. };
  4633. /** @arg {CodeMirrorV} cm */
  4634. function getSearchState(cm) {
  4635. var vim = cm.state.vim;
  4636. return vim.searchState_ || (vim.searchState_ = new SearchState());
  4637. }
  4638. /** @arg {string} argString */
  4639. function splitBySlash(argString) {
  4640. return splitBySeparator(argString, '/');
  4641. }
  4642. /** @arg {string} argString */
  4643. function findUnescapedSlashes(argString) {
  4644. return findUnescapedSeparators(argString, '/');
  4645. }
  4646. /** @arg {string} argString @arg {string} separator */
  4647. function splitBySeparator(argString, separator) {
  4648. var slashes = findUnescapedSeparators(argString, separator) || [];
  4649. if (!slashes.length) return [];
  4650. var tokens = [];
  4651. // in case of strings like foo/bar
  4652. if (slashes[0] !== 0) return;
  4653. for (var i = 0; i < slashes.length; i++) {
  4654. if (typeof slashes[i] == 'number')
  4655. tokens.push(argString.substring(slashes[i] + 1, slashes[i+1]));
  4656. }
  4657. return tokens;
  4658. }
  4659. /** @arg {string} str @arg {string} separator */
  4660. function findUnescapedSeparators(str, separator) {
  4661. if (!separator)
  4662. separator = '/';
  4663. var escapeNextChar = false;
  4664. var slashes = [];
  4665. for (var i = 0; i < str.length; i++) {
  4666. var c = str.charAt(i);
  4667. if (!escapeNextChar && c == separator) {
  4668. slashes.push(i);
  4669. }
  4670. escapeNextChar = !escapeNextChar && (c == '\\');
  4671. }
  4672. return slashes;
  4673. }
  4674. // Translates a search string from ex (vim) syntax into javascript form.
  4675. /** @arg {string} str */
  4676. function translateRegex(str) {
  4677. // When these match, add a '\' if unescaped or remove one if escaped.
  4678. var specials = '|(){';
  4679. // Remove, but never add, a '\' for these.
  4680. var unescape = '}';
  4681. var escapeNextChar = false;
  4682. var out = [];
  4683. for (var i = -1; i < str.length; i++) {
  4684. var c = str.charAt(i) || '';
  4685. var n = str.charAt(i+1) || '';
  4686. var specialComesNext = (n && specials.indexOf(n) != -1);
  4687. if (escapeNextChar) {
  4688. if (c !== '\\' || !specialComesNext) {
  4689. out.push(c);
  4690. }
  4691. escapeNextChar = false;
  4692. } else {
  4693. if (c === '\\') {
  4694. escapeNextChar = true;
  4695. // Treat the unescape list as special for removing, but not adding '\'.
  4696. if (n && unescape.indexOf(n) != -1) {
  4697. specialComesNext = true;
  4698. }
  4699. // Not passing this test means removing a '\'.
  4700. if (!specialComesNext || n === '\\') {
  4701. out.push(c);
  4702. }
  4703. } else {
  4704. out.push(c);
  4705. if (specialComesNext && n !== '\\') {
  4706. out.push('\\');
  4707. }
  4708. }
  4709. }
  4710. }
  4711. return out.join('');
  4712. }
  4713. // Translates the replace part of a search and replace from ex (vim) syntax into
  4714. // javascript form. Similar to translateRegex, but additionally fixes back references
  4715. // (translates '\[0..9]' to '$[0..9]') and follows different rules for escaping '$'.
  4716. /** @type{Object<string, string>} */
  4717. var charUnescapes = {'\\n': '\n', '\\r': '\r', '\\t': '\t'};
  4718. /** @arg {string} str */
  4719. function translateRegexReplace(str) {
  4720. var escapeNextChar = false;
  4721. var out = [];
  4722. for (var i = -1; i < str.length; i++) {
  4723. var c = str.charAt(i) || '';
  4724. var n = str.charAt(i+1) || '';
  4725. if (charUnescapes[c + n]) {
  4726. out.push(charUnescapes[c+n]);
  4727. i++;
  4728. } else if (escapeNextChar) {
  4729. // At any point in the loop, escapeNextChar is true if the previous
  4730. // character was a '\' and was not escaped.
  4731. out.push(c);
  4732. escapeNextChar = false;
  4733. } else {
  4734. if (c === '\\') {
  4735. escapeNextChar = true;
  4736. if ((isNumber(n) || n === '$')) {
  4737. out.push('$');
  4738. } else if (n !== '/' && n !== '\\') {
  4739. out.push('\\');
  4740. }
  4741. } else {
  4742. if (c === '$') {
  4743. out.push('$');
  4744. }
  4745. out.push(c);
  4746. if (n === '/') {
  4747. out.push('\\');
  4748. }
  4749. }
  4750. }
  4751. }
  4752. return out.join('');
  4753. }
  4754. // Unescape \ and / in the replace part, for PCRE mode.
  4755. /** @type{Record<string, string>} */
  4756. var unescapes = {'\\/': '/', '\\\\': '\\', '\\n': '\n', '\\r': '\r', '\\t': '\t', '\\&':'&'};
  4757. /** @arg {string} str */
  4758. function unescapeRegexReplace(str) {
  4759. var stream = new CodeMirror.StringStream(str);
  4760. var output = [];
  4761. while (!stream.eol()) {
  4762. // Search for \.
  4763. while (stream.peek() && stream.peek() != '\\') {
  4764. output.push(stream.next());
  4765. }
  4766. var matched = false;
  4767. for (var matcher in unescapes) {
  4768. if (stream.match(matcher, true)) {
  4769. matched = true;
  4770. output.push(unescapes[matcher]);
  4771. break;
  4772. }
  4773. }
  4774. if (!matched) {
  4775. // Don't change anything
  4776. output.push(stream.next());
  4777. }
  4778. }
  4779. return output.join('');
  4780. }
  4781. /**
  4782. * Extract the regular expression from the query and return a Regexp object.
  4783. * Returns null if the query is blank.
  4784. * If ignoreCase is passed in, the Regexp object will have the 'i' flag set.
  4785. * If smartCase is passed in, and the query contains upper case letters,
  4786. * then ignoreCase is overridden, and the 'i' flag will not be set.
  4787. * If the query contains the /i in the flag part of the regular expression,
  4788. * then both ignoreCase and smartCase are ignored, and 'i' will be passed
  4789. * through to the Regex object.
  4790. * @arg {string|RegExp} query
  4791. * @arg {boolean} ignoreCase
  4792. * @arg {boolean} smartCase
  4793. */
  4794. function parseQuery(query, ignoreCase, smartCase) {
  4795. // First update the last search register
  4796. var lastSearchRegister = vimGlobalState.registerController.getRegister('/');
  4797. lastSearchRegister.setText(query);
  4798. // Check if the query is already a regex.
  4799. if (query instanceof RegExp) { return query; }
  4800. // First try to extract regex + flags from the input. If no flags found,
  4801. // extract just the regex. IE does not accept flags directly defined in
  4802. // the regex string in the form /regex/flags
  4803. var slashes = findUnescapedSlashes(query);
  4804. var regexPart;
  4805. var forceIgnoreCase;
  4806. if (!slashes.length) {
  4807. // Query looks like 'regexp'
  4808. regexPart = query;
  4809. } else {
  4810. // Query looks like 'regexp/...'
  4811. regexPart = query.substring(0, slashes[0]);
  4812. var flagsPart = query.substring(slashes[0]);
  4813. forceIgnoreCase = (flagsPart.indexOf('i') != -1);
  4814. }
  4815. if (!regexPart) {
  4816. return null;
  4817. }
  4818. if (!getOption('pcre')) {
  4819. regexPart = translateRegex(regexPart);
  4820. }
  4821. if (smartCase) {
  4822. ignoreCase = (/^[^A-Z]*$/).test(regexPart);
  4823. }
  4824. var regexp = new RegExp(regexPart,
  4825. (ignoreCase || forceIgnoreCase) ? 'im' : 'm');
  4826. return regexp;
  4827. }
  4828. /**
  4829. * dom - Document Object Manipulator
  4830. * Usage:
  4831. * dom('<tag>'|<node>[, ...{<attributes>|<$styles>}|<child-node>|'<text>'])
  4832. * Examples:
  4833. * dom('div', {id:'xyz'}, dom('p', 'CM rocks!', {$color:'red'}))
  4834. * dom(document.head, dom('script', 'alert("hello!")'))
  4835. * Not supported:
  4836. * dom('p', ['arrays are objects'], Error('objects specify attributes'))
  4837. * @arg {string | HTMLElement } n
  4838. */
  4839. function dom(n) {
  4840. if (typeof n === 'string') n = document.createElement(n);
  4841. for (var a, i = 1; i < arguments.length; i++) {
  4842. if (!(a = arguments[i])) continue;
  4843. if (typeof a !== 'object') a = document.createTextNode(a);
  4844. if (a.nodeType) n.appendChild(a);
  4845. else for (var key in a) {
  4846. if (!Object.prototype.hasOwnProperty.call(a, key)) continue;
  4847. if (key[0] === '$') n.style[key.slice(1)] = a[key];
  4848. else n.setAttribute(key, a[key]);
  4849. }
  4850. }
  4851. return n;
  4852. }
  4853. /** @arg {CodeMirror} cm @arg {any} template */
  4854. function showConfirm(cm, template) {
  4855. var pre = dom('div', {$color: 'red', $whiteSpace: 'pre', class: 'cm-vim-message'}, template);
  4856. if (cm.openNotification) {
  4857. cm.openNotification(pre, {bottom: true, duration: 5000});
  4858. } else {
  4859. alert(pre.innerText);
  4860. }
  4861. }
  4862. /** @arg {string} prefix @arg {string} desc */
  4863. function makePrompt(prefix, desc) {
  4864. return dom('div', {$display: 'flex'},
  4865. dom('span', {$fontFamily: 'monospace', $whiteSpace: 'pre', $flex: 1},
  4866. prefix,
  4867. dom('input', {type: 'text', autocorrect: 'off',
  4868. autocapitalize: 'off', spellcheck: 'false', $width: '100%'})),
  4869. desc && dom('span', {$color: '#888'}, desc));
  4870. }
  4871. /**
  4872. * @arg {CodeMirror} cm
  4873. * @arg {{ onClose?: any; prefix: any; desc?: any; onKeyUp?: any; onKeyDown: any; value?: any; selectValueOnOpen?: boolean; }} options
  4874. */
  4875. function showPrompt(cm, options) {
  4876. if (keyToKeyStack.length) {
  4877. if (!options.value) options.value = '';
  4878. virtualPrompt = options;
  4879. return;
  4880. }
  4881. var template = makePrompt(options.prefix, options.desc);
  4882. if (cm.openDialog) {
  4883. cm.openDialog(template, options.onClose, {
  4884. onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp,
  4885. bottom: true, selectValueOnOpen: false, value: options.value
  4886. });
  4887. }
  4888. else {
  4889. var shortText = '';
  4890. if (typeof options.prefix != "string" && options.prefix) shortText += options.prefix.textContent;
  4891. if (options.desc) shortText += " " + options.desc;
  4892. options.onClose(prompt(shortText, ''));
  4893. }
  4894. }
  4895. /** @arg {RegExp|unknown} r1 @arg {RegExp|unknown} r2 */
  4896. function regexEqual(r1, r2) {
  4897. if (r1 instanceof RegExp && r2 instanceof RegExp) {
  4898. var props = ['global', 'multiline', 'ignoreCase', 'source'];
  4899. for (var i = 0; i < props.length; i++) {
  4900. var prop = props[i];
  4901. if (r1[prop] !== r2[prop]) {
  4902. return false;
  4903. }
  4904. }
  4905. return true;
  4906. }
  4907. return false;
  4908. }
  4909. // Returns true if the query is valid.
  4910. /**
  4911. * @arg {CodeMirrorV} cm
  4912. * @arg {string | RegExp} rawQuery
  4913. * @arg {boolean | undefined} [ignoreCase]
  4914. * @arg {boolean | undefined} [smartCase]
  4915. */
  4916. function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {
  4917. if (!rawQuery) {
  4918. return;
  4919. }
  4920. var state = getSearchState(cm);
  4921. var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase);
  4922. if (!query) {
  4923. return;
  4924. }
  4925. highlightSearchMatches(cm, query);
  4926. if (regexEqual(query, state.getQuery())) {
  4927. return query;
  4928. }
  4929. state.setQuery(query);
  4930. return query;
  4931. }
  4932. /** @arg {RegExp} query */
  4933. function searchOverlay(query) {
  4934. if (query.source.charAt(0) == '^') {
  4935. var matchSol = true;
  4936. }
  4937. return {
  4938. token: function(stream) {
  4939. if (matchSol && !stream.sol()) {
  4940. stream.skipToEnd();
  4941. return;
  4942. }
  4943. var match = stream.match(query, false);
  4944. if (match) {
  4945. if (match[0].length == 0) {
  4946. // Matched empty string, skip to next.
  4947. stream.next();
  4948. return 'searching';
  4949. }
  4950. if (!stream.sol()) {
  4951. // Backtrack 1 to match \b
  4952. stream.backUp(1);
  4953. if (!query.exec(stream.next() + match[0])) {
  4954. stream.next();
  4955. return null;
  4956. }
  4957. }
  4958. stream.match(query);
  4959. return 'searching';
  4960. }
  4961. while (!stream.eol()) {
  4962. stream.next();
  4963. if (stream.match(query, false)) break;
  4964. }
  4965. },
  4966. query: query
  4967. };
  4968. }
  4969. var highlightTimeout = 0;
  4970. /** @arg {CodeMirrorV} cm @arg {RegExp} query */
  4971. function highlightSearchMatches(cm, query) {
  4972. clearTimeout(highlightTimeout);
  4973. var searchState = getSearchState(cm);
  4974. searchState.highlightTimeout = highlightTimeout;
  4975. highlightTimeout = setTimeout(function() {
  4976. if (!cm.state.vim) return;
  4977. var searchState = getSearchState(cm);
  4978. searchState.highlightTimeout = null;
  4979. var overlay = searchState.getOverlay();
  4980. if (!overlay || query != overlay.query) {
  4981. if (overlay) {
  4982. cm.removeOverlay(overlay);
  4983. }
  4984. overlay = searchOverlay(query);
  4985. cm.addOverlay(overlay);
  4986. if (cm.showMatchesOnScrollbar) {
  4987. if (searchState.getScrollbarAnnotate()) {
  4988. searchState.getScrollbarAnnotate().clear();
  4989. }
  4990. searchState.setScrollbarAnnotate(cm.showMatchesOnScrollbar(query));
  4991. }
  4992. searchState.setOverlay(overlay);
  4993. }
  4994. }, 50);
  4995. }
  4996. /** @arg {CodeMirror} cm @arg {boolean} prev @arg {RegExp} query @arg {number | undefined} [repeat] */
  4997. function findNext(cm, prev, query, repeat) {
  4998. return cm.operation(function() {
  4999. if (repeat === undefined) { repeat = 1; }
  5000. var pos = cm.getCursor();
  5001. var cursor = cm.getSearchCursor(query, pos);
  5002. for (var i = 0; i < repeat; i++) {
  5003. var found = cursor.find(prev);
  5004. // @ts-ignore
  5005. if (i == 0 && found && cursorEqual(cursor.from(), pos)) {
  5006. var lastEndPos = prev ? cursor.from() : cursor.to();
  5007. found = cursor.find(prev);
  5008. // @ts-ignore
  5009. if (found && !found[0] && cursorEqual(cursor.from(), lastEndPos)) {
  5010. // @ts-ignore
  5011. if (cm.getLine(lastEndPos.line).length == lastEndPos.ch)
  5012. found = cursor.find(prev);
  5013. }
  5014. }
  5015. if (!found) {
  5016. // SearchCursor may have returned null because it hit EOF, wrap
  5017. // around and try again.
  5018. cursor = cm.getSearchCursor(query,
  5019. // @ts-ignore
  5020. (prev) ? new Pos(cm.lastLine()) : new Pos(cm.firstLine(), 0) );
  5021. if (!cursor.find(prev)) {
  5022. return;
  5023. }
  5024. }
  5025. }
  5026. return cursor.from();
  5027. });
  5028. }
  5029. /**
  5030. * Pretty much the same as `findNext`, except for the following differences:
  5031. *
  5032. * 1. Before starting the search, move to the previous search. This way if our cursor is
  5033. * already inside a match, we should return the current match.
  5034. * 2. Rather than only returning the cursor's from, we return the cursor's from and to as a tuple.
  5035. * @arg {CodeMirror} cm
  5036. * @arg {boolean} prev
  5037. * @arg {any} query
  5038. * @arg {number | undefined} repeat
  5039. * @arg {vimState} vim
  5040. */
  5041. function findNextFromAndToInclusive(cm, prev, query, repeat, vim) {
  5042. return cm.operation(function() {
  5043. if (repeat === undefined) { repeat = 1; }
  5044. var pos = cm.getCursor();
  5045. var cursor = cm.getSearchCursor(query, pos);
  5046. // Go back one result to ensure that if the cursor is currently a match, we keep it.
  5047. var found = cursor.find(!prev);
  5048. // If we haven't moved, go back one more (similar to if i==0 logic in findNext).
  5049. // @ts-ignore
  5050. if (!vim.visualMode && found && cursorEqual(cursor.from(), pos)) {
  5051. cursor.find(!prev);
  5052. }
  5053. for (var i = 0; i < repeat; i++) {
  5054. found = cursor.find(prev);
  5055. if (!found) {
  5056. // SearchCursor may have returned null because it hit EOF, wrap
  5057. // around and try again.
  5058. cursor = cm.getSearchCursor(query,
  5059. // @ts-ignore
  5060. (prev) ? new Pos(cm.lastLine()) : new Pos(cm.firstLine(), 0) );
  5061. if (!cursor.find(prev)) {
  5062. return;
  5063. }
  5064. }
  5065. }
  5066. return [cursor.from(), cursor.to()];
  5067. });
  5068. }
  5069. /** @arg {CodeMirrorV} cm */
  5070. function clearSearchHighlight(cm) {
  5071. var state = getSearchState(cm);
  5072. if (state.highlightTimeout) {
  5073. clearTimeout(state.highlightTimeout);
  5074. state.highlightTimeout = null;
  5075. }
  5076. cm.removeOverlay(getSearchState(cm).getOverlay());
  5077. state.setOverlay(null);
  5078. if (state.getScrollbarAnnotate()) {
  5079. state.getScrollbarAnnotate().clear();
  5080. state.setScrollbarAnnotate(null);
  5081. }
  5082. }
  5083. /**
  5084. * Check if pos is in the specified range, INCLUSIVE.
  5085. * Range can be specified with 1 or 2 arguments.
  5086. * If the first range argument is an array, treat it as an array of line
  5087. * numbers. Match pos against any of the lines.
  5088. * If the first range argument is a number,
  5089. * if there is only 1 range argument, check if pos has the same line
  5090. * number
  5091. * if there are 2 range arguments, then check if pos is in between the two
  5092. * range arguments.
  5093. * @arg {number|Pos} pos
  5094. * @arg {number|number[]} start
  5095. * @arg {number} end
  5096. */
  5097. function isInRange(pos, start, end) {
  5098. if (typeof pos != 'number') {
  5099. // Assume it is a cursor position. Get the line number.
  5100. pos = pos.line;
  5101. }
  5102. if (start instanceof Array) {
  5103. return inArray(pos, start);
  5104. } else {
  5105. if (typeof end == 'number') {
  5106. return (pos >= start && pos <= end);
  5107. } else {
  5108. return pos == start;
  5109. }
  5110. }
  5111. }
  5112. /** @arg {CodeMirror} cm */
  5113. function getUserVisibleLines(cm) {
  5114. var scrollInfo = cm.getScrollInfo();
  5115. var occludeToleranceTop = 6;
  5116. var occludeToleranceBottom = 10;
  5117. var from = cm.coordsChar({left:0, top: occludeToleranceTop + scrollInfo.top}, 'local');
  5118. var bottomY = scrollInfo.clientHeight - occludeToleranceBottom + scrollInfo.top;
  5119. var to = cm.coordsChar({left:0, top: bottomY}, 'local');
  5120. return {top: from.line, bottom: to.line};
  5121. }
  5122. /** @arg {CodeMirror} cm @arg {vimState} vim @arg {string} markName */
  5123. function getMarkPos(cm, vim, markName) {
  5124. if (markName == '\'' || markName == '`') {
  5125. return vimGlobalState.jumpList.find(cm, -1) || new Pos(0, 0);
  5126. } else if (markName == '.') {
  5127. return getLastEditPos(cm);
  5128. }
  5129. var mark = vim.marks[markName];
  5130. return mark && mark.find();
  5131. }
  5132. /** @arg {CodeMirror} cm */
  5133. function getLastEditPos(cm) {
  5134. if (cm.getLastEditEnd) {
  5135. return cm.getLastEditEnd();
  5136. }
  5137. // for old cm
  5138. var done = /**@type{any}*/(cm).doc.history.done;
  5139. for (var i = done.length; i--;) {
  5140. if (done[i].changes) {
  5141. return copyCursor(done[i].changes[0].to);
  5142. }
  5143. }
  5144. }
  5145. class ExCommandDispatcher {
  5146. constructor() {
  5147. /**@type {Record<string, any>} */
  5148. this.commandMap_
  5149. this.buildCommandMap_();
  5150. }
  5151. processCommand(cm, input, opt_params) {
  5152. var that = this;
  5153. cm.operation(function () {
  5154. cm.curOp.isVimOp = true;
  5155. that._processCommand(cm, input, opt_params);
  5156. });
  5157. }
  5158. _processCommand(cm, input, opt_params) {
  5159. var vim = cm.state.vim;
  5160. var commandHistoryRegister = vimGlobalState.registerController.getRegister(':');
  5161. var previousCommand = commandHistoryRegister.toString();
  5162. var inputStream = new CodeMirror.StringStream(input);
  5163. // update ": with the latest command whether valid or invalid
  5164. commandHistoryRegister.setText(input);
  5165. var params = opt_params || {};
  5166. params.input = input;
  5167. try {
  5168. this.parseInput_(cm, inputStream, params);
  5169. } catch(e) {
  5170. showConfirm(cm, e + "");
  5171. throw e;
  5172. }
  5173. if (vim.visualMode) {
  5174. exitVisualMode(cm);
  5175. }
  5176. var command;
  5177. var commandName;
  5178. if (!params.commandName) {
  5179. // If only a line range is defined, move to the line.
  5180. if (params.line !== undefined) {
  5181. commandName = 'move';
  5182. }
  5183. } else {
  5184. command = this.matchCommand_(params.commandName);
  5185. if (command) {
  5186. commandName = command.name;
  5187. if (command.excludeFromCommandHistory) {
  5188. commandHistoryRegister.setText(previousCommand);
  5189. }
  5190. this.parseCommandArgs_(inputStream, params, command);
  5191. if (command.type == 'exToKey') {
  5192. // Handle Ex to Key mapping.
  5193. doKeyToKey(cm, command.toKeys, command);
  5194. return;
  5195. } else if (command.type == 'exToEx') {
  5196. // Handle Ex to Ex mapping.
  5197. this.processCommand(cm, command.toInput);
  5198. return;
  5199. }
  5200. }
  5201. }
  5202. if (!commandName) {
  5203. showConfirm(cm, 'Not an editor command ":' + input + '"');
  5204. return;
  5205. }
  5206. try {
  5207. exCommands[commandName](cm, params);
  5208. // Possibly asynchronous commands (e.g. substitute, which might have a
  5209. // user confirmation), are responsible for calling the callback when
  5210. // done. All others have it taken care of for them here.
  5211. if ((!command || !command.possiblyAsync) && params.callback) {
  5212. params.callback();
  5213. }
  5214. } catch(e) {
  5215. showConfirm(cm, e + "");
  5216. throw e;
  5217. }
  5218. }
  5219. parseInput_(cm, inputStream, result) {
  5220. inputStream.eatWhile(':');
  5221. // Parse range.
  5222. if (inputStream.eat('%')) {
  5223. result.line = cm.firstLine();
  5224. result.lineEnd = cm.lastLine();
  5225. } else {
  5226. result.line = this.parseLineSpec_(cm, inputStream);
  5227. if (result.line !== undefined && inputStream.eat(',')) {
  5228. result.lineEnd = this.parseLineSpec_(cm, inputStream);
  5229. }
  5230. }
  5231. if (result.line == undefined) {
  5232. if (cm.state.vim.visualMode) {
  5233. result.selectionLine = getMarkPos(cm, cm.state.vim, '<')?.line;
  5234. result.selectionLineEnd = getMarkPos(cm, cm.state.vim, '>')?.line;
  5235. } else {
  5236. result.selectionLine = cm.getCursor().line;
  5237. }
  5238. } else {
  5239. result.selectionLine = result.line;
  5240. result.selectionLineEnd = result.lineEnd;
  5241. }
  5242. // Parse command name.
  5243. var commandMatch = inputStream.match(/^(\w+|!!|@@|[!#&*<=>@~])/);
  5244. if (commandMatch) {
  5245. result.commandName = commandMatch[1];
  5246. } else {
  5247. result.commandName = inputStream.match(/.*/)[0];
  5248. }
  5249. return result;
  5250. }
  5251. parseLineSpec_(cm, inputStream) {
  5252. var numberMatch = inputStream.match(/^(\d+)/);
  5253. if (numberMatch) {
  5254. // Absolute line number plus offset (N+M or N-M) is probably a typo,
  5255. // not something the user actually wanted. (NB: vim does allow this.)
  5256. return parseInt(numberMatch[1], 10) - 1;
  5257. }
  5258. switch (inputStream.next()) {
  5259. case '.':
  5260. return this.parseLineSpecOffset_(inputStream, cm.getCursor().line);
  5261. case '$':
  5262. return this.parseLineSpecOffset_(inputStream, cm.lastLine());
  5263. case '\'':
  5264. var markName = inputStream.next();
  5265. var markPos = getMarkPos(cm, cm.state.vim, markName);
  5266. if (!markPos) throw new Error('Mark not set');
  5267. return this.parseLineSpecOffset_(inputStream, markPos.line);
  5268. case '-':
  5269. case '+':
  5270. inputStream.backUp(1);
  5271. // Offset is relative to current line if not otherwise specified.
  5272. return this.parseLineSpecOffset_(inputStream, cm.getCursor().line);
  5273. default:
  5274. inputStream.backUp(1);
  5275. return undefined;
  5276. }
  5277. }
  5278. parseLineSpecOffset_(inputStream, line) {
  5279. var offsetMatch = inputStream.match(/^([+-])?(\d+)/);
  5280. if (offsetMatch) {
  5281. var offset = parseInt(offsetMatch[2], 10);
  5282. if (offsetMatch[1] == "-") {
  5283. line -= offset;
  5284. } else {
  5285. line += offset;
  5286. }
  5287. }
  5288. return line;
  5289. }
  5290. parseCommandArgs_(inputStream, params, command) {
  5291. if (inputStream.eol()) {
  5292. return;
  5293. }
  5294. params.argString = inputStream.match(/.*/)[0];
  5295. // Parse command-line arguments
  5296. var delim = command.argDelimiter || /\s+/;
  5297. var args = trim(params.argString).split(delim);
  5298. if (args.length && args[0]) {
  5299. params.args = args;
  5300. }
  5301. }
  5302. matchCommand_(commandName) {
  5303. // Return the command in the command map that matches the shortest
  5304. // prefix of the passed in command name. The match is guaranteed to be
  5305. // unambiguous if the defaultExCommandMap's shortNames are set up
  5306. // correctly. (see @code{defaultExCommandMap}).
  5307. for (var i = commandName.length; i > 0; i--) {
  5308. var prefix = commandName.substring(0, i);
  5309. if (this.commandMap_[prefix]) {
  5310. var command = this.commandMap_[prefix];
  5311. if (command.name.indexOf(commandName) === 0) {
  5312. return command;
  5313. }
  5314. }
  5315. }
  5316. return null;
  5317. }
  5318. buildCommandMap_() {
  5319. this.commandMap_ = {};
  5320. for (var i = 0; i < defaultExCommandMap.length; i++) {
  5321. var command = defaultExCommandMap[i];
  5322. var key = command.shortName || command.name;
  5323. this.commandMap_[key] = command;
  5324. }
  5325. }
  5326. /**@type {(lhs: string, rhs: string, ctx: string, noremap?: boolean) => void} */
  5327. map(lhs, rhs, ctx, noremap) {
  5328. if (lhs != ':' && lhs.charAt(0) == ':') {
  5329. if (ctx) { throw Error('Mode not supported for ex mappings'); }
  5330. var commandName = lhs.substring(1);
  5331. if (rhs != ':' && rhs.charAt(0) == ':') {
  5332. // Ex to Ex mapping
  5333. this.commandMap_[commandName] = {
  5334. name: commandName,
  5335. type: 'exToEx',
  5336. toInput: rhs.substring(1),
  5337. user: true
  5338. };
  5339. } else {
  5340. // Ex to key mapping
  5341. this.commandMap_[commandName] = {
  5342. name: commandName,
  5343. type: 'exToKey',
  5344. toKeys: rhs,
  5345. user: true
  5346. };
  5347. }
  5348. } else {
  5349. // Key to key or ex mapping
  5350. var mapping = {
  5351. keys: lhs,
  5352. type: 'keyToKey',
  5353. toKeys: rhs,
  5354. noremap: !!noremap
  5355. };
  5356. if (ctx) { mapping.context = ctx; }
  5357. // @ts-ignore
  5358. defaultKeymap.unshift(mapping);
  5359. }
  5360. }
  5361. /**@type {(lhs: string, ctx: string) => boolean|void} */
  5362. unmap(lhs, ctx) {
  5363. if (lhs != ':' && lhs.charAt(0) == ':') {
  5364. // Ex to Ex or Ex to key mapping
  5365. if (ctx) { throw Error('Mode not supported for ex mappings'); }
  5366. var commandName = lhs.substring(1);
  5367. if (this.commandMap_[commandName] && this.commandMap_[commandName].user) {
  5368. delete this.commandMap_[commandName];
  5369. return true;
  5370. }
  5371. } else {
  5372. // Key to Ex or key to key mapping
  5373. var keys = lhs;
  5374. for (var i = 0; i < defaultKeymap.length; i++) {
  5375. if (keys == defaultKeymap[i].keys
  5376. && defaultKeymap[i].context === ctx) {
  5377. defaultKeymap.splice(i, 1);
  5378. return true;
  5379. }
  5380. }
  5381. }
  5382. }
  5383. }
  5384. /** @typedef { import("./types").ExParams} ExParams */
  5385. var exCommands = {
  5386. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5387. colorscheme: function(cm, params) {
  5388. if (!params.args || params.args.length < 1) {
  5389. showConfirm(cm, cm.getOption('theme'));
  5390. return;
  5391. }
  5392. cm.setOption('theme', params.args[0]);
  5393. },
  5394. map: function(cm, params, ctx, defaultOnly) {
  5395. var mapArgs = params.args;
  5396. if (!mapArgs || mapArgs.length < 2) {
  5397. if (cm) {
  5398. showConfirm(cm, 'Invalid mapping: ' + params.input);
  5399. }
  5400. return;
  5401. }
  5402. exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx, defaultOnly);
  5403. },
  5404. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5405. imap: function(cm, params) { this.map(cm, params, 'insert'); },
  5406. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5407. nmap: function(cm, params) { this.map(cm, params, 'normal'); },
  5408. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5409. vmap: function(cm, params) { this.map(cm, params, 'visual'); },
  5410. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5411. omap: function(cm, params) { this.map(cm, params, 'operatorPending'); },
  5412. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5413. noremap: function(cm, params) { this.map(cm, params, undefined, true); },
  5414. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5415. inoremap: function(cm, params) { this.map(cm, params, 'insert', true); },
  5416. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5417. nnoremap: function(cm, params) { this.map(cm, params, 'normal', true); },
  5418. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5419. vnoremap: function(cm, params) { this.map(cm, params, 'visual', true); },
  5420. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5421. onoremap: function(cm, params) { this.map(cm, params, 'operatorPending', true); },
  5422. /** @arg {CodeMirrorV} cm @arg {ExParams} params @arg {string} ctx*/
  5423. unmap: function(cm, params, ctx) {
  5424. var mapArgs = params.args;
  5425. if (!mapArgs || mapArgs.length < 1 || !exCommandDispatcher.unmap(mapArgs[0], ctx)) {
  5426. if (cm) {
  5427. showConfirm(cm, 'No such mapping: ' + params.input);
  5428. }
  5429. }
  5430. },
  5431. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5432. mapclear: function(cm, params) { vimApi.mapclear(); },
  5433. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5434. imapclear: function(cm, params) { vimApi.mapclear('insert'); },
  5435. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5436. nmapclear: function(cm, params) { vimApi.mapclear('normal'); },
  5437. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5438. vmapclear: function(cm, params) { vimApi.mapclear('visual'); },
  5439. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5440. omapclear: function(cm, params) { vimApi.mapclear('operatorPending'); },
  5441. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5442. move: function(cm, params) {
  5443. commandDispatcher.processCommand(cm, cm.state.vim, {
  5444. keys: "",
  5445. type: 'motion',
  5446. motion: 'moveToLineOrEdgeOfDocument',
  5447. motionArgs: { forward: false, explicitRepeat: true, linewise: true },
  5448. repeatOverride: params.line+1
  5449. });
  5450. },
  5451. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5452. set: function(cm, params) {
  5453. var setArgs = params.args;
  5454. // Options passed through to the setOption/getOption calls. May be passed in by the
  5455. // local/global versions of the set command
  5456. var setCfg = params.setCfg || {};
  5457. if (!setArgs || setArgs.length < 1) {
  5458. if (cm) {
  5459. showConfirm(cm, 'Invalid mapping: ' + params.input);
  5460. }
  5461. return;
  5462. }
  5463. var expr = setArgs[0].split('=');
  5464. var optionName = expr.shift() || "";
  5465. /**@type {string|boolean|undefined} */
  5466. var value = expr.length > 0 ? expr.join('=') : undefined;
  5467. var forceGet = false;
  5468. var forceToggle = false;
  5469. if (optionName.charAt(optionName.length - 1) == '?') {
  5470. // If post-fixed with ?, then the set is actually a get.
  5471. if (value) { throw Error('Trailing characters: ' + params.argString); }
  5472. optionName = optionName.substring(0, optionName.length - 1);
  5473. forceGet = true;
  5474. } else if (optionName.charAt(optionName.length - 1) == '!') {
  5475. optionName = optionName.substring(0, optionName.length - 1);
  5476. forceToggle = true;
  5477. }
  5478. if (value === undefined && optionName.substring(0, 2) == 'no') {
  5479. // To set boolean options to false, the option name is prefixed with
  5480. // 'no'.
  5481. optionName = optionName.substring(2);
  5482. value = false;
  5483. }
  5484. var optionIsBoolean = options[optionName] && options[optionName].type == 'boolean';
  5485. if (optionIsBoolean) {
  5486. if (forceToggle) {
  5487. value = !getOption(optionName, cm, setCfg);
  5488. } else if (value == undefined) {
  5489. // Calling set with a boolean option sets it to true.
  5490. value = true;
  5491. }
  5492. }
  5493. // If no value is provided, then we assume this is a get.
  5494. if (!optionIsBoolean && value === undefined || forceGet) {
  5495. var oldValue = getOption(optionName, cm, setCfg);
  5496. if (oldValue instanceof Error) {
  5497. showConfirm(cm, oldValue.message);
  5498. } else if (oldValue === true || oldValue === false) {
  5499. showConfirm(cm, ' ' + (oldValue ? '' : 'no') + optionName);
  5500. } else {
  5501. showConfirm(cm, ' ' + optionName + '=' + oldValue);
  5502. }
  5503. } else {
  5504. var setOptionReturn = setOption(optionName, value, cm, setCfg);
  5505. if (setOptionReturn instanceof Error) {
  5506. showConfirm(cm, setOptionReturn.message);
  5507. }
  5508. }
  5509. },
  5510. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5511. setlocal: function (cm, params) {
  5512. // setCfg is passed through to setOption
  5513. params.setCfg = {scope: 'local'};
  5514. this.set(cm, params);
  5515. },
  5516. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5517. setglobal: function (cm, params) {
  5518. // setCfg is passed through to setOption
  5519. params.setCfg = {scope: 'global'};
  5520. this.set(cm, params);
  5521. },
  5522. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5523. registers: function(cm, params) {
  5524. var regArgs = params.args;
  5525. var registers = vimGlobalState.registerController.registers;
  5526. var regInfo = '----------Registers----------\n\n';
  5527. if (!regArgs) {
  5528. for (var registerName in registers) {
  5529. var text = registers[registerName].toString();
  5530. if (text.length) {
  5531. regInfo += '"' + registerName + ' ' + text + '\n'
  5532. }
  5533. }
  5534. } else {
  5535. var registerNames = regArgs.join('');
  5536. for (var i = 0; i < registerNames.length; i++) {
  5537. var registerName = registerNames.charAt(i);
  5538. if (!vimGlobalState.registerController.isValidRegister(registerName)) {
  5539. continue;
  5540. }
  5541. var register = registers[registerName] || new Register();
  5542. regInfo += '"' + registerName + ' ' + register.toString() + '\n'
  5543. }
  5544. }
  5545. showConfirm(cm, regInfo);
  5546. },
  5547. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5548. sort: function(cm, params) {
  5549. var reverse, ignoreCase, unique, number, pattern;
  5550. function parseArgs() {
  5551. if (params.argString) {
  5552. var args = new CodeMirror.StringStream(params.argString);
  5553. if (args.eat('!')) { reverse = true; }
  5554. if (args.eol()) { return; }
  5555. if (!args.eatSpace()) { return 'Invalid arguments'; }
  5556. var opts = args.match(/([dinuox]+)?\s*(\/.+\/)?\s*/);
  5557. if (!opts || !args.eol()) { return 'Invalid arguments'; }
  5558. if (opts[1]) {
  5559. ignoreCase = opts[1].indexOf('i') != -1;
  5560. unique = opts[1].indexOf('u') != -1;
  5561. var decimal = opts[1].indexOf('d') != -1 || opts[1].indexOf('n') != -1;
  5562. var hex = opts[1].indexOf('x') != -1;
  5563. var octal = opts[1].indexOf('o') != -1;
  5564. if (Number(decimal) + Number(hex) + Number(octal) > 1) { return 'Invalid arguments'; }
  5565. number = decimal && 'decimal' || hex && 'hex' || octal && 'octal';
  5566. }
  5567. if (opts[2]) {
  5568. pattern = new RegExp(opts[2].substr(1, opts[2].length - 2), ignoreCase ? 'i' : '');
  5569. }
  5570. }
  5571. }
  5572. var err = parseArgs();
  5573. if (err) {
  5574. showConfirm(cm, err + ': ' + params.argString);
  5575. return;
  5576. }
  5577. var lineStart = params.line || cm.firstLine();
  5578. var lineEnd = params.lineEnd || params.line || cm.lastLine();
  5579. if (lineStart == lineEnd) { return; }
  5580. var curStart = new Pos(lineStart, 0);
  5581. var curEnd = new Pos(lineEnd, lineLength(cm, lineEnd));
  5582. var text = cm.getRange(curStart, curEnd).split('\n');
  5583. var numberRegex =
  5584. (number == 'decimal') ? /(-?)([\d]+)/ :
  5585. (number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i :
  5586. (number == 'octal') ? /([0-7]+)/ : null;
  5587. var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : undefined;
  5588. var numPart = [], textPart = [];
  5589. if (number || pattern) {
  5590. for (var i = 0; i < text.length; i++) {
  5591. var matchPart = pattern ? text[i].match(pattern) : null;
  5592. if (matchPart && matchPart[0] != '') {
  5593. numPart.push(matchPart);
  5594. } else if (numberRegex && numberRegex.exec(text[i])) {
  5595. numPart.push(text[i]);
  5596. } else {
  5597. textPart.push(text[i]);
  5598. }
  5599. }
  5600. } else {
  5601. textPart = text;
  5602. }
  5603. /** @arg {string} a @arg {string} b */
  5604. function compareFn(a, b) {
  5605. if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
  5606. if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); }
  5607. var amatch = numberRegex && numberRegex.exec(a);
  5608. var bmatch = numberRegex && numberRegex.exec(b);
  5609. if (!amatch || !bmatch) { return a < b ? -1 : 1; }
  5610. var anum = parseInt((amatch[1] + amatch[2]).toLowerCase(), radix);
  5611. var bnum = parseInt((bmatch[1] + bmatch[2]).toLowerCase(), radix);
  5612. return anum - bnum;
  5613. }
  5614. /** @arg {string[]} a @arg {string[]} b */
  5615. function comparePatternFn(a, b) {
  5616. if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
  5617. if (ignoreCase) { a[0] = a[0].toLowerCase(); b[0] = b[0].toLowerCase(); }
  5618. return (a[0] < b[0]) ? -1 : 1;
  5619. }
  5620. // @ts-ignore
  5621. numPart.sort(pattern ? comparePatternFn : compareFn);
  5622. if (pattern) {
  5623. for (var i = 0; i < numPart.length; i++) {
  5624. // @ts-ignore
  5625. numPart[i] = numPart[i].input;
  5626. }
  5627. } else if (!number) { textPart.sort(compareFn); }
  5628. text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart);
  5629. if (unique) { // Remove duplicate lines
  5630. var textOld = text;
  5631. var lastLine;
  5632. text = [];
  5633. for (var i = 0; i < textOld.length; i++) {
  5634. if (textOld[i] != lastLine) {
  5635. text.push(textOld[i]);
  5636. }
  5637. lastLine = textOld[i];
  5638. }
  5639. }
  5640. cm.replaceRange(text.join('\n'), curStart, curEnd);
  5641. },
  5642. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5643. vglobal: function(cm, params) {
  5644. // global inspects params.commandName
  5645. this.global(cm, params);
  5646. },
  5647. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5648. normal: function(cm, params) {
  5649. var argString = params.argString;
  5650. if (argString && argString[0] == '!') {
  5651. argString = argString.slice(1);
  5652. noremap = true;
  5653. }
  5654. argString = argString.trimStart();
  5655. if (!argString) {
  5656. showConfirm(cm, 'Argument is required.');
  5657. return;
  5658. }
  5659. var line = params.line;
  5660. if (typeof line == 'number') {
  5661. var lineEnd = isNaN(params.lineEnd) ? line : params.lineEnd;
  5662. for (var i = line; i <= lineEnd; i++) {
  5663. cm.setCursor(i, 0);
  5664. doKeyToKey(cm, params.argString.trimStart());
  5665. if (cm.state.vim.insertMode) {
  5666. exitInsertMode(cm, true);
  5667. }
  5668. }
  5669. } else {
  5670. doKeyToKey(cm, params.argString.trimStart());
  5671. if (cm.state.vim.insertMode) {
  5672. exitInsertMode(cm, true);
  5673. }
  5674. }
  5675. },
  5676. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5677. global: function(cm, params) {
  5678. // a global command is of the form
  5679. // :[range]g/pattern/[cmd]
  5680. // argString holds the string /pattern/[cmd]
  5681. var argString = params.argString;
  5682. if (!argString) {
  5683. showConfirm(cm, 'Regular Expression missing from global');
  5684. return;
  5685. }
  5686. var inverted = params.commandName[0] === 'v';
  5687. if (argString[0] === '!' && params.commandName[0] === 'g') {
  5688. inverted = true;
  5689. argString = argString.slice(1);
  5690. }
  5691. // range is specified here
  5692. var lineStart = (params.line !== undefined) ? params.line : cm.firstLine();
  5693. var lineEnd = params.lineEnd || params.line || cm.lastLine();
  5694. // get the tokens from argString
  5695. var tokens = splitBySlash(argString);
  5696. var regexPart = argString, cmd = "";
  5697. if (tokens && tokens.length) {
  5698. regexPart = tokens[0];
  5699. cmd = tokens.slice(1, tokens.length).join('/');
  5700. }
  5701. if (regexPart) {
  5702. // If regex part is empty, then use the previous query. Otherwise
  5703. // use the regex part as the new query.
  5704. try {
  5705. updateSearchQuery(cm, regexPart, true /** ignoreCase */,
  5706. true /** smartCase */);
  5707. } catch (e) {
  5708. showConfirm(cm, 'Invalid regex: ' + regexPart);
  5709. return;
  5710. }
  5711. }
  5712. // now that we have the regexPart, search for regex matches in the
  5713. // specified range of lines
  5714. var query = getSearchState(cm).getQuery();
  5715. /**@type {(string|import("./types").LineHandle)[]}*/
  5716. var matchedLines = [];
  5717. for (var i = lineStart; i <= lineEnd; i++) {
  5718. var line = cm.getLine(i);
  5719. var matched = query.test(line);
  5720. if (matched !== inverted) {
  5721. matchedLines.push(cmd ? cm.getLineHandle(i) : line);
  5722. }
  5723. }
  5724. // if there is no [cmd], just display the list of matched lines
  5725. if (!cmd) {
  5726. showConfirm(cm, matchedLines.join('\n'));
  5727. return;
  5728. }
  5729. var index = 0;
  5730. var nextCommand = function() {
  5731. if (index < matchedLines.length) {
  5732. var lineHandle = matchedLines[index++];
  5733. var lineNum = cm.getLineNumber(lineHandle);
  5734. if (lineNum == null) {
  5735. nextCommand();
  5736. return;
  5737. }
  5738. var command = (lineNum + 1) + cmd;
  5739. exCommandDispatcher.processCommand(cm, command, {
  5740. callback: nextCommand
  5741. });
  5742. } else if (cm.releaseLineHandles) {
  5743. cm.releaseLineHandles();
  5744. }
  5745. };
  5746. nextCommand();
  5747. },
  5748. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5749. substitute: function(cm, params) {
  5750. if (!cm.getSearchCursor) {
  5751. throw new Error('Search feature not available. Requires searchcursor.js or ' +
  5752. 'any other getSearchCursor implementation.');
  5753. }
  5754. var argString = params.argString;
  5755. var tokens = argString ? splitBySeparator(argString, argString[0]) : [];
  5756. var regexPart = '', replacePart = '', trailing, flagsPart, count;
  5757. var confirm = false; // Whether to confirm each replace.
  5758. var global = false; // True to replace all instances on a line, false to replace only 1.
  5759. if (tokens && tokens.length) {
  5760. regexPart = tokens[0];
  5761. if (getOption('pcre') && regexPart !== '') {
  5762. regexPart = new RegExp(regexPart).source; //normalize not escaped characters
  5763. }
  5764. replacePart = tokens[1];
  5765. if (replacePart !== undefined) {
  5766. if (getOption('pcre')) {
  5767. replacePart = unescapeRegexReplace(replacePart.replace(/([^\\])&/g,"$1$$&"));
  5768. } else {
  5769. replacePart = translateRegexReplace(replacePart);
  5770. }
  5771. vimGlobalState.lastSubstituteReplacePart = replacePart;
  5772. }
  5773. trailing = tokens[2] ? tokens[2].split(' ') : [];
  5774. } else {
  5775. // either the argString is empty or its of the form ' hello/world'
  5776. // actually splitBySlash returns a list of tokens
  5777. // only if the string starts with a '/'
  5778. if (argString && argString.length) {
  5779. showConfirm(cm, 'Substitutions should be of the form ' +
  5780. ':s/pattern/replace/');
  5781. return;
  5782. }
  5783. }
  5784. // After the 3rd slash, we can have flags followed by a space followed
  5785. // by count.
  5786. if (trailing) {
  5787. flagsPart = trailing[0];
  5788. count = parseInt(trailing[1]);
  5789. if (flagsPart) {
  5790. if (flagsPart.indexOf('c') != -1) {
  5791. confirm = true;
  5792. }
  5793. if (flagsPart.indexOf('g') != -1) {
  5794. global = true;
  5795. }
  5796. if (getOption('pcre')) {
  5797. regexPart = regexPart + '/' + flagsPart;
  5798. } else {
  5799. regexPart = regexPart.replace(/\//g, "\\/") + '/' + flagsPart;
  5800. }
  5801. }
  5802. }
  5803. if (regexPart) {
  5804. // If regex part is empty, then use the previous query. Otherwise use
  5805. // the regex part as the new query.
  5806. try {
  5807. updateSearchQuery(cm, regexPart, true /** ignoreCase */,
  5808. true /** smartCase */);
  5809. } catch (e) {
  5810. showConfirm(cm, 'Invalid regex: ' + regexPart);
  5811. return;
  5812. }
  5813. }
  5814. replacePart = replacePart || vimGlobalState.lastSubstituteReplacePart;
  5815. if (replacePart === undefined) {
  5816. showConfirm(cm, 'No previous substitute regular expression');
  5817. return;
  5818. }
  5819. var state = getSearchState(cm);
  5820. var query = state.getQuery();
  5821. var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line;
  5822. var lineEnd = params.lineEnd || lineStart;
  5823. if (lineStart == cm.firstLine() && lineEnd == cm.lastLine()) {
  5824. lineEnd = Infinity;
  5825. }
  5826. if (count) {
  5827. lineStart = lineEnd;
  5828. lineEnd = lineStart + count - 1;
  5829. }
  5830. var startPos = clipCursorToContent(cm, new Pos(lineStart, 0));
  5831. var cursor = cm.getSearchCursor(query, startPos);
  5832. doReplace(cm, confirm, global, lineStart, lineEnd, cursor, query, replacePart, params.callback);
  5833. },
  5834. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5835. startinsert: function(cm, params) {
  5836. doKeyToKey(cm, params.argString == '!' ? 'A' : 'i', {});
  5837. },
  5838. redo: CodeMirror.commands.redo,
  5839. undo: CodeMirror.commands.undo,
  5840. /** @arg {CodeMirrorV} cm */
  5841. write: function(cm) {
  5842. if (CodeMirror.commands.save) {
  5843. CodeMirror.commands.save(cm);
  5844. } else if (cm.save) {
  5845. // Saves to text area if no save command is defined and cm.save() is available.
  5846. cm.save();
  5847. }
  5848. },
  5849. /** @arg {CodeMirrorV} cm */
  5850. nohlsearch: function(cm) {
  5851. clearSearchHighlight(cm);
  5852. },
  5853. /** @arg {CodeMirrorV} cm */
  5854. yank: function (cm) {
  5855. var cur = copyCursor(cm.getCursor());
  5856. var line = cur.line;
  5857. var lineText = cm.getLine(line);
  5858. vimGlobalState.registerController.pushText(
  5859. '0', 'yank', lineText, true, true);
  5860. },
  5861. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5862. delete: function(cm, params) {
  5863. var line = params.selectionLine;
  5864. var lineEnd = isNaN(params.selectionLineEnd) ? line : params.selectionLineEnd;
  5865. operators.delete(cm, {linewise: true}, [
  5866. { anchor: new Pos(line, 0),
  5867. head: new Pos(lineEnd + 1, 0) }
  5868. ]);
  5869. },
  5870. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5871. join: function(cm, params) {
  5872. var line = params.selectionLine;
  5873. var lineEnd = isNaN(params.selectionLineEnd) ? line : params.selectionLineEnd;
  5874. cm.setCursor(new Pos(line, 0));
  5875. actions.joinLines(cm, {repeat: lineEnd - line}, cm.state.vim);
  5876. },
  5877. /** @arg {CodeMirrorV} cm @arg {ExParams} params*/
  5878. delmarks: function(cm, params) {
  5879. if (!params.argString || !trim(params.argString)) {
  5880. showConfirm(cm, 'Argument required');
  5881. return;
  5882. }
  5883. var state = cm.state.vim;
  5884. var stream = new CodeMirror.StringStream(trim(params.argString));
  5885. while (!stream.eol()) {
  5886. stream.eatSpace();
  5887. // Record the streams position at the beginning of the loop for use
  5888. // in error messages.
  5889. var count = stream.pos;
  5890. if (!stream.match(/[a-zA-Z]/, false)) {
  5891. showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
  5892. return;
  5893. }
  5894. var sym = stream.next();
  5895. // Check if this symbol is part of a range
  5896. if (stream.match('-', true)) {
  5897. // This symbol is part of a range.
  5898. // The range must terminate at an alphabetic character.
  5899. if (!stream.match(/[a-zA-Z]/, false)) {
  5900. showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
  5901. return;
  5902. }
  5903. var startMark = sym;
  5904. var finishMark = stream.next();
  5905. // The range must terminate at an alphabetic character which
  5906. // shares the same case as the start of the range.
  5907. if (startMark && finishMark && isLowerCase(startMark) == isLowerCase(finishMark)) {
  5908. var start = startMark.charCodeAt(0);
  5909. var finish = finishMark.charCodeAt(0);
  5910. if (start >= finish) {
  5911. showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
  5912. return;
  5913. }
  5914. // Because marks are always ASCII values, and we have
  5915. // determined that they are the same case, we can use
  5916. // their char codes to iterate through the defined range.
  5917. for (var j = 0; j <= finish - start; j++) {
  5918. var mark = String.fromCharCode(start + j);
  5919. delete state.marks[mark];
  5920. }
  5921. } else {
  5922. showConfirm(cm, 'Invalid argument: ' + startMark + '-');
  5923. return;
  5924. }
  5925. } else if (sym) {
  5926. // This symbol is a valid mark, and is not part of a range.
  5927. delete state.marks[sym];
  5928. }
  5929. }
  5930. }
  5931. };
  5932. var exCommandDispatcher = new ExCommandDispatcher();
  5933. /**
  5934. * @arg {CodeMirrorV} cm CodeMirror instance we are in.
  5935. * @arg {boolean} confirm Whether to confirm each replace.
  5936. * @arg {boolean} global
  5937. * @arg {number} lineStart Line to start replacing from.
  5938. * @arg {number} lineEnd Line to stop replacing at.
  5939. * @arg {RegExp} query Query for performing matches with.
  5940. * @arg {string} replaceWith Text to replace matches with. May contain $1,
  5941. * $2, etc for replacing captured groups using JavaScript replace.
  5942. * @arg {function} [callback] A callback for when the replace is done.
  5943. */
  5944. function doReplace(cm, confirm, global, lineStart, lineEnd, searchCursor, query,
  5945. replaceWith, callback) {
  5946. // Set up all the functions.
  5947. cm.state.vim.exMode = true;
  5948. var done = false;
  5949. /** @type {Pos}*/ var lastPos;
  5950. /** @type {number}*/ var modifiedLineNumber
  5951. /** @type {boolean}*/var joined;
  5952. function replaceAll() {
  5953. cm.operation(function() {
  5954. while (!done) {
  5955. replace();
  5956. next();
  5957. }
  5958. stop();
  5959. });
  5960. }
  5961. function replace() {
  5962. var text = cm.getRange(searchCursor.from(), searchCursor.to());
  5963. var newText = text.replace(query, replaceWith);
  5964. var unmodifiedLineNumber = searchCursor.to().line;
  5965. searchCursor.replace(newText);
  5966. modifiedLineNumber = searchCursor.to().line;
  5967. lineEnd += modifiedLineNumber - unmodifiedLineNumber;
  5968. joined = modifiedLineNumber < unmodifiedLineNumber;
  5969. }
  5970. function findNextValidMatch() {
  5971. var lastMatchTo = lastPos && copyCursor(searchCursor.to());
  5972. var match = searchCursor.findNext();
  5973. if (match && !match[0] && lastMatchTo && cursorEqual(searchCursor.from(), lastMatchTo)) {
  5974. match = searchCursor.findNext();
  5975. }
  5976. return match;
  5977. }
  5978. function next() {
  5979. // The below only loops to skip over multiple occurrences on the same
  5980. // line when 'global' is not true.
  5981. while(findNextValidMatch() &&
  5982. isInRange(searchCursor.from(), lineStart, lineEnd)) {
  5983. if (!global && searchCursor.from().line == modifiedLineNumber && !joined) {
  5984. continue;
  5985. }
  5986. cm.scrollIntoView(searchCursor.from(), 30);
  5987. cm.setSelection(searchCursor.from(), searchCursor.to());
  5988. lastPos = searchCursor.from();
  5989. done = false;
  5990. return;
  5991. }
  5992. done = true;
  5993. }
  5994. /** @arg {(() => void) | undefined} [close] */
  5995. function stop(close) {
  5996. if (close) { close(); }
  5997. cm.focus();
  5998. if (lastPos) {
  5999. cm.setCursor(lastPos);
  6000. var vim = cm.state.vim;
  6001. vim.exMode = false;
  6002. vim.lastHPos = vim.lastHSPos = lastPos.ch;
  6003. }
  6004. if (callback) { callback(); }
  6005. }
  6006. /** @arg {KeyboardEvent} e @arg {any} _value @arg {any} close */
  6007. function onPromptKeyDown(e, _value, close) {
  6008. // Swallow all keys.
  6009. CodeMirror.e_stop(e);
  6010. var keyName = vimKeyFromEvent(e);
  6011. switch (keyName) {
  6012. case 'y':
  6013. replace(); next(); break;
  6014. case 'n':
  6015. next(); break;
  6016. case 'a':
  6017. // replaceAll contains a call to close of its own. We don't want it
  6018. // to fire too early or multiple times.
  6019. var savedCallback = callback;
  6020. callback = undefined;
  6021. cm.operation(replaceAll);
  6022. callback = savedCallback;
  6023. break;
  6024. case 'l':
  6025. replace();
  6026. // fall through and exit.
  6027. case 'q':
  6028. case '<Esc>':
  6029. case '<C-c>':
  6030. case '<C-[>':
  6031. stop(close);
  6032. break;
  6033. }
  6034. if (done) { stop(close); }
  6035. return true;
  6036. }
  6037. // Actually do replace.
  6038. next();
  6039. if (done) {
  6040. showConfirm(cm, 'No matches for ' + query.source);
  6041. return;
  6042. }
  6043. if (!confirm) {
  6044. replaceAll();
  6045. if (callback) { callback(); }
  6046. return;
  6047. }
  6048. showPrompt(cm, {
  6049. prefix: dom('span', 'replace with ', dom('strong', replaceWith), ' (y/n/a/q/l)'),
  6050. onKeyDown: onPromptKeyDown
  6051. });
  6052. }
  6053. /** @arg {CodeMirrorV} cm @arg {boolean} [keepCursor] */
  6054. function exitInsertMode(cm, keepCursor) {
  6055. var vim = cm.state.vim;
  6056. var macroModeState = vimGlobalState.macroModeState;
  6057. var insertModeChangeRegister = vimGlobalState.registerController.getRegister('.');
  6058. var isPlaying = macroModeState.isPlaying;
  6059. var lastChange = macroModeState.lastInsertModeChanges;
  6060. if (!isPlaying) {
  6061. cm.off('change', onChange);
  6062. if (vim.insertEnd) vim.insertEnd.clear();
  6063. vim.insertEnd = undefined;
  6064. CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
  6065. }
  6066. if (!isPlaying && vim.insertModeRepeat > 1) {
  6067. // Perform insert mode repeat for commands like 3,a and 3,o.
  6068. repeatLastEdit(cm, vim, vim.insertModeRepeat - 1,
  6069. true /** repeatForInsert */);
  6070. // @ts-ignore
  6071. vim.lastEditInputState.repeatOverride = vim.insertModeRepeat;
  6072. }
  6073. delete vim.insertModeRepeat;
  6074. vim.insertMode = false;
  6075. if (!keepCursor) {
  6076. cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1);
  6077. }
  6078. cm.setOption('keyMap', 'vim');
  6079. cm.setOption('disableInput', true);
  6080. cm.toggleOverwrite(false); // exit replace mode if we were in it.
  6081. // update the ". register before exiting insert mode
  6082. insertModeChangeRegister.setText(lastChange.changes.join(''));
  6083. CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
  6084. if (macroModeState.isRecording) {
  6085. logInsertModeChange(macroModeState);
  6086. }
  6087. }
  6088. /** @arg {vimKey} command*/
  6089. function _mapCommand(command) {
  6090. defaultKeymap.unshift(command);
  6091. }
  6092. /**
  6093. * @arg {string} keys
  6094. * @arg {string} type
  6095. * @arg {string} name
  6096. * @arg {any} args
  6097. * @arg {{ [x: string]: any; }} extra
  6098. **/
  6099. function mapCommand(keys, type, name, args, extra) {
  6100. /**@type{any} */
  6101. var command = {keys: keys, type: type};
  6102. command[type] = name;
  6103. command[type + "Args"] = args;
  6104. for (var key in extra)
  6105. command[key] = extra[key];
  6106. _mapCommand(command);
  6107. }
  6108. // The timeout in milliseconds for the two-character ESC keymap should be
  6109. // adjusted according to your typing speed to prevent false positives.
  6110. defineOption('insertModeEscKeysTimeout', 200, 'number');
  6111. /**
  6112. * @arg {CodeMirrorV} cm
  6113. * @arg {vimState} vim
  6114. * @arg {MacroModeState} macroModeState
  6115. * @arg {string} registerName
  6116. */
  6117. function executeMacroRegister(cm, vim, macroModeState, registerName) {
  6118. var register = vimGlobalState.registerController.getRegister(registerName);
  6119. if (registerName == ':') {
  6120. // Read-only register containing last Ex command.
  6121. if (register.keyBuffer[0]) {
  6122. exCommandDispatcher.processCommand(cm, register.keyBuffer[0]);
  6123. }
  6124. macroModeState.isPlaying = false;
  6125. return;
  6126. }
  6127. var keyBuffer = register.keyBuffer;
  6128. var imc = 0;
  6129. macroModeState.isPlaying = true;
  6130. macroModeState.replaySearchQueries = register.searchQueries.slice(0);
  6131. for (var i = 0; i < keyBuffer.length; i++) {
  6132. var text = keyBuffer[i];
  6133. var match, key;
  6134. var keyRe = /<(?:[CSMA]-)*\w+>|./gi;
  6135. while ((match = keyRe.exec(text))) {
  6136. // Pull off one command key, which is either a single character
  6137. // or a special sequence wrapped in '<' and '>', e.g. '<Space>'.
  6138. key = match[0];
  6139. vimApi.handleKey(cm, key, 'macro');
  6140. if (vim.insertMode) {
  6141. var changes = register.insertModeChanges[imc++].changes;
  6142. vimGlobalState.macroModeState.lastInsertModeChanges.changes = changes;
  6143. repeatInsertModeChanges(cm, changes, 1);
  6144. exitInsertMode(cm);
  6145. }
  6146. }
  6147. }
  6148. macroModeState.isPlaying = false;
  6149. }
  6150. /** @arg {MacroModeState} macroModeState @arg {any} key */
  6151. function logKey(macroModeState, key) {
  6152. if (macroModeState.isPlaying) { return; }
  6153. var registerName = macroModeState.latestRegister;
  6154. var register = vimGlobalState.registerController.getRegister(registerName);
  6155. if (register) {
  6156. register.pushText(key);
  6157. }
  6158. }
  6159. /** @arg {MacroModeState} macroModeState */
  6160. function logInsertModeChange(macroModeState) {
  6161. if (macroModeState.isPlaying) { return; }
  6162. var registerName = macroModeState.latestRegister;
  6163. var register = vimGlobalState.registerController.getRegister(registerName);
  6164. if (register && register.pushInsertModeChanges) {
  6165. register.pushInsertModeChanges(macroModeState.lastInsertModeChanges);
  6166. }
  6167. }
  6168. /** @arg {MacroModeState} macroModeState @arg {string} query */
  6169. function logSearchQuery(macroModeState, query) {
  6170. if (macroModeState.isPlaying) { return; }
  6171. var registerName = macroModeState.latestRegister;
  6172. var register = vimGlobalState.registerController.getRegister(registerName);
  6173. if (register && register.pushSearchQuery) {
  6174. register.pushSearchQuery(query);
  6175. }
  6176. }
  6177. /**
  6178. * Listens for changes made in insert mode.
  6179. * Should only be active in insert mode.
  6180. * @arg {CodeMirror} cm
  6181. * @arg {{ origin: string | undefined; text: any[]; next: any; }} changeObj
  6182. */
  6183. function onChange(cm, changeObj) {
  6184. var macroModeState = vimGlobalState.macroModeState;
  6185. var lastChange = macroModeState.lastInsertModeChanges;
  6186. if (!macroModeState.isPlaying) {
  6187. var vim = cm.state.vim;
  6188. while(changeObj) {
  6189. lastChange.expectCursorActivityForChange = true;
  6190. // @ts-ignore
  6191. if (lastChange.ignoreCount > 1) {
  6192. // @ts-ignore
  6193. lastChange.ignoreCount--;
  6194. } else if (changeObj.origin == '+input' || changeObj.origin == 'paste'
  6195. || changeObj.origin === undefined /* only in testing */) {
  6196. var selectionCount = cm.listSelections().length;
  6197. if (selectionCount > 1)
  6198. lastChange.ignoreCount = selectionCount;
  6199. var text = changeObj.text.join('\n');
  6200. if (lastChange.maybeReset) {
  6201. lastChange.changes = [];
  6202. lastChange.maybeReset = false;
  6203. }
  6204. if (text) {
  6205. if (cm.state.overwrite && !/\n/.test(text)) {
  6206. lastChange.changes.push([text]);
  6207. } else {
  6208. if (text.length > 1) {
  6209. var insertEnd = vim && vim.insertEnd && vim.insertEnd.find()
  6210. var cursor = cm.getCursor();
  6211. if (insertEnd && insertEnd.line == cursor.line) {
  6212. var offset = insertEnd.ch - cursor.ch;
  6213. if (offset > 0 && offset < text.length) {
  6214. lastChange.changes.push([text, offset]);
  6215. text = '';
  6216. }
  6217. }
  6218. }
  6219. if (text) lastChange.changes.push(text);
  6220. }
  6221. }
  6222. }
  6223. // Change objects may be chained with next.
  6224. changeObj = changeObj.next;
  6225. }
  6226. }
  6227. }
  6228. /**
  6229. * Listens for any kind of cursor activity on CodeMirror.
  6230. * @arg {CodeMirrorV} cm
  6231. */
  6232. function onCursorActivity(cm) {
  6233. var vim = cm.state.vim;
  6234. if (vim.insertMode) {
  6235. // Tracking cursor activity in insert mode (for macro support).
  6236. var macroModeState = vimGlobalState.macroModeState;
  6237. if (macroModeState.isPlaying) { return; }
  6238. var lastChange = macroModeState.lastInsertModeChanges;
  6239. if (lastChange.expectCursorActivityForChange) {
  6240. lastChange.expectCursorActivityForChange = false;
  6241. } else {
  6242. // Cursor moved outside the context of an edit. Reset the change.
  6243. lastChange.maybeReset = true;
  6244. if (vim.insertEnd) vim.insertEnd.clear();
  6245. vim.insertEnd = cm.setBookmark(cm.getCursor(), {insertLeft: true});
  6246. }
  6247. } else if (!cm.curOp?.isVimOp) {
  6248. handleExternalSelection(cm, vim);
  6249. }
  6250. }
  6251. /** @arg {CodeMirrorV} cm @arg {vimState} vim */
  6252. function handleExternalSelection(cm, vim) {
  6253. var anchor = cm.getCursor('anchor');
  6254. var head = cm.getCursor('head');
  6255. // Enter or exit visual mode to match mouse selection.
  6256. if (vim.visualMode && !cm.somethingSelected()) {
  6257. exitVisualMode(cm, false);
  6258. } else if (!vim.visualMode && !vim.insertMode && cm.somethingSelected()) {
  6259. vim.visualMode = true;
  6260. vim.visualLine = false;
  6261. CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
  6262. }
  6263. if (vim.visualMode) {
  6264. // Bind CodeMirror selection model to vim selection model.
  6265. // Mouse selections are considered visual characterwise.
  6266. var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0;
  6267. var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0;
  6268. head = offsetCursor(head, 0, headOffset);
  6269. anchor = offsetCursor(anchor, 0, anchorOffset);
  6270. vim.sel = {
  6271. anchor: anchor,
  6272. head: head
  6273. };
  6274. updateMark(cm, vim, '<', cursorMin(head, anchor));
  6275. updateMark(cm, vim, '>', cursorMax(head, anchor));
  6276. } else if (!vim.insertMode) {
  6277. // Reset lastHPos if selection was modified by something outside of vim mode e.g. by mouse.
  6278. vim.lastHPos = cm.getCursor().ch;
  6279. }
  6280. }
  6281. /**
  6282. * Wrapper for special keys pressed in insert mode
  6283. * @arg {string} keyName
  6284. */
  6285. function InsertModeKey(keyName, e) {
  6286. this.keyName = keyName;
  6287. this.key = e.key;
  6288. this.ctrlKey = e.ctrlKey;
  6289. this.altKey = e.altKey;
  6290. this.metaKey = e.metaKey;
  6291. this.shiftKey = e.shiftKey;
  6292. }
  6293. /**
  6294. * Handles raw key down events from the text area.
  6295. * - Should only be active in insert mode.
  6296. * - For recording deletes in insert mode.
  6297. * @arg {KeyboardEvent} e
  6298. */
  6299. function onKeyEventTargetKeyDown(e) {
  6300. var macroModeState = vimGlobalState.macroModeState;
  6301. var lastChange = macroModeState.lastInsertModeChanges;
  6302. var keyName = CodeMirror.keyName ? CodeMirror.keyName(e) : e.key;
  6303. if (!keyName) { return; }
  6304. if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
  6305. if (lastChange.maybeReset) {
  6306. lastChange.changes = [];
  6307. lastChange.maybeReset = false;
  6308. }
  6309. lastChange.changes.push(new InsertModeKey(keyName, e));
  6310. }
  6311. }
  6312. /**
  6313. * Repeats the last edit, which includes exactly 1 command and at most 1
  6314. * insert. Operator and motion commands are read from lastEditInputState,
  6315. * while action commands are read from lastEditActionCommand.
  6316. *
  6317. * If repeatForInsert is true, then the function was called by
  6318. * exitInsertMode to repeat the insert mode changes the user just made. The
  6319. * corresponding enterInsertMode call was made with a count.
  6320. * @arg {CodeMirrorV} cm
  6321. * @arg {vimState} vim
  6322. * @arg {number} repeat
  6323. * @arg {boolean} repeatForInsert
  6324. */
  6325. function repeatLastEdit(cm, vim, repeat, repeatForInsert) {
  6326. var macroModeState = vimGlobalState.macroModeState;
  6327. macroModeState.isPlaying = true;
  6328. var lastAction = vim.lastEditActionCommand;
  6329. var cachedInputState = vim.inputState;
  6330. function repeatCommand() {
  6331. if (lastAction) {
  6332. commandDispatcher.processAction(cm, vim, lastAction);
  6333. } else {
  6334. commandDispatcher.evalInput(cm, vim);
  6335. }
  6336. }
  6337. /** @arg {number} repeat */
  6338. function repeatInsert(repeat) {
  6339. if (macroModeState.lastInsertModeChanges.changes.length > 0) {
  6340. // For some reason, repeat cw in desktop VIM does not repeat
  6341. // insert mode changes. Will conform to that behavior.
  6342. repeat = !vim.lastEditActionCommand ? 1 : repeat;
  6343. var changeObject = macroModeState.lastInsertModeChanges;
  6344. repeatInsertModeChanges(cm, changeObject.changes, repeat);
  6345. }
  6346. }
  6347. // @ts-ignore
  6348. vim.inputState = vim.lastEditInputState;
  6349. if (lastAction && lastAction.interlaceInsertRepeat) {
  6350. // o and O repeat have to be interlaced with insert repeats so that the
  6351. // insertions appear on separate lines instead of the last line.
  6352. for (var i = 0; i < repeat; i++) {
  6353. repeatCommand();
  6354. repeatInsert(1);
  6355. }
  6356. } else {
  6357. if (!repeatForInsert) {
  6358. // Hack to get the cursor to end up at the right place. If I is
  6359. // repeated in insert mode repeat, cursor will be 1 insert
  6360. // change set left of where it should be.
  6361. repeatCommand();
  6362. }
  6363. repeatInsert(repeat);
  6364. }
  6365. vim.inputState = cachedInputState;
  6366. if (vim.insertMode && !repeatForInsert) {
  6367. // Don't exit insert mode twice. If repeatForInsert is set, then we
  6368. // were called by an exitInsertMode call lower on the stack.
  6369. exitInsertMode(cm);
  6370. }
  6371. macroModeState.isPlaying = false;
  6372. }
  6373. /**@arg {CodeMirrorV} cm, @arg {string} key */
  6374. function sendCmKey(cm, key) {
  6375. CodeMirror.lookupKey(key, 'vim-insert', function keyHandler(binding) {
  6376. if (typeof binding == 'string') {
  6377. CodeMirror.commands[binding](cm);
  6378. } else {
  6379. binding(cm);
  6380. }
  6381. return true;
  6382. });
  6383. }
  6384. function repeatInsertModeChanges(cm, changes, repeat) {
  6385. var head = cm.getCursor('head');
  6386. var visualBlock = vimGlobalState.macroModeState.lastInsertModeChanges.visualBlock;
  6387. if (visualBlock) {
  6388. // Set up block selection again for repeating the changes.
  6389. selectForInsert(cm, head, visualBlock + 1);
  6390. repeat = cm.listSelections().length;
  6391. cm.setCursor(head);
  6392. }
  6393. for (var i = 0; i < repeat; i++) {
  6394. if (visualBlock) {
  6395. cm.setCursor(offsetCursor(head, i, 0));
  6396. }
  6397. for (var j = 0; j < changes.length; j++) {
  6398. var change = changes[j];
  6399. if (change instanceof InsertModeKey) {
  6400. sendCmKey(cm, change.keyName);
  6401. } else if (typeof change == "string") {
  6402. cm.replaceSelection(change);
  6403. } else {
  6404. var start = cm.getCursor();
  6405. var end = offsetCursor(start, 0, change[0].length - (change[1] || 0));
  6406. cm.replaceRange(change[0], start, change[1] ? start: end);
  6407. cm.setCursor(end);
  6408. }
  6409. }
  6410. }
  6411. if (visualBlock) {
  6412. cm.setCursor(offsetCursor(head, 0, 1));
  6413. }
  6414. }
  6415. // multiselect support
  6416. /** @arg {vimState} state */
  6417. function cloneVimState(state) {
  6418. var n = new state.constructor();
  6419. Object.keys(state).forEach(function(key) {
  6420. if (key == "insertEnd") return;
  6421. var o = state[key];
  6422. if (Array.isArray(o))
  6423. o = o.slice();
  6424. else if (o && typeof o == "object" && o.constructor != Object)
  6425. o = cloneVimState(o);
  6426. n[key] = o;
  6427. });
  6428. if (state.sel) {
  6429. n.sel = {
  6430. head: state.sel.head && copyCursor(state.sel.head),
  6431. anchor: state.sel.anchor && copyCursor(state.sel.anchor)
  6432. };
  6433. }
  6434. return n;
  6435. }
  6436. /** @arg {CodeMirror} cm_ @arg {string} key @arg {string} origin */
  6437. function multiSelectHandleKey(cm_, key, origin) {
  6438. var vim = maybeInitVimState(cm_);
  6439. var cm = /**@type {CodeMirrorV}*/(cm_);
  6440. /** @type {boolean | undefined} */
  6441. var isHandled = false;
  6442. var vim = vimApi.maybeInitVimState_(cm);
  6443. var visualBlock = vim.visualBlock || vim.wasInVisualBlock;
  6444. var wasMultiselect = cm.isInMultiSelectMode();
  6445. if (vim.wasInVisualBlock && !wasMultiselect) {
  6446. vim.wasInVisualBlock = false;
  6447. } else if (wasMultiselect && vim.visualBlock) {
  6448. vim.wasInVisualBlock = true;
  6449. }
  6450. if (key == '<Esc>' && !vim.insertMode && !vim.visualMode && wasMultiselect && vim.status == "<Esc>") {
  6451. // allow editor to exit multiselect
  6452. clearInputState(cm);
  6453. // @ts-ignore
  6454. } else if (visualBlock || !wasMultiselect || cm.inVirtualSelectionMode) {
  6455. isHandled = vimApi.handleKey(cm, key, origin);
  6456. } else {
  6457. var old = cloneVimState(vim);
  6458. var changeQueueList = vim.inputState.changeQueueList || [];
  6459. cm.operation(function() {
  6460. if (cm.curOp)
  6461. cm.curOp.isVimOp = true;
  6462. var index = 0;
  6463. cm.forEachSelection(function() {
  6464. cm.state.vim.inputState.changeQueue = changeQueueList[index];
  6465. var head = cm.getCursor("head");
  6466. var anchor = cm.getCursor("anchor");
  6467. var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0;
  6468. var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0;
  6469. head = offsetCursor(head, 0, headOffset);
  6470. anchor = offsetCursor(anchor, 0, anchorOffset);
  6471. cm.state.vim.sel.head = head;
  6472. cm.state.vim.sel.anchor = anchor;
  6473. isHandled = vimApi.handleKey(cm, key, origin);
  6474. if (cm.virtualSelection) {
  6475. changeQueueList[index] = cm.state.vim.inputState.changeQueue;
  6476. cm.state.vim = cloneVimState(old);
  6477. }
  6478. index++;
  6479. });
  6480. if (cm.curOp?.cursorActivity && !isHandled)
  6481. cm.curOp.cursorActivity = false;
  6482. cm.state.vim = vim
  6483. vim.inputState.changeQueueList = changeQueueList
  6484. vim.inputState.changeQueue = null;
  6485. }, true);
  6486. }
  6487. // some commands may bring visualMode and selection out of sync
  6488. if (isHandled && !vim.visualMode && !vim.insert && vim.visualMode != cm.somethingSelected()) {
  6489. handleExternalSelection(cm, vim);
  6490. }
  6491. return isHandled;
  6492. }
  6493. resetVimGlobalState();
  6494. return vimApi;
  6495. };