vim.js 195 KB

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