vim.js 206 KB

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