vim.js 218 KB

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