vim.js 209 KB

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