vim.js 232 KB

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