vim.js 189 KB

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