vim.js 191 KB

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