vim.js 188 KB

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