keybinding-vim.js 214 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931
  1. define("ace/keyboard/vim",["ace_require","exports","module","ace/range","ace/lib/event_emitter","ace/lib/dom","ace/lib/oop","ace/lib/keys","ace/lib/event","ace/search","ace/lib/useragent","ace/search_highlight","ace/commands/multi_select_commands","ace/mode/text","ace/multi_select"], function(ace_require, exports, module) {
  2. 'use strict';
  3. function log() {
  4. var d = "";
  5. function format(p) {
  6. if (typeof p != "object")
  7. return p + "";
  8. if ("line" in p) {
  9. return p.line + ":" + p.ch;
  10. }
  11. if ("anchor" in p) {
  12. return format(p.anchor) + "->" + format(p.head);
  13. }
  14. if (Array.isArray(p))
  15. return "[" + p.map(function(x) {
  16. return format(x);
  17. }) + "]";
  18. return JSON.stringify(p);
  19. }
  20. for (var i = 0; i < arguments.length; i++) {
  21. var p = arguments[i];
  22. var f = format(p);
  23. d += f + " ";
  24. }
  25. console.log(d);
  26. }
  27. var Range = ace_require("../range").Range;
  28. var EventEmitter = ace_require("../lib/event_emitter").EventEmitter;
  29. var dom = ace_require("../lib/dom");
  30. var oop = ace_require("../lib/oop");
  31. var KEYS = ace_require("../lib/keys");
  32. var event = ace_require("../lib/event");
  33. var Search = ace_require("../search").Search;
  34. var useragent = ace_require("../lib/useragent");
  35. var SearchHighlight = ace_require("../search_highlight").SearchHighlight;
  36. var multiSelectCommands = ace_require("../commands/multi_select_commands");
  37. var TextModeTokenRe = ace_require("../mode/text").Mode.prototype.tokenRe;
  38. ace_require("../multi_select");
  39. var CodeMirror = function(ace) {
  40. this.ace = ace;
  41. this.state = {};
  42. this.marks = {};
  43. this.$uid = 0;
  44. this.onChange = this.onChange.bind(this);
  45. this.onSelectionChange = this.onSelectionChange.bind(this);
  46. this.onBeforeEndOperation = this.onBeforeEndOperation.bind(this);
  47. this.ace.on('change', this.onChange);
  48. this.ace.on('changeSelection', this.onSelectionChange);
  49. this.ace.on('beforeEndOperation', this.onBeforeEndOperation);
  50. };
  51. CodeMirror.Pos = function(line, ch) {
  52. if (!(this instanceof Pos)) return new Pos(line, ch);
  53. this.line = line; this.ch = ch;
  54. };
  55. CodeMirror.defineOption = function(name, val, setter) {};
  56. CodeMirror.commands = {
  57. redo: function(cm) { cm.ace.redo(); },
  58. undo: function(cm) { cm.ace.undo(); },
  59. newlineAndIndent: function(cm) { cm.ace.insert("\n"); }
  60. };
  61. CodeMirror.keyMap = {};
  62. CodeMirror.addClass = CodeMirror.rmClass = function() {};
  63. CodeMirror.e_stop = CodeMirror.e_preventDefault = event.stopEvent;
  64. CodeMirror.keyName = function(e) {
  65. var key = (KEYS[e.keyCode] || e.key || "");
  66. if (key.length == 1) key = key.toUpperCase();
  67. key = event.getModifierString(e).replace(/(^|-)\w/g, function(m) {
  68. return m.toUpperCase();
  69. }) + key;
  70. return key;
  71. };
  72. CodeMirror.keyMap['default'] = function(key) {
  73. return function(cm) {
  74. var cmd = cm.ace.commands.commandKeyBinding[key.toLowerCase()];
  75. return cmd && cm.ace.execCommand(cmd) !== false;
  76. };
  77. };
  78. CodeMirror.lookupKey = function lookupKey(key, map, handle) {
  79. if (!map) map = "default";
  80. if (typeof map == "string")
  81. map = CodeMirror.keyMap[map];
  82. var found = typeof map == "function" ? map(key) : map[key];
  83. if (found === false) return "nothing";
  84. if (found === "...") return "multi";
  85. if (found != null && handle(found)) return "handled";
  86. if (map.fallthrough) {
  87. if (!Array.isArray(map.fallthrough))
  88. return lookupKey(key, map.fallthrough, handle);
  89. for (var i = 0; i < map.fallthrough.length; i++) {
  90. var result = lookupKey(key, map.fallthrough[i], handle);
  91. if (result) return result;
  92. }
  93. }
  94. };
  95. CodeMirror.signal = function(o, name, e) { return o._signal(name, e) };
  96. CodeMirror.on = event.addListener;
  97. CodeMirror.off = event.removeListener;
  98. CodeMirror.isWordChar = function(ch) {
  99. if (ch < "\x7f") return /^\w$/.test(ch);
  100. TextModeTokenRe.lastIndex = 0;
  101. return TextModeTokenRe.test(ch);
  102. };
  103. (function() {
  104. oop.implement(CodeMirror.prototype, EventEmitter);
  105. this.destroy = function() {
  106. this.ace.off('change', this.onChange);
  107. this.ace.off('changeSelection', this.onSelectionChange);
  108. this.ace.off('beforeEndOperation', this.onBeforeEndOperation);
  109. this.removeOverlay();
  110. };
  111. this.virtualSelectionMode = function() {
  112. return this.ace.inVirtualSelectionMode && this.ace.selection.index;
  113. };
  114. this.onChange = function(delta) {
  115. var change = { text: delta.action[0] == 'i' ? delta.lines : [] };
  116. var curOp = this.curOp = this.curOp || {};
  117. if (!curOp.changeHandlers)
  118. curOp.changeHandlers = this._eventRegistry["change"] && this._eventRegistry["change"].slice();
  119. if (!curOp.lastChange) {
  120. curOp.lastChange = curOp.change = change;
  121. } else {
  122. curOp.lastChange.next = curOp.lastChange = change;
  123. }
  124. this.$updateMarkers(delta);
  125. };
  126. this.onSelectionChange = function() {
  127. var curOp = this.curOp = this.curOp || {};
  128. if (!curOp.cursorActivityHandlers)
  129. curOp.cursorActivityHandlers = this._eventRegistry["cursorActivity"] && this._eventRegistry["cursorActivity"].slice();
  130. this.curOp.cursorActivity = true;
  131. if (this.ace.inMultiSelectMode) {
  132. this.ace.keyBinding.removeKeyboardHandler(multiSelectCommands.keyboardHandler);
  133. }
  134. };
  135. this.operation = function(fn, force) {
  136. if (!force && this.curOp || force && this.curOp && this.curOp.force) {
  137. return fn();
  138. }
  139. if (force || !this.ace.curOp) {
  140. if (this.curOp)
  141. this.onBeforeEndOperation();
  142. }
  143. if (!this.ace.curOp) {
  144. var prevOp = this.ace.prevOp;
  145. this.ace.startOperation({
  146. command: { name: "vim", scrollIntoView: "cursor" }
  147. });
  148. }
  149. var curOp = this.curOp = this.curOp || {};
  150. this.curOp.force = force;
  151. var result = fn();
  152. if (this.ace.curOp && this.ace.curOp.command.name == "vim") {
  153. if (this.state.dialog)
  154. this.ace.curOp.command.scrollIntoView = false;
  155. this.ace.endOperation();
  156. if (!curOp.cursorActivity && !curOp.lastChange && prevOp)
  157. this.ace.prevOp = prevOp;
  158. }
  159. if (force || !this.ace.curOp) {
  160. if (this.curOp)
  161. this.onBeforeEndOperation();
  162. }
  163. return result;
  164. };
  165. this.onBeforeEndOperation = function() {
  166. var op = this.curOp;
  167. if (op) {
  168. if (op.change) { this.signal("change", op.change, op); }
  169. if (op && op.cursorActivity) { this.signal("cursorActivity", null, op); }
  170. this.curOp = null;
  171. }
  172. };
  173. this.signal = function(eventName, e, handlers) {
  174. var listeners = handlers ? handlers[eventName + "Handlers"]
  175. : (this._eventRegistry || {})[eventName];
  176. if (!listeners)
  177. return;
  178. listeners = listeners.slice();
  179. for (var i=0; i<listeners.length; i++)
  180. listeners[i](this, e);
  181. };
  182. this.firstLine = function() { return 0; };
  183. this.lastLine = function() { return this.ace.session.getLength() - 1; };
  184. this.lineCount = function() { return this.ace.session.getLength(); };
  185. this.setCursor = function(line, ch) {
  186. if (typeof line === 'object') {
  187. ch = line.ch;
  188. line = line.line;
  189. }
  190. if (!this.ace.inVirtualSelectionMode)
  191. this.ace.exitMultiSelectMode();
  192. this.ace.session.unfold({row: line, column: ch});
  193. this.ace.selection.moveTo(line, ch);
  194. };
  195. this.getCursor = function(p) {
  196. var sel = this.ace.selection;
  197. var pos = p == 'anchor' ? (sel.isEmpty() ? sel.lead : sel.anchor) :
  198. p == 'head' || !p ? sel.lead : sel.getRange()[p];
  199. return toCmPos(pos);
  200. };
  201. this.listSelections = function(p) {
  202. var ranges = this.ace.multiSelect.rangeList.ranges;
  203. if (!ranges.length || this.ace.inVirtualSelectionMode)
  204. return [{anchor: this.getCursor('anchor'), head: this.getCursor('head')}];
  205. return ranges.map(function(r) {
  206. return {
  207. anchor: this.clipPos(toCmPos(r.cursor == r.end ? r.start : r.end)),
  208. head: this.clipPos(toCmPos(r.cursor))
  209. };
  210. }, this);
  211. };
  212. this.setSelections = function(p, primIndex) {
  213. var sel = this.ace.multiSelect;
  214. var ranges = p.map(function(x) {
  215. var anchor = toAcePos(x.anchor);
  216. var head = toAcePos(x.head);
  217. var r = Range.comparePoints(anchor, head) < 0
  218. ? new Range.fromPoints(anchor, head)
  219. : new Range.fromPoints(head, anchor);
  220. r.cursor = Range.comparePoints(r.start, head) ? r.end : r.start;
  221. return r;
  222. });
  223. if (this.ace.inVirtualSelectionMode) {
  224. this.ace.selection.fromOrientedRange(ranges[0]);
  225. return;
  226. }
  227. if (!primIndex) {
  228. ranges = ranges.reverse();
  229. } else if (ranges[primIndex]) {
  230. ranges.push(ranges.splice(primIndex, 1)[0]);
  231. }
  232. sel.toSingleRange(ranges[0].clone());
  233. var session = this.ace.session;
  234. for (var i = 0; i < ranges.length; i++) {
  235. var range = session.$clipRangeToDocument(ranges[i]); // todo why ace doesn't do this?
  236. sel.addRange(range);
  237. }
  238. };
  239. this.setSelection = function(a, h, options) {
  240. var sel = this.ace.selection;
  241. sel.moveTo(a.line, a.ch);
  242. sel.selectTo(h.line, h.ch);
  243. if (options && options.origin == '*mouse') {
  244. this.onBeforeEndOperation();
  245. }
  246. };
  247. this.somethingSelected = function(p) {
  248. return !this.ace.selection.isEmpty();
  249. };
  250. this.clipPos = function(p) {
  251. var pos = this.ace.session.$clipPositionToDocument(p.line, p.ch);
  252. return toCmPos(pos);
  253. };
  254. this.markText = function(cursor) {
  255. return {clear: function() {}, find: function() {}};
  256. };
  257. this.$updateMarkers = function(delta) {
  258. var isInsert = delta.action == "insert";
  259. var start = delta.start;
  260. var end = delta.end;
  261. var rowShift = (end.row - start.row) * (isInsert ? 1 : -1);
  262. var colShift = (end.column - start.column) * (isInsert ? 1 : -1);
  263. if (isInsert) end = start;
  264. for (var i in this.marks) {
  265. var point = this.marks[i];
  266. var cmp = Range.comparePoints(point, start);
  267. if (cmp < 0) {
  268. continue; // delta starts after the range
  269. }
  270. if (cmp === 0) {
  271. if (isInsert) {
  272. if (point.bias == 1) {
  273. cmp = 1;
  274. } else {
  275. point.bias = -1;
  276. continue;
  277. }
  278. }
  279. }
  280. var cmp2 = isInsert ? cmp : Range.comparePoints(point, end);
  281. if (cmp2 > 0) {
  282. point.row += rowShift;
  283. point.column += point.row == end.row ? colShift : 0;
  284. continue;
  285. }
  286. if (!isInsert && cmp2 <= 0) {
  287. point.row = start.row;
  288. point.column = start.column;
  289. if (cmp2 === 0)
  290. point.bias = 1;
  291. }
  292. }
  293. };
  294. var Marker = function(cm, id, row, column) {
  295. this.cm = cm;
  296. this.id = id;
  297. this.row = row;
  298. this.column = column;
  299. cm.marks[this.id] = this;
  300. };
  301. Marker.prototype.clear = function() { delete this.cm.marks[this.id] };
  302. Marker.prototype.find = function() { return toCmPos(this) };
  303. this.setBookmark = function(cursor, options) {
  304. var bm = new Marker(this, this.$uid++, cursor.line, cursor.ch);
  305. if (!options || !options.insertLeft)
  306. bm.$insertRight = true;
  307. this.marks[bm.id] = bm;
  308. return bm;
  309. };
  310. this.moveH = function(increment, unit) {
  311. if (unit == 'char') {
  312. var sel = this.ace.selection;
  313. sel.clearSelection();
  314. sel.moveCursorBy(0, increment);
  315. }
  316. };
  317. this.findPosV = function(start, amount, unit, goalColumn) {
  318. if (unit == 'page') {
  319. var renderer = this.ace.renderer;
  320. var config = renderer.layerConfig;
  321. amount = amount * Math.floor(config.height / config.lineHeight);
  322. unit = 'line';
  323. }
  324. if (unit == 'line') {
  325. var screenPos = this.ace.session.documentToScreenPosition(start.line, start.ch);
  326. if (goalColumn != null)
  327. screenPos.column = goalColumn;
  328. screenPos.row += amount;
  329. screenPos.row = Math.min(Math.max(0, screenPos.row), this.ace.session.getScreenLength() - 1);
  330. var pos = this.ace.session.screenToDocumentPosition(screenPos.row, screenPos.column);
  331. return toCmPos(pos);
  332. } else {
  333. debugger;
  334. }
  335. };
  336. this.charCoords = function(pos, mode) {
  337. if (mode == 'div' || !mode) {
  338. var sc = this.ace.session.documentToScreenPosition(pos.line, pos.ch);
  339. return {left: sc.column, top: sc.row};
  340. }if (mode == 'local') {
  341. var renderer = this.ace.renderer;
  342. var sc = this.ace.session.documentToScreenPosition(pos.line, pos.ch);
  343. var lh = renderer.layerConfig.lineHeight;
  344. var cw = renderer.layerConfig.characterWidth;
  345. var top = lh * sc.row;
  346. return {left: sc.column * cw, top: top, bottom: top + lh};
  347. }
  348. };
  349. this.coordsChar = function(pos, mode) {
  350. var renderer = this.ace.renderer;
  351. if (mode == 'local') {
  352. var row = Math.max(0, Math.floor(pos.top / renderer.lineHeight));
  353. var col = Math.max(0, Math.floor(pos.left / renderer.characterWidth));
  354. var ch = renderer.session.screenToDocumentPosition(row, col);
  355. return toCmPos(ch);
  356. } else if (mode == 'div') {
  357. throw "not implemented";
  358. }
  359. };
  360. this.getSearchCursor = function(query, pos, caseFold) {
  361. var caseSensitive = false;
  362. var isRegexp = false;
  363. if (query instanceof RegExp && !query.global) {
  364. caseSensitive = !query.ignoreCase;
  365. query = query.source;
  366. isRegexp = true;
  367. }
  368. var search = new Search();
  369. if (pos.ch == undefined) pos.ch = Number.MAX_VALUE;
  370. var acePos = {row: pos.line, column: pos.ch};
  371. var cm = this;
  372. var last = null;
  373. return {
  374. findNext: function() { return this.find(false) },
  375. findPrevious: function() {return this.find(true) },
  376. find: function(back) {
  377. search.setOptions({
  378. needle: query,
  379. caseSensitive: caseSensitive,
  380. wrap: false,
  381. backwards: back,
  382. regExp: isRegexp,
  383. start: last || acePos
  384. });
  385. var range = search.find(cm.ace.session);
  386. if (range && range.isEmpty()) {
  387. if (cm.getLine(range.start.row).length == range.start.column) {
  388. search.$options.start = range;
  389. range = search.find(cm.ace.session);
  390. }
  391. }
  392. last = range;
  393. return last;
  394. },
  395. from: function() { return last && toCmPos(last.start) },
  396. to: function() { return last && toCmPos(last.end) },
  397. replace: function(text) {
  398. if (last) {
  399. last.end = cm.ace.session.doc.replace(last, text);
  400. }
  401. }
  402. };
  403. };
  404. this.scrollTo = function(x, y) {
  405. var renderer = this.ace.renderer;
  406. var config = renderer.layerConfig;
  407. var maxHeight = config.maxHeight;
  408. maxHeight -= (renderer.$size.scrollerHeight - renderer.lineHeight) * renderer.$scrollPastEnd;
  409. if (y != null) this.ace.session.setScrollTop(Math.max(0, Math.min(y, maxHeight)));
  410. if (x != null) this.ace.session.setScrollLeft(Math.max(0, Math.min(x, config.width)));
  411. };
  412. this.scrollInfo = function() { return 0; };
  413. this.scrollIntoView = function(pos, margin) {
  414. if (pos) {
  415. var renderer = this.ace.renderer;
  416. var viewMargin = { "top": 0, "bottom": margin };
  417. renderer.scrollCursorIntoView(toAcePos(pos),
  418. (renderer.lineHeight * 2) / renderer.$size.scrollerHeight, viewMargin);
  419. }
  420. };
  421. this.getLine = function(row) { return this.ace.session.getLine(row) };
  422. this.getRange = function(s, e) {
  423. return this.ace.session.getTextRange(new Range(s.line, s.ch, e.line, e.ch));
  424. };
  425. this.replaceRange = function(text, s, e) {
  426. if (!e) e = s;
  427. return this.ace.session.replace(new Range(s.line, s.ch, e.line, e.ch), text);
  428. };
  429. this.replaceSelection =
  430. this.replaceSelections = function(p) {
  431. var sel = this.ace.selection;
  432. if (this.ace.inVirtualSelectionMode) {
  433. this.ace.session.replace(sel.getRange(), p[0] || "");
  434. return;
  435. }
  436. sel.inVirtualSelectionMode = true;
  437. var ranges = sel.rangeList.ranges;
  438. if (!ranges.length) ranges = [this.ace.multiSelect.getRange()];
  439. for (var i = ranges.length; i--;)
  440. this.ace.session.replace(ranges[i], p[i] || "");
  441. sel.inVirtualSelectionMode = false;
  442. };
  443. this.getSelection = function() {
  444. return this.ace.getSelectedText();
  445. };
  446. this.getSelections = function() {
  447. return this.listSelections().map(function(x) {
  448. return this.getRange(x.anchor, x.head);
  449. }, this);
  450. };
  451. this.getInputField = function() {
  452. return this.ace.textInput.getElement();
  453. };
  454. this.getWrapperElement = function() {
  455. return this.ace.container;
  456. };
  457. var optMap = {
  458. indentWithTabs: "useSoftTabs",
  459. indentUnit: "tabSize",
  460. tabSize: "tabSize",
  461. firstLineNumber: "firstLineNumber",
  462. readOnly: "readOnly"
  463. };
  464. this.setOption = function(name, val) {
  465. this.state[name] = val;
  466. switch (name) {
  467. case 'indentWithTabs':
  468. name = optMap[name];
  469. val = !val;
  470. break;
  471. case 'keyMap':
  472. this.state.$keyMap = val;
  473. return;
  474. break;
  475. default:
  476. name = optMap[name];
  477. }
  478. if (name)
  479. this.ace.setOption(name, val);
  480. };
  481. this.getOption = function(name, val) {
  482. var aceOpt = optMap[name];
  483. if (aceOpt)
  484. val = this.ace.getOption(aceOpt);
  485. switch (name) {
  486. case 'indentWithTabs':
  487. name = optMap[name];
  488. return !val;
  489. case 'keyMap':
  490. return this.state.$keyMap;
  491. }
  492. return aceOpt ? val : this.state[name];
  493. };
  494. this.toggleOverwrite = function(on) {
  495. this.state.overwrite = on;
  496. return this.ace.setOverwrite(on);
  497. };
  498. this.addOverlay = function(o) {
  499. if (!this.$searchHighlight || !this.$searchHighlight.session) {
  500. var highlight = new SearchHighlight(null, "ace_highlight-marker", "text");
  501. var marker = this.ace.session.addDynamicMarker(highlight);
  502. highlight.id = marker.id;
  503. highlight.session = this.ace.session;
  504. highlight.destroy = function(o) {
  505. highlight.session.off("change", highlight.updateOnChange);
  506. highlight.session.off("changeEditor", highlight.destroy);
  507. highlight.session.removeMarker(highlight.id);
  508. highlight.session = null;
  509. };
  510. highlight.updateOnChange = function(delta) {
  511. var row = delta.start.row;
  512. if (row == delta.end.row) highlight.cache[row] = undefined;
  513. else highlight.cache.splice(row, highlight.cache.length);
  514. };
  515. highlight.session.on("changeEditor", highlight.destroy);
  516. highlight.session.on("change", highlight.updateOnChange);
  517. }
  518. var re = new RegExp(o.query.source, "gmi");
  519. this.$searchHighlight = o.highlight = highlight;
  520. this.$searchHighlight.setRegexp(re);
  521. this.ace.renderer.updateBackMarkers();
  522. };
  523. this.removeOverlay = function(o) {
  524. if (this.$searchHighlight && this.$searchHighlight.session) {
  525. this.$searchHighlight.destroy();
  526. }
  527. };
  528. this.getScrollInfo = function() {
  529. var renderer = this.ace.renderer;
  530. var config = renderer.layerConfig;
  531. return {
  532. left: renderer.scrollLeft,
  533. top: renderer.scrollTop,
  534. height: config.maxHeight,
  535. width: config.width,
  536. clientHeight: config.height,
  537. clientWidth: config.width
  538. };
  539. };
  540. this.getValue = function() {
  541. return this.ace.getValue();
  542. };
  543. this.setValue = function(v) {
  544. return this.ace.setValue(v, -1);
  545. };
  546. this.getTokenTypeAt = function(pos) {
  547. var token = this.ace.session.getTokenAt(pos.line, pos.ch);
  548. return token && /comment|string/.test(token.type) ? "string" : "";
  549. };
  550. this.findMatchingBracket = function(pos) {
  551. var m = this.ace.session.findMatchingBracket(toAcePos(pos));
  552. return {to: m && toCmPos(m)};
  553. };
  554. this.indentLine = function(line, method) {
  555. if (method === true)
  556. this.ace.session.indentRows(line, line, "\t");
  557. else if (method === false)
  558. this.ace.session.outdentRows(new Range(line, 0, line, 0));
  559. };
  560. this.indexFromPos = function(pos) {
  561. return this.ace.session.doc.positionToIndex(toAcePos(pos));
  562. };
  563. this.posFromIndex = function(index) {
  564. return toCmPos(this.ace.session.doc.indexToPosition(index));
  565. };
  566. this.focus = function(index) {
  567. return this.ace.textInput.focus();
  568. };
  569. this.blur = function(index) {
  570. return this.ace.blur();
  571. };
  572. this.defaultTextHeight = function(index) {
  573. return this.ace.renderer.layerConfig.lineHeight;
  574. };
  575. this.scanForBracket = function(pos, dir, _, options) {
  576. var re = options.bracketRegex.source;
  577. var tokenRe = /paren|text|operator|tag/;
  578. if (dir == 1) {
  579. var m = this.ace.session.$findClosingBracket(re.slice(1, 2), toAcePos(pos), tokenRe);
  580. } else {
  581. var m = this.ace.session.$findOpeningBracket(re.slice(-2, -1), {row: pos.line, column: pos.ch + 1}, tokenRe);
  582. }
  583. return m && {pos: toCmPos(m)};
  584. };
  585. this.refresh = function() {
  586. return this.ace.resize(true);
  587. };
  588. this.getMode = function() {
  589. return { name : this.getOption("mode") };
  590. };
  591. this.execCommand = function(name) {
  592. if (name == "indentAuto") this.ace.execCommand("autoindent");
  593. else console.log(name + " is not implemented");
  594. };
  595. }).call(CodeMirror.prototype);
  596. function toAcePos(cmPos) {
  597. return {row: cmPos.line, column: cmPos.ch};
  598. }
  599. function toCmPos(acePos) {
  600. return new Pos(acePos.row, acePos.column);
  601. }
  602. var StringStream = CodeMirror.StringStream = function(string, tabSize) {
  603. this.pos = this.start = 0;
  604. this.string = string;
  605. this.tabSize = tabSize || 8;
  606. this.lastColumnPos = this.lastColumnValue = 0;
  607. this.lineStart = 0;
  608. };
  609. StringStream.prototype = {
  610. eol: function() {return this.pos >= this.string.length;},
  611. sol: function() {return this.pos == this.lineStart;},
  612. peek: function() {return this.string.charAt(this.pos) || undefined;},
  613. next: function() {
  614. if (this.pos < this.string.length)
  615. return this.string.charAt(this.pos++);
  616. },
  617. eat: function(match) {
  618. var ch = this.string.charAt(this.pos);
  619. if (typeof match == "string") var ok = ch == match;
  620. else var ok = ch && (match.test ? match.test(ch) : match(ch));
  621. if (ok) {++this.pos; return ch;}
  622. },
  623. eatWhile: function(match) {
  624. var start = this.pos;
  625. while (this.eat(match)){}
  626. return this.pos > start;
  627. },
  628. eatSpace: function() {
  629. var start = this.pos;
  630. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
  631. return this.pos > start;
  632. },
  633. skipToEnd: function() {this.pos = this.string.length;},
  634. skipTo: function(ch) {
  635. var found = this.string.indexOf(ch, this.pos);
  636. if (found > -1) {this.pos = found; return true;}
  637. },
  638. backUp: function(n) {this.pos -= n;},
  639. column: function() {
  640. throw "not implemented";
  641. },
  642. indentation: function() {
  643. throw "not implemented";
  644. },
  645. match: function(pattern, consume, caseInsensitive) {
  646. if (typeof pattern == "string") {
  647. var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
  648. var substr = this.string.substr(this.pos, pattern.length);
  649. if (cased(substr) == cased(pattern)) {
  650. if (consume !== false) this.pos += pattern.length;
  651. return true;
  652. }
  653. } else {
  654. var match = this.string.slice(this.pos).match(pattern);
  655. if (match && match.index > 0) return null;
  656. if (match && consume !== false) this.pos += match[0].length;
  657. return match;
  658. }
  659. },
  660. current: function(){return this.string.slice(this.start, this.pos);},
  661. hideFirstChars: function(n, inner) {
  662. this.lineStart += n;
  663. try { return inner(); }
  664. finally { this.lineStart -= n; }
  665. }
  666. };
  667. CodeMirror.defineExtension = function(name, fn) {
  668. CodeMirror.prototype[name] = fn;
  669. };
  670. dom.importCssString(".normal-mode .ace_cursor{\
  671. border: none;\
  672. background-color: rgba(255,0,0,0.5);\
  673. }\
  674. .normal-mode .ace_hidden-cursors .ace_cursor{\
  675. background-color: transparent;\
  676. border: 1px solid red;\
  677. opacity: 0.7\
  678. }\
  679. .ace_dialog {\
  680. position: absolute;\
  681. left: 0; right: 0;\
  682. background: inherit;\
  683. z-index: 15;\
  684. padding: .1em .8em;\
  685. overflow: hidden;\
  686. color: inherit;\
  687. }\
  688. .ace_dialog-top {\
  689. border-bottom: 1px solid #444;\
  690. top: 0;\
  691. }\
  692. .ace_dialog-bottom {\
  693. border-top: 1px solid #444;\
  694. bottom: 0;\
  695. }\
  696. .ace_dialog input {\
  697. border: none;\
  698. outline: none;\
  699. background: transparent;\
  700. width: 20em;\
  701. color: inherit;\
  702. font-family: monospace;\
  703. }", "vimMode");
  704. (function() {
  705. function dialogDiv(cm, template, bottom) {
  706. var wrap = cm.ace.container;
  707. var dialog;
  708. dialog = wrap.appendChild(document.createElement("div"));
  709. if (bottom)
  710. dialog.className = "ace_dialog ace_dialog-bottom";
  711. else
  712. dialog.className = "ace_dialog ace_dialog-top";
  713. if (typeof template == "string") {
  714. dialog.innerHTML = template;
  715. } else { // Assuming it's a detached DOM element.
  716. dialog.appendChild(template);
  717. }
  718. return dialog;
  719. }
  720. function closeNotification(cm, newVal) {
  721. if (cm.state.currentNotificationClose)
  722. cm.state.currentNotificationClose();
  723. cm.state.currentNotificationClose = newVal;
  724. }
  725. CodeMirror.defineExtension("openDialog", function(template, callback, options) {
  726. if (this.virtualSelectionMode()) return;
  727. if (!options) options = {};
  728. closeNotification(this, null);
  729. var dialog = dialogDiv(this, template, options.bottom);
  730. var closed = false, me = this;
  731. this.state.dialog = dialog;
  732. function close(newVal) {
  733. if (typeof newVal == 'string') {
  734. inp.value = newVal;
  735. } else {
  736. if (closed) return;
  737. if (newVal && newVal.type == "blur") {
  738. if (document.activeElement === inp)
  739. return;
  740. }
  741. me.state.dialog = null;
  742. closed = true;
  743. dialog.parentNode.removeChild(dialog);
  744. me.focus();
  745. if (options.onClose) options.onClose(dialog);
  746. }
  747. }
  748. var inp = dialog.getElementsByTagName("input")[0], button;
  749. if (inp) {
  750. if (options.value) {
  751. inp.value = options.value;
  752. if (options.selectValueOnOpen !== false) inp.select();
  753. }
  754. if (options.onInput)
  755. CodeMirror.on(inp, "input", function(e) { options.onInput(e, inp.value, close);});
  756. if (options.onKeyUp)
  757. CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);});
  758. CodeMirror.on(inp, "keydown", function(e) {
  759. if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; }
  760. if (e.keyCode == 13) callback(inp.value);
  761. if (e.keyCode == 27 || (options.closeOnEnter !== false && e.keyCode == 13)) {
  762. inp.blur();
  763. CodeMirror.e_stop(e);
  764. close();
  765. }
  766. });
  767. if (options.closeOnBlur !== false) CodeMirror.on(inp, "blur", close);
  768. inp.focus();
  769. } else if (button = dialog.getElementsByTagName("button")[0]) {
  770. CodeMirror.on(button, "click", function() {
  771. close();
  772. me.focus();
  773. });
  774. if (options.closeOnBlur !== false) CodeMirror.on(button, "blur", close);
  775. button.focus();
  776. }
  777. return close;
  778. });
  779. CodeMirror.defineExtension("openNotification", function(template, options) {
  780. if (this.virtualSelectionMode()) return;
  781. closeNotification(this, close);
  782. var dialog = dialogDiv(this, template, options && options.bottom);
  783. var closed = false, doneTimer;
  784. var duration = options && typeof options.duration !== "undefined" ? options.duration : 5000;
  785. function close() {
  786. if (closed) return;
  787. closed = true;
  788. clearTimeout(doneTimer);
  789. dialog.parentNode.removeChild(dialog);
  790. }
  791. CodeMirror.on(dialog, 'click', function(e) {
  792. CodeMirror.e_preventDefault(e);
  793. close();
  794. });
  795. if (duration)
  796. doneTimer = setTimeout(close, duration);
  797. return close;
  798. });
  799. })();
  800. var defaultKeymap = [
  801. { keys: '<Left>', type: 'keyToKey', toKeys: 'h' },
  802. { keys: '<Right>', type: 'keyToKey', toKeys: 'l' },
  803. { keys: '<Up>', type: 'keyToKey', toKeys: 'k' },
  804. { keys: '<Down>', type: 'keyToKey', toKeys: 'j' },
  805. { keys: '<Space>', type: 'keyToKey', toKeys: 'l' },
  806. { keys: '<BS>', type: 'keyToKey', toKeys: 'h', context: 'normal'},
  807. { keys: '<Del>', type: 'keyToKey', toKeys: 'x', context: 'normal'},
  808. { keys: '<C-Space>', type: 'keyToKey', toKeys: 'W' },
  809. { keys: '<C-BS>', type: 'keyToKey', toKeys: 'B', context: 'normal' },
  810. { keys: '<S-Space>', type: 'keyToKey', toKeys: 'w' },
  811. { keys: '<S-BS>', type: 'keyToKey', toKeys: 'b', context: 'normal' },
  812. { keys: '<C-n>', type: 'keyToKey', toKeys: 'j' },
  813. { keys: '<C-p>', type: 'keyToKey', toKeys: 'k' },
  814. { keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>' },
  815. { keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>' },
  816. { keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
  817. { keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
  818. { keys: '<C-Esc>', type: 'keyToKey', toKeys: '<Esc>' }, // ace_patch ipad keyboard sends C-Esc instead of C-[
  819. { keys: '<C-Esc>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
  820. { keys: 's', type: 'keyToKey', toKeys: 'cl', context: 'normal' },
  821. { keys: 's', type: 'keyToKey', toKeys: 'c', context: 'visual'},
  822. { keys: 'S', type: 'keyToKey', toKeys: 'cc', context: 'normal' },
  823. { keys: 'S', type: 'keyToKey', toKeys: 'VdO', context: 'visual' },
  824. { keys: '<Home>', type: 'keyToKey', toKeys: '0' },
  825. { keys: '<End>', type: 'keyToKey', toKeys: '$' },
  826. { keys: '<PageUp>', type: 'keyToKey', toKeys: '<C-b>' },
  827. { keys: '<PageDown>', type: 'keyToKey', toKeys: '<C-f>' },
  828. { keys: '<CR>', type: 'keyToKey', toKeys: 'j^', context: 'normal' },
  829. { keys: '<Ins>', type: 'action', action: 'toggleOverwrite', context: 'insert' },
  830. { keys: 'H', type: 'motion', motion: 'moveToTopLine', motionArgs: { linewise: true, toJumplist: true }},
  831. { keys: 'M', type: 'motion', motion: 'moveToMiddleLine', motionArgs: { linewise: true, toJumplist: true }},
  832. { keys: 'L', type: 'motion', motion: 'moveToBottomLine', motionArgs: { linewise: true, toJumplist: true }},
  833. { keys: 'h', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: false }},
  834. { keys: 'l', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: true }},
  835. { keys: 'j', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, linewise: true }},
  836. { keys: 'k', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, linewise: true }},
  837. { keys: 'gj', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: true }},
  838. { keys: 'gk', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: false }},
  839. { keys: 'w', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false }},
  840. { keys: 'W', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false, bigWord: true }},
  841. { keys: 'e', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, inclusive: true }},
  842. { keys: 'E', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, bigWord: true, inclusive: true }},
  843. { keys: 'b', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }},
  844. { keys: 'B', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false, bigWord: true }},
  845. { keys: 'ge', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, inclusive: true }},
  846. { keys: 'gE', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, bigWord: true, inclusive: true }},
  847. { keys: '{', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: false, toJumplist: true }},
  848. { keys: '}', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: true, toJumplist: true }},
  849. { keys: '(', type: 'motion', motion: 'moveBySentence', motionArgs: { forward: false }},
  850. { keys: ')', type: 'motion', motion: 'moveBySentence', motionArgs: { forward: true }},
  851. { keys: '<C-f>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: true }},
  852. { keys: '<C-b>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: false }},
  853. { keys: '<C-d>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: true, explicitRepeat: true }},
  854. { keys: '<C-u>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: false, explicitRepeat: true }},
  855. { keys: 'gg', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},
  856. { keys: 'G', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},
  857. { keys: '0', type: 'motion', motion: 'moveToStartOfLine' },
  858. { keys: '^', type: 'motion', motion: 'moveToFirstNonWhiteSpaceCharacter' },
  859. { keys: '+', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true }},
  860. { keys: '-', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, toFirstChar:true }},
  861. { keys: '_', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},
  862. { keys: '$', type: 'motion', motion: 'moveToEol', motionArgs: { inclusive: true }},
  863. { keys: '%', type: 'motion', motion: 'moveToMatchedSymbol', motionArgs: { inclusive: true, toJumplist: true }},
  864. { keys: 'f<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: true , inclusive: true }},
  865. { keys: 'F<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: false }},
  866. { keys: 't<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: true, inclusive: true }},
  867. { keys: 'T<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: false }},
  868. { keys: ';', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: true }},
  869. { keys: ',', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: false }},
  870. { keys: '\'<character>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true, linewise: true}},
  871. { keys: '`<character>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true}},
  872. { keys: ']`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
  873. { keys: '[`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
  874. { keys: ']\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
  875. { keys: '[\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
  876. { keys: ']p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true, matchIndent: true}},
  877. { keys: '[p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true, matchIndent: true}},
  878. { keys: ']<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: true, toJumplist: true}},
  879. { keys: '[<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: false, toJumplist: true}},
  880. { keys: '|', type: 'motion', motion: 'moveToColumn'},
  881. { keys: 'o', type: 'motion', motion: 'moveToOtherHighlightedEnd', context:'visual'},
  882. { keys: 'O', type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: {sameLine: true}, context:'visual'},
  883. { keys: 'd', type: 'operator', operator: 'delete' },
  884. { keys: 'y', type: 'operator', operator: 'yank' },
  885. { keys: 'c', type: 'operator', operator: 'change' },
  886. { keys: '=', type: 'operator', operator: 'indentAuto' },
  887. { keys: '>', type: 'operator', operator: 'indent', operatorArgs: { indentRight: true }},
  888. { keys: '<', type: 'operator', operator: 'indent', operatorArgs: { indentRight: false }},
  889. { keys: 'g~', type: 'operator', operator: 'changeCase' },
  890. { keys: 'gu', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, isEdit: true },
  891. { keys: 'gU', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, isEdit: true },
  892. { keys: 'n', type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: true }},
  893. { keys: 'N', type: 'motion', motion: 'findNext', motionArgs: { forward: false, toJumplist: true }},
  894. { keys: 'x', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorMotionArgs: { visualLine: false }},
  895. { keys: 'X', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: false }, operatorMotionArgs: { visualLine: true }},
  896. { keys: 'D', type: 'operatorMotion', operator: 'delete', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
  897. { keys: 'D', type: 'operator', operator: 'delete', operatorArgs: { linewise: true }, context: 'visual'},
  898. { keys: 'Y', type: 'operatorMotion', operator: 'yank', motion: 'expandToLine', motionArgs: { linewise: true }, context: 'normal'},
  899. { keys: 'Y', type: 'operator', operator: 'yank', operatorArgs: { linewise: true }, context: 'visual'},
  900. { keys: 'C', type: 'operatorMotion', operator: 'change', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
  901. { keys: 'C', type: 'operator', operator: 'change', operatorArgs: { linewise: true }, context: 'visual'},
  902. { keys: '~', type: 'operatorMotion', operator: 'changeCase', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorArgs: { shouldMoveCursor: true }, context: 'normal'},
  903. { keys: '~', type: 'operator', operator: 'changeCase', context: 'visual'},
  904. { keys: '<C-w>', type: 'operatorMotion', operator: 'delete', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }, context: 'insert' },
  905. { keys: '<C-w>', type: 'idle', context: 'normal' },
  906. { keys: '<C-i>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: true }},
  907. { keys: '<C-o>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: false }},
  908. { keys: '<C-e>', type: 'action', action: 'scroll', actionArgs: { forward: true, linewise: true }},
  909. { keys: '<C-y>', type: 'action', action: 'scroll', actionArgs: { forward: false, linewise: true }},
  910. { keys: 'a', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'charAfter' }, context: 'normal' },
  911. { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'eol' }, context: 'normal' },
  912. { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' },
  913. { keys: 'i', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'inplace' }, context: 'normal' },
  914. { keys: 'gi', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'lastEdit' }, context: 'normal' },
  915. { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'firstNonBlank'}, context: 'normal' },
  916. { keys: 'gI', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'bol'}, context: 'normal' },
  917. { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'startOfSelectedArea' }, context: 'visual' },
  918. { keys: 'o', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: true }, context: 'normal' },
  919. { keys: 'O', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: false }, context: 'normal' },
  920. { keys: 'v', type: 'action', action: 'toggleVisualMode' },
  921. { keys: 'V', type: 'action', action: 'toggleVisualMode', actionArgs: { linewise: true }},
  922. { keys: '<C-v>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }},
  923. { keys: '<C-q>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }},
  924. { keys: 'gv', type: 'action', action: 'reselectLastSelection' },
  925. { keys: 'J', type: 'action', action: 'joinLines', isEdit: true },
  926. { keys: 'gJ', type: 'action', action: 'joinLines', actionArgs: { keepSpaces: true }, isEdit: true },
  927. { keys: 'p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true }},
  928. { keys: 'P', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true }},
  929. { keys: 'r<character>', type: 'action', action: 'replace', isEdit: true },
  930. { keys: '@<character>', type: 'action', action: 'replayMacro' },
  931. { keys: 'q<character>', type: 'action', action: 'enterMacroRecordMode' },
  932. { keys: 'R', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { replace: true }, context: 'normal'},
  933. { keys: 'R', type: 'operator', operator: 'change', operatorArgs: { linewise: true, fullLine: true }, context: 'visual', exitVisualBlock: true},
  934. { keys: 'u', type: 'action', action: 'undo', context: 'normal' },
  935. { keys: 'u', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, context: 'visual', isEdit: true },
  936. { keys: 'U', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, context: 'visual', isEdit: true },
  937. { keys: '<C-r>', type: 'action', action: 'redo' },
  938. { keys: 'm<character>', type: 'action', action: 'setMark' },
  939. { keys: '"<character>', type: 'action', action: 'setRegister' },
  940. { keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }},
  941. { keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
  942. { keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }},
  943. { keys: 'z<CR>', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
  944. { keys: 'z-', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }},
  945. { keys: 'zb', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
  946. { keys: '.', type: 'action', action: 'repeatLastEdit' },
  947. { keys: '<C-a>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: true, backtrack: false}},
  948. { keys: '<C-x>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: false, backtrack: false}},
  949. { keys: '<C-t>', type: 'action', action: 'indent', actionArgs: { indentRight: true }, context: 'insert' },
  950. { keys: '<C-d>', type: 'action', action: 'indent', actionArgs: { indentRight: false }, context: 'insert' },
  951. { keys: 'a<character>', type: 'motion', motion: 'textObjectManipulation' },
  952. { keys: 'i<character>', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }},
  953. { keys: '/', type: 'search', searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},
  954. { keys: '?', type: 'search', searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},
  955. { keys: '*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
  956. { keys: '#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
  957. { keys: 'g*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},
  958. { keys: 'g#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},
  959. { keys: ':', type: 'ex' }
  960. ];
  961. var defaultKeymapLength = defaultKeymap.length;
  962. var defaultExCommandMap = [
  963. { name: 'colorscheme', shortName: 'colo' },
  964. { name: 'map' },
  965. { name: 'imap', shortName: 'im' },
  966. { name: 'nmap', shortName: 'nm' },
  967. { name: 'vmap', shortName: 'vm' },
  968. { name: 'unmap' },
  969. { name: 'write', shortName: 'w' },
  970. { name: 'undo', shortName: 'u' },
  971. { name: 'redo', shortName: 'red' },
  972. { name: 'set', shortName: 'se' },
  973. { name: 'set', shortName: 'se' },
  974. { name: 'setlocal', shortName: 'setl' },
  975. { name: 'setglobal', shortName: 'setg' },
  976. { name: 'sort', shortName: 'sor' },
  977. { name: 'substitute', shortName: 's', possiblyAsync: true },
  978. { name: 'nohlsearch', shortName: 'noh' },
  979. { name: 'yank', shortName: 'y' },
  980. { name: 'delmarks', shortName: 'delm' },
  981. { name: 'registers', shortName: 'reg', excludeFromCommandHistory: true },
  982. { name: 'global', shortName: 'g' }
  983. ];
  984. var Pos = CodeMirror.Pos;
  985. var Vim = function() { return vimApi; } //{
  986. function enterVimMode(cm) {
  987. cm.setOption('disableInput', true);
  988. cm.setOption('showCursorWhenSelecting', false);
  989. CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
  990. cm.on('cursorActivity', onCursorActivity);
  991. maybeInitVimState(cm);
  992. CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm));
  993. }
  994. function leaveVimMode(cm) {
  995. cm.setOption('disableInput', false);
  996. cm.off('cursorActivity', onCursorActivity);
  997. CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm));
  998. cm.state.vim = null;
  999. }
  1000. function detachVimMap(cm, next) {
  1001. if (this == CodeMirror.keyMap.vim)
  1002. CodeMirror.rmClass(cm.getWrapperElement(), "cm-fat-cursor");
  1003. if (!next || next.attach != attachVimMap)
  1004. leaveVimMode(cm);
  1005. }
  1006. function attachVimMap(cm, prev) {
  1007. if (this == CodeMirror.keyMap.vim)
  1008. CodeMirror.addClass(cm.getWrapperElement(), "cm-fat-cursor");
  1009. if (!prev || prev.attach != attachVimMap)
  1010. enterVimMode(cm);
  1011. }
  1012. CodeMirror.defineOption('vimMode', false, function(cm, val, prev) {
  1013. if (val && cm.getOption("keyMap") != "vim")
  1014. cm.setOption("keyMap", "vim");
  1015. else if (!val && prev != CodeMirror.Init && /^vim/.test(cm.getOption("keyMap")))
  1016. cm.setOption("keyMap", "default");
  1017. });
  1018. function cmKey(key, cm) {
  1019. if (!cm) { return undefined; }
  1020. if (this[key]) { return this[key]; }
  1021. var vimKey = cmKeyToVimKey(key);
  1022. if (!vimKey) {
  1023. return false;
  1024. }
  1025. var cmd = CodeMirror.Vim.findKey(cm, vimKey);
  1026. if (typeof cmd == 'function') {
  1027. CodeMirror.signal(cm, 'vim-keypress', vimKey);
  1028. }
  1029. return cmd;
  1030. }
  1031. var modifiers = {'Shift': 'S', 'Ctrl': 'C', 'Alt': 'A', 'Cmd': 'D', 'Mod': 'A'};
  1032. var specialKeys = {Enter:'CR',Backspace:'BS',Delete:'Del',Insert:'Ins'};
  1033. function cmKeyToVimKey(key) {
  1034. if (key.charAt(0) == '\'') {
  1035. return key.charAt(1);
  1036. }
  1037. var pieces = key.split(/-(?!$)/);
  1038. var lastPiece = pieces[pieces.length - 1];
  1039. if (pieces.length == 1 && pieces[0].length == 1) {
  1040. return false;
  1041. } else if (pieces.length == 2 && pieces[0] == 'Shift' && lastPiece.length == 1) {
  1042. return false;
  1043. }
  1044. var hasCharacter = false;
  1045. for (var i = 0; i < pieces.length; i++) {
  1046. var piece = pieces[i];
  1047. if (piece in modifiers) { pieces[i] = modifiers[piece]; }
  1048. else { hasCharacter = true; }
  1049. if (piece in specialKeys) { pieces[i] = specialKeys[piece]; }
  1050. }
  1051. if (!hasCharacter) {
  1052. return false;
  1053. }
  1054. if (isUpperCase(lastPiece)) {
  1055. pieces[pieces.length - 1] = lastPiece.toLowerCase();
  1056. }
  1057. return '<' + pieces.join('-') + '>';
  1058. }
  1059. function getOnPasteFn(cm) {
  1060. var vim = cm.state.vim;
  1061. if (!vim.onPasteFn) {
  1062. vim.onPasteFn = function() {
  1063. if (!vim.insertMode) {
  1064. cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
  1065. actions.enterInsertMode(cm, {}, vim);
  1066. }
  1067. };
  1068. }
  1069. return vim.onPasteFn;
  1070. }
  1071. var numberRegex = /[\d]/;
  1072. var wordCharTest = [CodeMirror.isWordChar, function(ch) {
  1073. return ch && !CodeMirror.isWordChar(ch) && !/\s/.test(ch);
  1074. }], bigWordCharTest = [function(ch) {
  1075. return /\S/.test(ch);
  1076. }];
  1077. function makeKeyRange(start, size) {
  1078. var keys = [];
  1079. for (var i = start; i < start + size; i++) {
  1080. keys.push(String.fromCharCode(i));
  1081. }
  1082. return keys;
  1083. }
  1084. var upperCaseAlphabet = makeKeyRange(65, 26);
  1085. var lowerCaseAlphabet = makeKeyRange(97, 26);
  1086. var numbers = makeKeyRange(48, 10);
  1087. var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']);
  1088. var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"', '.', ':', '/']);
  1089. function isLine(cm, line) {
  1090. return line >= cm.firstLine() && line <= cm.lastLine();
  1091. }
  1092. function isLowerCase(k) {
  1093. return (/^[a-z]$/).test(k);
  1094. }
  1095. function isMatchableSymbol(k) {
  1096. return '()[]{}'.indexOf(k) != -1;
  1097. }
  1098. function isNumber(k) {
  1099. return numberRegex.test(k);
  1100. }
  1101. function isUpperCase(k) {
  1102. return (/^[A-Z]$/).test(k);
  1103. }
  1104. function isWhiteSpaceString(k) {
  1105. return (/^\s*$/).test(k);
  1106. }
  1107. function isEndOfSentenceSymbol(k) {
  1108. return '.?!'.indexOf(k) != -1;
  1109. }
  1110. function inArray(val, arr) {
  1111. for (var i = 0; i < arr.length; i++) {
  1112. if (arr[i] == val) {
  1113. return true;
  1114. }
  1115. }
  1116. return false;
  1117. }
  1118. var options = {};
  1119. function defineOption(name, defaultValue, type, aliases, callback) {
  1120. if (defaultValue === undefined && !callback) {
  1121. throw Error('defaultValue is required unless callback is provided');
  1122. }
  1123. if (!type) { type = 'string'; }
  1124. options[name] = {
  1125. type: type,
  1126. defaultValue: defaultValue,
  1127. callback: callback
  1128. };
  1129. if (aliases) {
  1130. for (var i = 0; i < aliases.length; i++) {
  1131. options[aliases[i]] = options[name];
  1132. }
  1133. }
  1134. if (defaultValue) {
  1135. setOption(name, defaultValue);
  1136. }
  1137. }
  1138. function setOption(name, value, cm, cfg) {
  1139. var option = options[name];
  1140. cfg = cfg || {};
  1141. var scope = cfg.scope;
  1142. if (!option) {
  1143. return new Error('Unknown option: ' + name);
  1144. }
  1145. if (option.type == 'boolean') {
  1146. if (value && value !== true) {
  1147. return new Error('Invalid argument: ' + name + '=' + value);
  1148. } else if (value !== false) {
  1149. value = true;
  1150. }
  1151. }
  1152. if (option.callback) {
  1153. if (scope !== 'local') {
  1154. option.callback(value, undefined);
  1155. }
  1156. if (scope !== 'global' && cm) {
  1157. option.callback(value, cm);
  1158. }
  1159. } else {
  1160. if (scope !== 'local') {
  1161. option.value = option.type == 'boolean' ? !!value : value;
  1162. }
  1163. if (scope !== 'global' && cm) {
  1164. cm.state.vim.options[name] = {value: value};
  1165. }
  1166. }
  1167. }
  1168. function getOption(name, cm, cfg) {
  1169. var option = options[name];
  1170. cfg = cfg || {};
  1171. var scope = cfg.scope;
  1172. if (!option) {
  1173. return new Error('Unknown option: ' + name);
  1174. }
  1175. if (option.callback) {
  1176. var local = cm && option.callback(undefined, cm);
  1177. if (scope !== 'global' && local !== undefined) {
  1178. return local;
  1179. }
  1180. if (scope !== 'local') {
  1181. return option.callback();
  1182. }
  1183. return;
  1184. } else {
  1185. var local = (scope !== 'global') && (cm && cm.state.vim.options[name]);
  1186. return (local || (scope !== 'local') && option || {}).value;
  1187. }
  1188. }
  1189. defineOption('filetype', undefined, 'string', ['ft'], function(name, cm) {
  1190. if (cm === undefined) {
  1191. return;
  1192. }
  1193. if (name === undefined) {
  1194. var mode = cm.getOption('mode');
  1195. return mode == 'null' ? '' : mode;
  1196. } else {
  1197. var mode = name == '' ? 'null' : name;
  1198. cm.setOption('mode', mode);
  1199. }
  1200. });
  1201. var createCircularJumpList = function() {
  1202. var size = 100;
  1203. var pointer = -1;
  1204. var head = 0;
  1205. var tail = 0;
  1206. var buffer = new Array(size);
  1207. function add(cm, oldCur, newCur) {
  1208. var current = pointer % size;
  1209. var curMark = buffer[current];
  1210. function useNextSlot(cursor) {
  1211. var next = ++pointer % size;
  1212. var trashMark = buffer[next];
  1213. if (trashMark) {
  1214. trashMark.clear();
  1215. }
  1216. buffer[next] = cm.setBookmark(cursor);
  1217. }
  1218. if (curMark) {
  1219. var markPos = curMark.find();
  1220. if (markPos && !cursorEqual(markPos, oldCur)) {
  1221. useNextSlot(oldCur);
  1222. }
  1223. } else {
  1224. useNextSlot(oldCur);
  1225. }
  1226. useNextSlot(newCur);
  1227. head = pointer;
  1228. tail = pointer - size + 1;
  1229. if (tail < 0) {
  1230. tail = 0;
  1231. }
  1232. }
  1233. function move(cm, offset) {
  1234. pointer += offset;
  1235. if (pointer > head) {
  1236. pointer = head;
  1237. } else if (pointer < tail) {
  1238. pointer = tail;
  1239. }
  1240. var mark = buffer[(size + pointer) % size];
  1241. if (mark && !mark.find()) {
  1242. var inc = offset > 0 ? 1 : -1;
  1243. var newCur;
  1244. var oldCur = cm.getCursor();
  1245. do {
  1246. pointer += inc;
  1247. mark = buffer[(size + pointer) % size];
  1248. if (mark &&
  1249. (newCur = mark.find()) &&
  1250. !cursorEqual(oldCur, newCur)) {
  1251. break;
  1252. }
  1253. } while (pointer < head && pointer > tail);
  1254. }
  1255. return mark;
  1256. }
  1257. function find(cm, offset) {
  1258. var oldPointer = pointer;
  1259. var mark = move(cm, offset);
  1260. pointer = oldPointer;
  1261. return mark && mark.find();
  1262. }
  1263. return {
  1264. cachedCursor: undefined, //used for # and * jumps
  1265. add: add,
  1266. find: find,
  1267. move: move
  1268. };
  1269. };
  1270. var createInsertModeChanges = function(c) {
  1271. if (c) {
  1272. return {
  1273. changes: c.changes,
  1274. expectCursorActivityForChange: c.expectCursorActivityForChange
  1275. };
  1276. }
  1277. return {
  1278. changes: [],
  1279. expectCursorActivityForChange: false
  1280. };
  1281. };
  1282. function MacroModeState() {
  1283. this.latestRegister = undefined;
  1284. this.isPlaying = false;
  1285. this.isRecording = false;
  1286. this.replaySearchQueries = [];
  1287. this.onRecordingDone = undefined;
  1288. this.lastInsertModeChanges = createInsertModeChanges();
  1289. }
  1290. MacroModeState.prototype = {
  1291. exitMacroRecordMode: function() {
  1292. var macroModeState = vimGlobalState.macroModeState;
  1293. if (macroModeState.onRecordingDone) {
  1294. macroModeState.onRecordingDone(); // close dialog
  1295. }
  1296. macroModeState.onRecordingDone = undefined;
  1297. macroModeState.isRecording = false;
  1298. },
  1299. enterMacroRecordMode: function(cm, registerName) {
  1300. var register =
  1301. vimGlobalState.registerController.getRegister(registerName);
  1302. if (register) {
  1303. register.clear();
  1304. this.latestRegister = registerName;
  1305. if (cm.openDialog) {
  1306. this.onRecordingDone = cm.openDialog(
  1307. '(recording)['+registerName+']', null, {bottom:true});
  1308. }
  1309. this.isRecording = true;
  1310. }
  1311. }
  1312. };
  1313. function maybeInitVimState(cm) {
  1314. if (!cm.state.vim) {
  1315. cm.state.vim = {
  1316. inputState: new InputState(),
  1317. lastEditInputState: undefined,
  1318. lastEditActionCommand: undefined,
  1319. lastHPos: -1,
  1320. lastHSPos: -1,
  1321. lastMotion: null,
  1322. marks: {},
  1323. fakeCursor: null,
  1324. insertMode: false,
  1325. insertModeRepeat: undefined,
  1326. visualMode: false,
  1327. visualLine: false,
  1328. visualBlock: false,
  1329. lastSelection: null,
  1330. lastPastedText: null,
  1331. sel: {},
  1332. options: {}
  1333. };
  1334. }
  1335. return cm.state.vim;
  1336. }
  1337. var vimGlobalState;
  1338. function resetVimGlobalState() {
  1339. vimGlobalState = {
  1340. searchQuery: null,
  1341. searchIsReversed: false,
  1342. lastSubstituteReplacePart: undefined,
  1343. jumpList: createCircularJumpList(),
  1344. macroModeState: new MacroModeState,
  1345. lastCharacterSearch: {increment:0, forward:true, selectedCharacter:''},
  1346. registerController: new RegisterController({}),
  1347. searchHistoryController: new HistoryController(),
  1348. exCommandHistoryController : new HistoryController()
  1349. };
  1350. for (var optionName in options) {
  1351. var option = options[optionName];
  1352. option.value = option.defaultValue;
  1353. }
  1354. }
  1355. var lastInsertModeKeyTimer;
  1356. var vimApi= {
  1357. buildKeyMap: function() {
  1358. },
  1359. getRegisterController: function() {
  1360. return vimGlobalState.registerController;
  1361. },
  1362. resetVimGlobalState_: resetVimGlobalState,
  1363. getVimGlobalState_: function() {
  1364. return vimGlobalState;
  1365. },
  1366. maybeInitVimState_: maybeInitVimState,
  1367. suppressErrorLogging: false,
  1368. InsertModeKey: InsertModeKey,
  1369. map: function(lhs, rhs, ctx) {
  1370. exCommandDispatcher.map(lhs, rhs, ctx);
  1371. },
  1372. unmap: function(lhs, ctx) {
  1373. exCommandDispatcher.unmap(lhs, ctx);
  1374. },
  1375. noremap: function(lhs, rhs, ctx) {
  1376. function toCtxArray(ctx) {
  1377. return ctx ? [ctx] : ['normal', 'insert', 'visual'];
  1378. }
  1379. var ctxsToMap = toCtxArray(ctx);
  1380. var actualLength = defaultKeymap.length, origLength = defaultKeymapLength;
  1381. for (var i = actualLength - origLength;
  1382. i < actualLength && ctxsToMap.length;
  1383. i++) {
  1384. var mapping = defaultKeymap[i];
  1385. if (mapping.keys == rhs &&
  1386. (!ctx || !mapping.context || mapping.context === ctx) &&
  1387. mapping.type.substr(0, 2) !== 'ex' &&
  1388. mapping.type.substr(0, 3) !== 'key') {
  1389. var newMapping = {};
  1390. for (var key in mapping) {
  1391. newMapping[key] = mapping[key];
  1392. }
  1393. newMapping.keys = lhs;
  1394. if (ctx && !newMapping.context) {
  1395. newMapping.context = ctx;
  1396. }
  1397. this._mapCommand(newMapping);
  1398. var mappedCtxs = toCtxArray(mapping.context);
  1399. ctxsToMap = ctxsToMap.filter(function(el) { return mappedCtxs.indexOf(el) === -1; });
  1400. }
  1401. }
  1402. },
  1403. mapclear: function(ctx) {
  1404. var actualLength = defaultKeymap.length,
  1405. origLength = defaultKeymapLength;
  1406. var userKeymap = defaultKeymap.slice(0, actualLength - origLength);
  1407. defaultKeymap = defaultKeymap.slice(actualLength - origLength);
  1408. if (ctx) {
  1409. for (var i = userKeymap.length - 1; i >= 0; i--) {
  1410. var mapping = userKeymap[i];
  1411. if (ctx !== mapping.context) {
  1412. if (mapping.context) {
  1413. this._mapCommand(mapping);
  1414. } else {
  1415. var contexts = ['normal', 'insert', 'visual'];
  1416. for (var j in contexts) {
  1417. if (contexts[j] !== ctx) {
  1418. var newMapping = {};
  1419. for (var key in mapping) {
  1420. newMapping[key] = mapping[key];
  1421. }
  1422. newMapping.context = contexts[j];
  1423. this._mapCommand(newMapping);
  1424. }
  1425. }
  1426. }
  1427. }
  1428. }
  1429. }
  1430. },
  1431. setOption: setOption,
  1432. getOption: getOption,
  1433. defineOption: defineOption,
  1434. defineEx: function(name, prefix, func){
  1435. if (!prefix) {
  1436. prefix = name;
  1437. } else if (name.indexOf(prefix) !== 0) {
  1438. throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered');
  1439. }
  1440. exCommands[name]=func;
  1441. exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'};
  1442. },
  1443. handleKey: function (cm, key, origin) {
  1444. var command = this.findKey(cm, key, origin);
  1445. if (typeof command === 'function') {
  1446. return command();
  1447. }
  1448. },
  1449. findKey: function(cm, key, origin) {
  1450. var vim = maybeInitVimState(cm);
  1451. function handleMacroRecording() {
  1452. var macroModeState = vimGlobalState.macroModeState;
  1453. if (macroModeState.isRecording) {
  1454. if (key == 'q') {
  1455. macroModeState.exitMacroRecordMode();
  1456. clearInputState(cm);
  1457. return true;
  1458. }
  1459. if (origin != 'mapping') {
  1460. logKey(macroModeState, key);
  1461. }
  1462. }
  1463. }
  1464. function handleEsc() {
  1465. if (key == '<Esc>') {
  1466. clearInputState(cm);
  1467. if (vim.visualMode) {
  1468. exitVisualMode(cm);
  1469. } else if (vim.insertMode) {
  1470. exitInsertMode(cm);
  1471. }
  1472. return true;
  1473. }
  1474. }
  1475. function doKeyToKey(keys) {
  1476. var match;
  1477. while (keys) {
  1478. match = (/<\w+-.+?>|<\w+>|./).exec(keys);
  1479. key = match[0];
  1480. keys = keys.substring(match.index + key.length);
  1481. CodeMirror.Vim.handleKey(cm, key, 'mapping');
  1482. }
  1483. }
  1484. function handleKeyInsertMode() {
  1485. if (handleEsc()) { return true; }
  1486. var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
  1487. var keysAreChars = key.length == 1;
  1488. var match = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
  1489. while (keys.length > 1 && match.type != 'full') {
  1490. var keys = vim.inputState.keyBuffer = keys.slice(1);
  1491. var thisMatch = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
  1492. if (thisMatch.type != 'none') { match = thisMatch; }
  1493. }
  1494. if (match.type == 'none') { clearInputState(cm); return false; }
  1495. else if (match.type == 'partial') {
  1496. if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
  1497. lastInsertModeKeyTimer = window.setTimeout(
  1498. function() { if (vim.insertMode && vim.inputState.keyBuffer) { clearInputState(cm); } },
  1499. getOption('insertModeEscKeysTimeout'));
  1500. return !keysAreChars;
  1501. }
  1502. if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
  1503. if (keysAreChars) {
  1504. var selections = cm.listSelections();
  1505. for (var i = 0; i < selections.length; i++) {
  1506. var here = selections[i].head;
  1507. cm.replaceRange('', offsetCursor(here, 0, -(keys.length - 1)), here, '+input');
  1508. }
  1509. vimGlobalState.macroModeState.lastInsertModeChanges.changes.pop();
  1510. }
  1511. clearInputState(cm);
  1512. return match.command;
  1513. }
  1514. function handleKeyNonInsertMode() {
  1515. if (handleMacroRecording() || handleEsc()) { return true; }
  1516. var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
  1517. if (/^[1-9]\d*$/.test(keys)) { return true; }
  1518. var keysMatcher = /^(\d*)(.*)$/.exec(keys);
  1519. if (!keysMatcher) { clearInputState(cm); return false; }
  1520. var context = vim.visualMode ? 'visual' :
  1521. 'normal';
  1522. var match = commandDispatcher.matchCommand(keysMatcher[2] || keysMatcher[1], defaultKeymap, vim.inputState, context);
  1523. if (match.type == 'none') { clearInputState(cm); return false; }
  1524. else if (match.type == 'partial') { return true; }
  1525. vim.inputState.keyBuffer = '';
  1526. var keysMatcher = /^(\d*)(.*)$/.exec(keys);
  1527. if (keysMatcher[1] && keysMatcher[1] != '0') {
  1528. vim.inputState.pushRepeatDigit(keysMatcher[1]);
  1529. }
  1530. return match.command;
  1531. }
  1532. var command;
  1533. if (vim.insertMode) { command = handleKeyInsertMode(); }
  1534. else { command = handleKeyNonInsertMode(); }
  1535. if (command === false) {
  1536. return undefined; //ace_patch
  1537. } else if (command === true) {
  1538. return function() { return true; };
  1539. } else {
  1540. return function() {
  1541. if ((command.operator || command.isEdit) && cm.getOption('readOnly'))
  1542. return; // ace_patch
  1543. return cm.operation(function() {
  1544. cm.curOp.isVimOp = true;
  1545. try {
  1546. if (command.type == 'keyToKey') {
  1547. doKeyToKey(command.toKeys);
  1548. } else {
  1549. commandDispatcher.processCommand(cm, vim, command);
  1550. }
  1551. } catch (e) {
  1552. cm.state.vim = undefined;
  1553. maybeInitVimState(cm);
  1554. if (!CodeMirror.Vim.suppressErrorLogging) {
  1555. console['log'](e);
  1556. }
  1557. throw e;
  1558. }
  1559. return true;
  1560. });
  1561. };
  1562. }
  1563. },
  1564. handleEx: function(cm, input) {
  1565. exCommandDispatcher.processCommand(cm, input);
  1566. },
  1567. defineMotion: defineMotion,
  1568. defineAction: defineAction,
  1569. defineOperator: defineOperator,
  1570. mapCommand: mapCommand,
  1571. _mapCommand: _mapCommand,
  1572. defineRegister: defineRegister,
  1573. exitVisualMode: exitVisualMode,
  1574. exitInsertMode: exitInsertMode
  1575. };
  1576. function InputState() {
  1577. this.prefixRepeat = [];
  1578. this.motionRepeat = [];
  1579. this.operator = null;
  1580. this.operatorArgs = null;
  1581. this.motion = null;
  1582. this.motionArgs = null;
  1583. this.keyBuffer = []; // For matching multi-key commands.
  1584. this.registerName = null; // Defaults to the unnamed register.
  1585. }
  1586. InputState.prototype.pushRepeatDigit = function(n) {
  1587. if (!this.operator) {
  1588. this.prefixRepeat = this.prefixRepeat.concat(n);
  1589. } else {
  1590. this.motionRepeat = this.motionRepeat.concat(n);
  1591. }
  1592. };
  1593. InputState.prototype.getRepeat = function() {
  1594. var repeat = 0;
  1595. if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) {
  1596. repeat = 1;
  1597. if (this.prefixRepeat.length > 0) {
  1598. repeat *= parseInt(this.prefixRepeat.join(''), 10);
  1599. }
  1600. if (this.motionRepeat.length > 0) {
  1601. repeat *= parseInt(this.motionRepeat.join(''), 10);
  1602. }
  1603. }
  1604. return repeat;
  1605. };
  1606. function clearInputState(cm, reason) {
  1607. cm.state.vim.inputState = new InputState();
  1608. CodeMirror.signal(cm, 'vim-command-done', reason);
  1609. }
  1610. function Register(text, linewise, blockwise) {
  1611. this.clear();
  1612. this.keyBuffer = [text || ''];
  1613. this.insertModeChanges = [];
  1614. this.searchQueries = [];
  1615. this.linewise = !!linewise;
  1616. this.blockwise = !!blockwise;
  1617. }
  1618. Register.prototype = {
  1619. setText: function(text, linewise, blockwise) {
  1620. this.keyBuffer = [text || ''];
  1621. this.linewise = !!linewise;
  1622. this.blockwise = !!blockwise;
  1623. },
  1624. pushText: function(text, linewise) {
  1625. if (linewise) {
  1626. if (!this.linewise) {
  1627. this.keyBuffer.push('\n');
  1628. }
  1629. this.linewise = true;
  1630. }
  1631. this.keyBuffer.push(text);
  1632. },
  1633. pushInsertModeChanges: function(changes) {
  1634. this.insertModeChanges.push(createInsertModeChanges(changes));
  1635. },
  1636. pushSearchQuery: function(query) {
  1637. this.searchQueries.push(query);
  1638. },
  1639. clear: function() {
  1640. this.keyBuffer = [];
  1641. this.insertModeChanges = [];
  1642. this.searchQueries = [];
  1643. this.linewise = false;
  1644. },
  1645. toString: function() {
  1646. return this.keyBuffer.join('');
  1647. }
  1648. };
  1649. function defineRegister(name, register) {
  1650. var registers = vimGlobalState.registerController.registers;
  1651. if (!name || name.length != 1) {
  1652. throw Error('Register name must be 1 character');
  1653. }
  1654. registers[name] = register;
  1655. validRegisters.push(name);
  1656. }
  1657. function RegisterController(registers) {
  1658. this.registers = registers;
  1659. this.unnamedRegister = registers['"'] = new Register();
  1660. registers['.'] = new Register();
  1661. registers[':'] = new Register();
  1662. registers['/'] = new Register();
  1663. }
  1664. RegisterController.prototype = {
  1665. pushText: function(registerName, operator, text, linewise, blockwise) {
  1666. if (linewise && text.charAt(text.length - 1) !== '\n'){
  1667. text += '\n';
  1668. }
  1669. var register = this.isValidRegister(registerName) ?
  1670. this.getRegister(registerName) : null;
  1671. if (!register) {
  1672. switch (operator) {
  1673. case 'yank':
  1674. this.registers['0'] = new Register(text, linewise, blockwise);
  1675. break;
  1676. case 'delete':
  1677. case 'change':
  1678. if (text.indexOf('\n') == -1) {
  1679. this.registers['-'] = new Register(text, linewise);
  1680. } else {
  1681. this.shiftNumericRegisters_();
  1682. this.registers['1'] = new Register(text, linewise);
  1683. }
  1684. break;
  1685. }
  1686. this.unnamedRegister.setText(text, linewise, blockwise);
  1687. return;
  1688. }
  1689. var append = isUpperCase(registerName);
  1690. if (append) {
  1691. register.pushText(text, linewise);
  1692. } else {
  1693. register.setText(text, linewise, blockwise);
  1694. }
  1695. this.unnamedRegister.setText(register.toString(), linewise);
  1696. },
  1697. getRegister: function(name) {
  1698. if (!this.isValidRegister(name)) {
  1699. return this.unnamedRegister;
  1700. }
  1701. name = name.toLowerCase();
  1702. if (!this.registers[name]) {
  1703. this.registers[name] = new Register();
  1704. }
  1705. return this.registers[name];
  1706. },
  1707. isValidRegister: function(name) {
  1708. return name && inArray(name, validRegisters);
  1709. },
  1710. shiftNumericRegisters_: function() {
  1711. for (var i = 9; i >= 2; i--) {
  1712. this.registers[i] = this.getRegister('' + (i - 1));
  1713. }
  1714. }
  1715. };
  1716. function HistoryController() {
  1717. this.historyBuffer = [];
  1718. this.iterator = 0;
  1719. this.initialPrefix = null;
  1720. }
  1721. HistoryController.prototype = {
  1722. nextMatch: function (input, up) {
  1723. var historyBuffer = this.historyBuffer;
  1724. var dir = up ? -1 : 1;
  1725. if (this.initialPrefix === null) this.initialPrefix = input;
  1726. for (var i = this.iterator + dir; up ? i >= 0 : i < historyBuffer.length; i+= dir) {
  1727. var element = historyBuffer[i];
  1728. for (var j = 0; j <= element.length; j++) {
  1729. if (this.initialPrefix == element.substring(0, j)) {
  1730. this.iterator = i;
  1731. return element;
  1732. }
  1733. }
  1734. }
  1735. if (i >= historyBuffer.length) {
  1736. this.iterator = historyBuffer.length;
  1737. return this.initialPrefix;
  1738. }
  1739. if (i < 0 ) return input;
  1740. },
  1741. pushInput: function(input) {
  1742. var index = this.historyBuffer.indexOf(input);
  1743. if (index > -1) this.historyBuffer.splice(index, 1);
  1744. if (input.length) this.historyBuffer.push(input);
  1745. },
  1746. reset: function() {
  1747. this.initialPrefix = null;
  1748. this.iterator = this.historyBuffer.length;
  1749. }
  1750. };
  1751. var commandDispatcher = {
  1752. matchCommand: function(keys, keyMap, inputState, context) {
  1753. var matches = commandMatches(keys, keyMap, context, inputState);
  1754. if (!matches.full && !matches.partial) {
  1755. return {type: 'none'};
  1756. } else if (!matches.full && matches.partial) {
  1757. return {type: 'partial'};
  1758. }
  1759. var bestMatch;
  1760. for (var i = 0; i < matches.full.length; i++) {
  1761. var match = matches.full[i];
  1762. if (!bestMatch) {
  1763. bestMatch = match;
  1764. }
  1765. }
  1766. if (bestMatch.keys.slice(-11) == '<character>') {
  1767. var character = lastChar(keys);
  1768. if (/<C-.>/.test(character) || !character) return {type: 'none'}; //ace_patch
  1769. inputState.selectedCharacter = character;
  1770. }
  1771. return {type: 'full', command: bestMatch};
  1772. },
  1773. processCommand: function(cm, vim, command) {
  1774. vim.inputState.repeatOverride = command.repeatOverride;
  1775. switch (command.type) {
  1776. case 'motion':
  1777. this.processMotion(cm, vim, command);
  1778. break;
  1779. case 'operator':
  1780. this.processOperator(cm, vim, command);
  1781. break;
  1782. case 'operatorMotion':
  1783. this.processOperatorMotion(cm, vim, command);
  1784. break;
  1785. case 'action':
  1786. this.processAction(cm, vim, command);
  1787. break;
  1788. case 'search':
  1789. this.processSearch(cm, vim, command);
  1790. break;
  1791. case 'ex':
  1792. case 'keyToEx':
  1793. this.processEx(cm, vim, command);
  1794. break;
  1795. default:
  1796. break;
  1797. }
  1798. },
  1799. processMotion: function(cm, vim, command) {
  1800. vim.inputState.motion = command.motion;
  1801. vim.inputState.motionArgs = copyArgs(command.motionArgs);
  1802. this.evalInput(cm, vim);
  1803. },
  1804. processOperator: function(cm, vim, command) {
  1805. var inputState = vim.inputState;
  1806. if (inputState.operator) {
  1807. if (inputState.operator == command.operator) {
  1808. inputState.motion = 'expandToLine';
  1809. inputState.motionArgs = { linewise: true };
  1810. this.evalInput(cm, vim);
  1811. return;
  1812. } else {
  1813. clearInputState(cm);
  1814. }
  1815. }
  1816. inputState.operator = command.operator;
  1817. inputState.operatorArgs = copyArgs(command.operatorArgs);
  1818. if (command.exitVisualBlock) {
  1819. vim.visualBlock = false;
  1820. updateCmSelection(cm);
  1821. }
  1822. if (vim.visualMode) {
  1823. this.evalInput(cm, vim);
  1824. }
  1825. },
  1826. processOperatorMotion: function(cm, vim, command) {
  1827. var visualMode = vim.visualMode;
  1828. var operatorMotionArgs = copyArgs(command.operatorMotionArgs);
  1829. if (operatorMotionArgs) {
  1830. if (visualMode && operatorMotionArgs.visualLine) {
  1831. vim.visualLine = true;
  1832. }
  1833. }
  1834. this.processOperator(cm, vim, command);
  1835. if (!visualMode) {
  1836. this.processMotion(cm, vim, command);
  1837. }
  1838. },
  1839. processAction: function(cm, vim, command) {
  1840. var inputState = vim.inputState;
  1841. var repeat = inputState.getRepeat();
  1842. var repeatIsExplicit = !!repeat;
  1843. var actionArgs = copyArgs(command.actionArgs) || {};
  1844. if (inputState.selectedCharacter) {
  1845. actionArgs.selectedCharacter = inputState.selectedCharacter;
  1846. }
  1847. if (command.operator) {
  1848. this.processOperator(cm, vim, command);
  1849. }
  1850. if (command.motion) {
  1851. this.processMotion(cm, vim, command);
  1852. }
  1853. if (command.motion || command.operator) {
  1854. this.evalInput(cm, vim);
  1855. }
  1856. actionArgs.repeat = repeat || 1;
  1857. actionArgs.repeatIsExplicit = repeatIsExplicit;
  1858. actionArgs.registerName = inputState.registerName;
  1859. clearInputState(cm);
  1860. vim.lastMotion = null;
  1861. if (command.isEdit) {
  1862. this.recordLastEdit(vim, inputState, command);
  1863. }
  1864. actions[command.action](cm, actionArgs, vim);
  1865. },
  1866. processSearch: function(cm, vim, command) {
  1867. if (!cm.getSearchCursor) {
  1868. return;
  1869. }
  1870. var forward = command.searchArgs.forward;
  1871. var wholeWordOnly = command.searchArgs.wholeWordOnly;
  1872. getSearchState(cm).setReversed(!forward);
  1873. var promptPrefix = (forward) ? '/' : '?';
  1874. var originalQuery = getSearchState(cm).getQuery();
  1875. var originalScrollPos = cm.getScrollInfo();
  1876. function handleQuery(query, ignoreCase, smartCase) {
  1877. vimGlobalState.searchHistoryController.pushInput(query);
  1878. vimGlobalState.searchHistoryController.reset();
  1879. try {
  1880. updateSearchQuery(cm, query, ignoreCase, smartCase);
  1881. } catch (e) {
  1882. showConfirm(cm, 'Invalid regex: ' + query);
  1883. clearInputState(cm);
  1884. return;
  1885. }
  1886. commandDispatcher.processMotion(cm, vim, {
  1887. type: 'motion',
  1888. motion: 'findNext',
  1889. motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist }
  1890. });
  1891. }
  1892. function onPromptClose(query) {
  1893. cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
  1894. handleQuery(query, true /** ignoreCase */, true /** smartCase */);
  1895. var macroModeState = vimGlobalState.macroModeState;
  1896. if (macroModeState.isRecording) {
  1897. logSearchQuery(macroModeState, query);
  1898. }
  1899. }
  1900. function onPromptKeyUp(e, query, close) {
  1901. var keyName = CodeMirror.keyName(e), up, offset;
  1902. if (keyName == 'Up' || keyName == 'Down') {
  1903. up = keyName == 'Up' ? true : false;
  1904. offset = e.target ? e.target.selectionEnd : 0;
  1905. query = vimGlobalState.searchHistoryController.nextMatch(query, up) || '';
  1906. close(query);
  1907. if (offset && e.target) e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length);
  1908. } else {
  1909. if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')
  1910. vimGlobalState.searchHistoryController.reset();
  1911. }
  1912. var parsedQuery;
  1913. try {
  1914. parsedQuery = updateSearchQuery(cm, query,
  1915. true /** ignoreCase */, true /** smartCase */);
  1916. } catch (e) {
  1917. }
  1918. if (parsedQuery) {
  1919. cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30);
  1920. } else {
  1921. clearSearchHighlight(cm);
  1922. cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
  1923. }
  1924. }
  1925. function onPromptKeyDown(e, query, close) {
  1926. var keyName = CodeMirror.keyName(e);
  1927. if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' ||
  1928. (keyName == 'Backspace' && query == '')) {
  1929. vimGlobalState.searchHistoryController.pushInput(query);
  1930. vimGlobalState.searchHistoryController.reset();
  1931. updateSearchQuery(cm, originalQuery);
  1932. clearSearchHighlight(cm);
  1933. cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
  1934. CodeMirror.e_stop(e);
  1935. clearInputState(cm);
  1936. close();
  1937. cm.focus();
  1938. } else if (keyName == 'Up' || keyName == 'Down') {
  1939. CodeMirror.e_stop(e);
  1940. } else if (keyName == 'Ctrl-U') {
  1941. CodeMirror.e_stop(e);
  1942. close('');
  1943. }
  1944. }
  1945. switch (command.searchArgs.querySrc) {
  1946. case 'prompt':
  1947. var macroModeState = vimGlobalState.macroModeState;
  1948. if (macroModeState.isPlaying) {
  1949. var query = macroModeState.replaySearchQueries.shift();
  1950. handleQuery(query, true /** ignoreCase */, false /** smartCase */);
  1951. } else {
  1952. showPrompt(cm, {
  1953. onClose: onPromptClose,
  1954. prefix: promptPrefix,
  1955. desc: searchPromptDesc,
  1956. onKeyUp: onPromptKeyUp,
  1957. onKeyDown: onPromptKeyDown
  1958. });
  1959. }
  1960. break;
  1961. case 'wordUnderCursor':
  1962. var word = expandWordUnderCursor(cm, false /** inclusive */,
  1963. true /** forward */, false /** bigWord */,
  1964. true /** noSymbol */);
  1965. var isKeyword = true;
  1966. if (!word) {
  1967. word = expandWordUnderCursor(cm, false /** inclusive */,
  1968. true /** forward */, false /** bigWord */,
  1969. false /** noSymbol */);
  1970. isKeyword = false;
  1971. }
  1972. if (!word) {
  1973. return;
  1974. }
  1975. var query = cm.getLine(word.start.line).substring(word.start.ch,
  1976. word.end.ch);
  1977. if (isKeyword && wholeWordOnly) {
  1978. query = '\\b' + query + '\\b';
  1979. } else {
  1980. query = escapeRegex(query);
  1981. }
  1982. vimGlobalState.jumpList.cachedCursor = cm.getCursor();
  1983. cm.setCursor(word.start);
  1984. handleQuery(query, true /** ignoreCase */, false /** smartCase */);
  1985. break;
  1986. }
  1987. },
  1988. processEx: function(cm, vim, command) {
  1989. function onPromptClose(input) {
  1990. vimGlobalState.exCommandHistoryController.pushInput(input);
  1991. vimGlobalState.exCommandHistoryController.reset();
  1992. exCommandDispatcher.processCommand(cm, input);
  1993. }
  1994. function onPromptKeyDown(e, input, close) {
  1995. var keyName = CodeMirror.keyName(e), up, offset;
  1996. if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' ||
  1997. (keyName == 'Backspace' && input == '')) {
  1998. vimGlobalState.exCommandHistoryController.pushInput(input);
  1999. vimGlobalState.exCommandHistoryController.reset();
  2000. CodeMirror.e_stop(e);
  2001. clearInputState(cm);
  2002. close();
  2003. cm.focus();
  2004. }
  2005. if (keyName == 'Up' || keyName == 'Down') {
  2006. CodeMirror.e_stop(e);
  2007. up = keyName == 'Up' ? true : false;
  2008. offset = e.target ? e.target.selectionEnd : 0;
  2009. input = vimGlobalState.exCommandHistoryController.nextMatch(input, up) || '';
  2010. close(input);
  2011. if (offset && e.target) e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length);
  2012. } else if (keyName == 'Ctrl-U') {
  2013. CodeMirror.e_stop(e);
  2014. close('');
  2015. } else {
  2016. if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')
  2017. vimGlobalState.exCommandHistoryController.reset();
  2018. }
  2019. }
  2020. if (command.type == 'keyToEx') {
  2021. exCommandDispatcher.processCommand(cm, command.exArgs.input);
  2022. } else {
  2023. if (vim.visualMode) {
  2024. showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>',
  2025. onKeyDown: onPromptKeyDown, selectValueOnOpen: false});
  2026. } else {
  2027. showPrompt(cm, { onClose: onPromptClose, prefix: ':',
  2028. onKeyDown: onPromptKeyDown});
  2029. }
  2030. }
  2031. },
  2032. evalInput: function(cm, vim) {
  2033. var inputState = vim.inputState;
  2034. var motion = inputState.motion;
  2035. var motionArgs = inputState.motionArgs || {};
  2036. var operator = inputState.operator;
  2037. var operatorArgs = inputState.operatorArgs || {};
  2038. var registerName = inputState.registerName;
  2039. var sel = vim.sel;
  2040. var origHead = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.head): cm.getCursor('head'));
  2041. var origAnchor = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.anchor) : cm.getCursor('anchor'));
  2042. var oldHead = copyCursor(origHead);
  2043. var oldAnchor = copyCursor(origAnchor);
  2044. var newHead, newAnchor;
  2045. var repeat;
  2046. if (operator) {
  2047. this.recordLastEdit(vim, inputState);
  2048. }
  2049. if (inputState.repeatOverride !== undefined) {
  2050. repeat = inputState.repeatOverride;
  2051. } else {
  2052. repeat = inputState.getRepeat();
  2053. }
  2054. if (repeat > 0 && motionArgs.explicitRepeat) {
  2055. motionArgs.repeatIsExplicit = true;
  2056. } else if (motionArgs.noRepeat ||
  2057. (!motionArgs.explicitRepeat && repeat === 0)) {
  2058. repeat = 1;
  2059. motionArgs.repeatIsExplicit = false;
  2060. }
  2061. if (inputState.selectedCharacter) {
  2062. motionArgs.selectedCharacter = operatorArgs.selectedCharacter =
  2063. inputState.selectedCharacter;
  2064. }
  2065. motionArgs.repeat = repeat;
  2066. clearInputState(cm);
  2067. if (motion) {
  2068. var motionResult = motions[motion](cm, origHead, motionArgs, vim);
  2069. vim.lastMotion = motions[motion];
  2070. if (!motionResult) {
  2071. return;
  2072. }
  2073. if (motionArgs.toJumplist) {
  2074. if (!operator && cm.ace.curOp != null)
  2075. cm.ace.curOp.command.scrollIntoView = "center-animate"; // ace_patch
  2076. var jumpList = vimGlobalState.jumpList;
  2077. var cachedCursor = jumpList.cachedCursor;
  2078. if (cachedCursor) {
  2079. recordJumpPosition(cm, cachedCursor, motionResult);
  2080. delete jumpList.cachedCursor;
  2081. } else {
  2082. recordJumpPosition(cm, origHead, motionResult);
  2083. }
  2084. }
  2085. if (motionResult instanceof Array) {
  2086. newAnchor = motionResult[0];
  2087. newHead = motionResult[1];
  2088. } else {
  2089. newHead = motionResult;
  2090. }
  2091. if (!newHead) {
  2092. newHead = copyCursor(origHead);
  2093. }
  2094. if (vim.visualMode) {
  2095. if (!(vim.visualBlock && newHead.ch === Infinity)) {
  2096. newHead = clipCursorToContent(cm, newHead, vim.visualBlock);
  2097. }
  2098. if (newAnchor) {
  2099. newAnchor = clipCursorToContent(cm, newAnchor, true);
  2100. }
  2101. newAnchor = newAnchor || oldAnchor;
  2102. sel.anchor = newAnchor;
  2103. sel.head = newHead;
  2104. updateCmSelection(cm);
  2105. updateMark(cm, vim, '<',
  2106. cursorIsBefore(newAnchor, newHead) ? newAnchor
  2107. : newHead);
  2108. updateMark(cm, vim, '>',
  2109. cursorIsBefore(newAnchor, newHead) ? newHead
  2110. : newAnchor);
  2111. } else if (!operator) {
  2112. newHead = clipCursorToContent(cm, newHead);
  2113. cm.setCursor(newHead.line, newHead.ch);
  2114. }
  2115. }
  2116. if (operator) {
  2117. if (operatorArgs.lastSel) {
  2118. newAnchor = oldAnchor;
  2119. var lastSel = operatorArgs.lastSel;
  2120. var lineOffset = Math.abs(lastSel.head.line - lastSel.anchor.line);
  2121. var chOffset = Math.abs(lastSel.head.ch - lastSel.anchor.ch);
  2122. if (lastSel.visualLine) {
  2123. newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
  2124. } else if (lastSel.visualBlock) {
  2125. newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch + chOffset);
  2126. } else if (lastSel.head.line == lastSel.anchor.line) {
  2127. newHead = Pos(oldAnchor.line, oldAnchor.ch + chOffset);
  2128. } else {
  2129. newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
  2130. }
  2131. vim.visualMode = true;
  2132. vim.visualLine = lastSel.visualLine;
  2133. vim.visualBlock = lastSel.visualBlock;
  2134. sel = vim.sel = {
  2135. anchor: newAnchor,
  2136. head: newHead
  2137. };
  2138. updateCmSelection(cm);
  2139. } else if (vim.visualMode) {
  2140. operatorArgs.lastSel = {
  2141. anchor: copyCursor(sel.anchor),
  2142. head: copyCursor(sel.head),
  2143. visualBlock: vim.visualBlock,
  2144. visualLine: vim.visualLine
  2145. };
  2146. }
  2147. var curStart, curEnd, linewise, mode;
  2148. var cmSel;
  2149. if (vim.visualMode) {
  2150. curStart = cursorMin(sel.head, sel.anchor);
  2151. curEnd = cursorMax(sel.head, sel.anchor);
  2152. linewise = vim.visualLine || operatorArgs.linewise;
  2153. mode = vim.visualBlock ? 'block' :
  2154. linewise ? 'line' :
  2155. 'char';
  2156. cmSel = makeCmSelection(cm, {
  2157. anchor: curStart,
  2158. head: curEnd
  2159. }, mode);
  2160. if (linewise) {
  2161. var ranges = cmSel.ranges;
  2162. if (mode == 'block') {
  2163. for (var i = 0; i < ranges.length; i++) {
  2164. ranges[i].head.ch = lineLength(cm, ranges[i].head.line);
  2165. }
  2166. } else if (mode == 'line') {
  2167. ranges[0].head = Pos(ranges[0].head.line + 1, 0);
  2168. }
  2169. }
  2170. } else {
  2171. curStart = copyCursor(newAnchor || oldAnchor);
  2172. curEnd = copyCursor(newHead || oldHead);
  2173. if (cursorIsBefore(curEnd, curStart)) {
  2174. var tmp = curStart;
  2175. curStart = curEnd;
  2176. curEnd = tmp;
  2177. }
  2178. linewise = motionArgs.linewise || operatorArgs.linewise;
  2179. if (linewise) {
  2180. expandSelectionToLine(cm, curStart, curEnd);
  2181. } else if (motionArgs.forward) {
  2182. clipToLine(cm, curStart, curEnd);
  2183. }
  2184. mode = 'char';
  2185. var exclusive = !motionArgs.inclusive || linewise;
  2186. cmSel = makeCmSelection(cm, {
  2187. anchor: curStart,
  2188. head: curEnd
  2189. }, mode, exclusive);
  2190. }
  2191. cm.setSelections(cmSel.ranges, cmSel.primary);
  2192. vim.lastMotion = null;
  2193. operatorArgs.repeat = repeat; // For indent in visual mode.
  2194. operatorArgs.registerName = registerName;
  2195. operatorArgs.linewise = linewise;
  2196. var operatorMoveTo = operators[operator](
  2197. cm, operatorArgs, cmSel.ranges, oldAnchor, newHead);
  2198. if (vim.visualMode) {
  2199. exitVisualMode(cm, operatorMoveTo != null);
  2200. }
  2201. if (operatorMoveTo) {
  2202. cm.setCursor(operatorMoveTo);
  2203. }
  2204. }
  2205. },
  2206. recordLastEdit: function(vim, inputState, actionCommand) {
  2207. var macroModeState = vimGlobalState.macroModeState;
  2208. if (macroModeState.isPlaying) { return; }
  2209. vim.lastEditInputState = inputState;
  2210. vim.lastEditActionCommand = actionCommand;
  2211. macroModeState.lastInsertModeChanges.changes = [];
  2212. macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false;
  2213. macroModeState.lastInsertModeChanges.visualBlock = vim.visualBlock ? vim.sel.head.line - vim.sel.anchor.line : 0;
  2214. }
  2215. };
  2216. var motions = {
  2217. moveToTopLine: function(cm, _head, motionArgs) {
  2218. var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;
  2219. return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
  2220. },
  2221. moveToMiddleLine: function(cm) {
  2222. var range = getUserVisibleLines(cm);
  2223. var line = Math.floor((range.top + range.bottom) * 0.5);
  2224. return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
  2225. },
  2226. moveToBottomLine: function(cm, _head, motionArgs) {
  2227. var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;
  2228. return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
  2229. },
  2230. expandToLine: function(_cm, head, motionArgs) {
  2231. var cur = head;
  2232. return Pos(cur.line + motionArgs.repeat - 1, Infinity);
  2233. },
  2234. findNext: function(cm, _head, motionArgs) {
  2235. var state = getSearchState(cm);
  2236. var query = state.getQuery();
  2237. if (!query) {
  2238. return;
  2239. }
  2240. var prev = !motionArgs.forward;
  2241. prev = (state.isReversed()) ? !prev : prev;
  2242. highlightSearchMatches(cm, query);
  2243. return findNext(cm, prev/** prev */, query, motionArgs.repeat);
  2244. },
  2245. goToMark: function(cm, _head, motionArgs, vim) {
  2246. var pos = getMarkPos(cm, vim, motionArgs.selectedCharacter);
  2247. if (pos) {
  2248. return motionArgs.linewise ? { line: pos.line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line)) } : pos;
  2249. }
  2250. return null;
  2251. },
  2252. moveToOtherHighlightedEnd: function(cm, _head, motionArgs, vim) {
  2253. if (vim.visualBlock && motionArgs.sameLine) {
  2254. var sel = vim.sel;
  2255. return [
  2256. clipCursorToContent(cm, Pos(sel.anchor.line, sel.head.ch)),
  2257. clipCursorToContent(cm, Pos(sel.head.line, sel.anchor.ch))
  2258. ];
  2259. } else {
  2260. return ([vim.sel.head, vim.sel.anchor]);
  2261. }
  2262. },
  2263. jumpToMark: function(cm, head, motionArgs, vim) {
  2264. var best = head;
  2265. for (var i = 0; i < motionArgs.repeat; i++) {
  2266. var cursor = best;
  2267. for (var key in vim.marks) {
  2268. if (!isLowerCase(key)) {
  2269. continue;
  2270. }
  2271. var mark = vim.marks[key].find();
  2272. var isWrongDirection = (motionArgs.forward) ?
  2273. cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark);
  2274. if (isWrongDirection) {
  2275. continue;
  2276. }
  2277. if (motionArgs.linewise && (mark.line == cursor.line)) {
  2278. continue;
  2279. }
  2280. var equal = cursorEqual(cursor, best);
  2281. var between = (motionArgs.forward) ?
  2282. cursorIsBetween(cursor, mark, best) :
  2283. cursorIsBetween(best, mark, cursor);
  2284. if (equal || between) {
  2285. best = mark;
  2286. }
  2287. }
  2288. }
  2289. if (motionArgs.linewise) {
  2290. best = Pos(best.line, findFirstNonWhiteSpaceCharacter(cm.getLine(best.line)));
  2291. }
  2292. return best;
  2293. },
  2294. moveByCharacters: function(_cm, head, motionArgs) {
  2295. var cur = head;
  2296. var repeat = motionArgs.repeat;
  2297. var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;
  2298. return Pos(cur.line, ch);
  2299. },
  2300. moveByLines: function(cm, head, motionArgs, vim) {
  2301. var cur = head;
  2302. var endCh = cur.ch;
  2303. switch (vim.lastMotion) {
  2304. case this.moveByLines:
  2305. case this.moveByDisplayLines:
  2306. case this.moveByScroll:
  2307. case this.moveToColumn:
  2308. case this.moveToEol:
  2309. endCh = vim.lastHPos;
  2310. break;
  2311. default:
  2312. vim.lastHPos = endCh;
  2313. }
  2314. var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0);
  2315. var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat;
  2316. var first = cm.firstLine();
  2317. var last = cm.lastLine();
  2318. if (line < first && cur.line == first){
  2319. return this.moveToStartOfLine(cm, head, motionArgs, vim);
  2320. }else if (line > last && cur.line == last){
  2321. return this.moveToEol(cm, head, motionArgs, vim, true);
  2322. }
  2323. var fold = cm.ace.session.getFoldLine(line);
  2324. if (fold) {
  2325. if (motionArgs.forward) {
  2326. if (line > fold.start.row)
  2327. line = fold.end.row + 1;
  2328. } else {
  2329. line = fold.start.row;
  2330. }
  2331. }
  2332. if (motionArgs.toFirstChar){
  2333. endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));
  2334. vim.lastHPos = endCh;
  2335. }
  2336. vim.lastHSPos = cm.charCoords(Pos(line, endCh),'div').left;
  2337. return Pos(line, endCh);
  2338. },
  2339. moveByDisplayLines: function(cm, head, motionArgs, vim) {
  2340. var cur = head;
  2341. switch (vim.lastMotion) {
  2342. case this.moveByDisplayLines:
  2343. case this.moveByScroll:
  2344. case this.moveByLines:
  2345. case this.moveToColumn:
  2346. case this.moveToEol:
  2347. break;
  2348. default:
  2349. vim.lastHSPos = cm.charCoords(cur,'div').left;
  2350. }
  2351. var repeat = motionArgs.repeat;
  2352. var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos);
  2353. if (res.hitSide) {
  2354. if (motionArgs.forward) {
  2355. var lastCharCoords = cm.charCoords(res, 'div');
  2356. var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos };
  2357. var res = cm.coordsChar(goalCoords, 'div');
  2358. } else {
  2359. var resCoords = cm.charCoords(Pos(cm.firstLine(), 0), 'div');
  2360. resCoords.left = vim.lastHSPos;
  2361. res = cm.coordsChar(resCoords, 'div');
  2362. }
  2363. }
  2364. vim.lastHPos = res.ch;
  2365. return res;
  2366. },
  2367. moveByPage: function(cm, head, motionArgs) {
  2368. var curStart = head;
  2369. var repeat = motionArgs.repeat;
  2370. return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page');
  2371. },
  2372. moveByParagraph: function(cm, head, motionArgs) {
  2373. var dir = motionArgs.forward ? 1 : -1;
  2374. return findParagraph(cm, head, motionArgs.repeat, dir);
  2375. },
  2376. moveBySentence: function(cm, head, motionArgs) {
  2377. var dir = motionArgs.forward ? 1 : -1;
  2378. return findSentence(cm, head, motionArgs.repeat, dir);
  2379. },
  2380. moveByScroll: function(cm, head, motionArgs, vim) {
  2381. var scrollbox = cm.getScrollInfo();
  2382. var curEnd = null;
  2383. var repeat = motionArgs.repeat;
  2384. if (!repeat) {
  2385. repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
  2386. }
  2387. var orig = cm.charCoords(head, 'local');
  2388. motionArgs.repeat = repeat;
  2389. var curEnd = motions.moveByDisplayLines(cm, head, motionArgs, vim);
  2390. if (!curEnd) {
  2391. return null;
  2392. }
  2393. var dest = cm.charCoords(curEnd, 'local');
  2394. cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
  2395. return curEnd;
  2396. },
  2397. moveByWords: function(cm, head, motionArgs) {
  2398. return moveToWord(cm, head, motionArgs.repeat, !!motionArgs.forward,
  2399. !!motionArgs.wordEnd, !!motionArgs.bigWord);
  2400. },
  2401. moveTillCharacter: function(cm, _head, motionArgs) {
  2402. var repeat = motionArgs.repeat;
  2403. var curEnd = moveToCharacter(cm, repeat, motionArgs.forward,
  2404. motionArgs.selectedCharacter);
  2405. var increment = motionArgs.forward ? -1 : 1;
  2406. recordLastCharacterSearch(increment, motionArgs);
  2407. if (!curEnd) return null;
  2408. curEnd.ch += increment;
  2409. return curEnd;
  2410. },
  2411. moveToCharacter: function(cm, head, motionArgs) {
  2412. var repeat = motionArgs.repeat;
  2413. recordLastCharacterSearch(0, motionArgs);
  2414. return moveToCharacter(cm, repeat, motionArgs.forward,
  2415. motionArgs.selectedCharacter) || head;
  2416. },
  2417. moveToSymbol: function(cm, head, motionArgs) {
  2418. var repeat = motionArgs.repeat;
  2419. return findSymbol(cm, repeat, motionArgs.forward,
  2420. motionArgs.selectedCharacter) || head;
  2421. },
  2422. moveToColumn: function(cm, head, motionArgs, vim) {
  2423. var repeat = motionArgs.repeat;
  2424. vim.lastHPos = repeat - 1;
  2425. vim.lastHSPos = cm.charCoords(head,'div').left;
  2426. return moveToColumn(cm, repeat);
  2427. },
  2428. moveToEol: function(cm, head, motionArgs, vim, keepHPos) {
  2429. var cur = head;
  2430. var retval= Pos(cur.line + motionArgs.repeat - 1, Infinity);
  2431. var end=cm.clipPos(retval);
  2432. end.ch--;
  2433. if (!keepHPos) {
  2434. vim.lastHPos = Infinity;
  2435. vim.lastHSPos = cm.charCoords(end,'div').left;
  2436. }
  2437. return retval;
  2438. },
  2439. moveToFirstNonWhiteSpaceCharacter: function(cm, head) {
  2440. var cursor = head;
  2441. return Pos(cursor.line,
  2442. findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)));
  2443. },
  2444. moveToMatchedSymbol: function(cm, head) {
  2445. var cursor = head;
  2446. var line = cursor.line;
  2447. var ch = cursor.ch;
  2448. var lineText = cm.getLine(line);
  2449. var symbol;
  2450. for (; ch < lineText.length; ch++) {
  2451. symbol = lineText.charAt(ch);
  2452. if (symbol && isMatchableSymbol(symbol)) {
  2453. var style = cm.getTokenTypeAt(Pos(line, ch + 1));
  2454. if (style !== "string" && style !== "comment") {
  2455. break;
  2456. }
  2457. }
  2458. }
  2459. if (ch < lineText.length) {
  2460. var re = /[<>]/.test(lineText[ch]) ? /[(){}[\]<>]/ : /[(){}[\]]/; //ace_patch?
  2461. var matched = cm.findMatchingBracket(Pos(line, ch+1), {bracketRegex: re});
  2462. return matched.to;
  2463. } else {
  2464. return cursor;
  2465. }
  2466. },
  2467. moveToStartOfLine: function(_cm, head) {
  2468. return Pos(head.line, 0);
  2469. },
  2470. moveToLineOrEdgeOfDocument: function(cm, _head, motionArgs) {
  2471. var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine();
  2472. if (motionArgs.repeatIsExplicit) {
  2473. lineNum = motionArgs.repeat - cm.getOption('firstLineNumber');
  2474. }
  2475. return Pos(lineNum,
  2476. findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)));
  2477. },
  2478. textObjectManipulation: function(cm, head, motionArgs, vim) {
  2479. var mirroredPairs = {'(': ')', ')': '(',
  2480. '{': '}', '}': '{',
  2481. '[': ']', ']': '[',
  2482. '<': '>', '>': '<'};
  2483. var selfPaired = {'\'': true, '"': true, '`': true};
  2484. var character = motionArgs.selectedCharacter;
  2485. if (character == 'b') {
  2486. character = '(';
  2487. } else if (character == 'B') {
  2488. character = '{';
  2489. }
  2490. var inclusive = !motionArgs.textObjectInner;
  2491. var tmp;
  2492. if (mirroredPairs[character]) {
  2493. tmp = selectCompanionObject(cm, head, character, inclusive);
  2494. } else if (selfPaired[character]) {
  2495. tmp = findBeginningAndEnd(cm, head, character, inclusive);
  2496. } else if (character === 'W') {
  2497. tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
  2498. true /** bigWord */);
  2499. } else if (character === 'w') {
  2500. tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
  2501. false /** bigWord */);
  2502. } else if (character === 'p') {
  2503. tmp = findParagraph(cm, head, motionArgs.repeat, 0, inclusive);
  2504. motionArgs.linewise = true;
  2505. if (vim.visualMode) {
  2506. if (!vim.visualLine) { vim.visualLine = true; }
  2507. } else {
  2508. var operatorArgs = vim.inputState.operatorArgs;
  2509. if (operatorArgs) { operatorArgs.linewise = true; }
  2510. tmp.end.line--;
  2511. }
  2512. } else {
  2513. return null;
  2514. }
  2515. if (!cm.state.vim.visualMode) {
  2516. return [tmp.start, tmp.end];
  2517. } else {
  2518. return expandSelection(cm, tmp.start, tmp.end);
  2519. }
  2520. },
  2521. repeatLastCharacterSearch: function(cm, head, motionArgs) {
  2522. var lastSearch = vimGlobalState.lastCharacterSearch;
  2523. var repeat = motionArgs.repeat;
  2524. var forward = motionArgs.forward === lastSearch.forward;
  2525. var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1);
  2526. cm.moveH(-increment, 'char');
  2527. motionArgs.inclusive = forward ? true : false;
  2528. var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);
  2529. if (!curEnd) {
  2530. cm.moveH(increment, 'char');
  2531. return head;
  2532. }
  2533. curEnd.ch += increment;
  2534. return curEnd;
  2535. }
  2536. };
  2537. function defineMotion(name, fn) {
  2538. motions[name] = fn;
  2539. }
  2540. function fillArray(val, times) {
  2541. var arr = [];
  2542. for (var i = 0; i < times; i++) {
  2543. arr.push(val);
  2544. }
  2545. return arr;
  2546. }
  2547. var operators = {
  2548. change: function(cm, args, ranges) {
  2549. var finalHead, text;
  2550. var vim = cm.state.vim;
  2551. var anchor = ranges[0].anchor,
  2552. head = ranges[0].head;
  2553. if (!vim.visualMode) {
  2554. text = cm.getRange(anchor, head);
  2555. var lastState = vim.lastEditInputState || {};
  2556. if (lastState.motion == "moveByWords" && !isWhiteSpaceString(text)) {
  2557. var match = (/\s+$/).exec(text);
  2558. if (match && lastState.motionArgs && lastState.motionArgs.forward) {
  2559. head = offsetCursor(head, 0, - match[0].length);
  2560. text = text.slice(0, - match[0].length);
  2561. }
  2562. }
  2563. var prevLineEnd = new Pos(anchor.line - 1, Number.MAX_VALUE);
  2564. var wasLastLine = cm.firstLine() == cm.lastLine();
  2565. if (head.line > cm.lastLine() && args.linewise && !wasLastLine) {
  2566. cm.replaceRange('', prevLineEnd, head);
  2567. } else {
  2568. cm.replaceRange('', anchor, head);
  2569. }
  2570. if (args.linewise) {
  2571. if (!wasLastLine) {
  2572. cm.setCursor(prevLineEnd);
  2573. CodeMirror.commands.newlineAndIndent(cm);
  2574. }
  2575. anchor.ch = Number.MAX_VALUE;
  2576. }
  2577. finalHead = anchor;
  2578. } else if (args.fullLine) {
  2579. head.ch = Number.MAX_VALUE;
  2580. head.line--;
  2581. cm.setSelection(anchor, head)
  2582. text = cm.getSelection();
  2583. cm.replaceSelection("");
  2584. finalHead = anchor;
  2585. } else {
  2586. text = cm.getSelection();
  2587. var replacement = fillArray('', ranges.length);
  2588. cm.replaceSelections(replacement);
  2589. finalHead = cursorMin(ranges[0].head, ranges[0].anchor);
  2590. }
  2591. vimGlobalState.registerController.pushText(
  2592. args.registerName, 'change', text,
  2593. args.linewise, ranges.length > 1);
  2594. actions.enterInsertMode(cm, {head: finalHead}, cm.state.vim);
  2595. },
  2596. 'delete': function(cm, args, ranges) {
  2597. var finalHead, text;
  2598. var vim = cm.state.vim;
  2599. if (!vim.visualBlock) {
  2600. var anchor = ranges[0].anchor,
  2601. head = ranges[0].head;
  2602. if (args.linewise &&
  2603. head.line != cm.firstLine() &&
  2604. anchor.line == cm.lastLine() &&
  2605. anchor.line == head.line - 1) {
  2606. if (anchor.line == cm.firstLine()) {
  2607. anchor.ch = 0;
  2608. } else {
  2609. anchor = Pos(anchor.line - 1, lineLength(cm, anchor.line - 1));
  2610. }
  2611. }
  2612. text = cm.getRange(anchor, head);
  2613. cm.replaceRange('', anchor, head);
  2614. finalHead = anchor;
  2615. if (args.linewise) {
  2616. finalHead = motions.moveToFirstNonWhiteSpaceCharacter(cm, anchor);
  2617. }
  2618. } else {
  2619. text = cm.getSelection();
  2620. var replacement = fillArray('', ranges.length);
  2621. cm.replaceSelections(replacement);
  2622. finalHead = ranges[0].anchor;
  2623. }
  2624. vimGlobalState.registerController.pushText(
  2625. args.registerName, 'delete', text,
  2626. args.linewise, vim.visualBlock);
  2627. var includeLineBreak = vim.insertMode
  2628. return clipCursorToContent(cm, finalHead, includeLineBreak);
  2629. },
  2630. indent: function(cm, args, ranges) {
  2631. var vim = cm.state.vim;
  2632. var startLine = ranges[0].anchor.line;
  2633. var endLine = vim.visualBlock ?
  2634. ranges[ranges.length - 1].anchor.line :
  2635. ranges[0].head.line;
  2636. var repeat = (vim.visualMode) ? args.repeat : 1;
  2637. if (args.linewise) {
  2638. endLine--;
  2639. }
  2640. for (var i = startLine; i <= endLine; i++) {
  2641. for (var j = 0; j < repeat; j++) {
  2642. cm.indentLine(i, args.indentRight);
  2643. }
  2644. }
  2645. return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);
  2646. },
  2647. indentAuto: function(cm, _args, ranges) {
  2648. cm.execCommand("indentAuto");
  2649. return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);
  2650. },
  2651. changeCase: function(cm, args, ranges, oldAnchor, newHead) {
  2652. var selections = cm.getSelections();
  2653. var swapped = [];
  2654. var toLower = args.toLower;
  2655. for (var j = 0; j < selections.length; j++) {
  2656. var toSwap = selections[j];
  2657. var text = '';
  2658. if (toLower === true) {
  2659. text = toSwap.toLowerCase();
  2660. } else if (toLower === false) {
  2661. text = toSwap.toUpperCase();
  2662. } else {
  2663. for (var i = 0; i < toSwap.length; i++) {
  2664. var character = toSwap.charAt(i);
  2665. text += isUpperCase(character) ? character.toLowerCase() :
  2666. character.toUpperCase();
  2667. }
  2668. }
  2669. swapped.push(text);
  2670. }
  2671. cm.replaceSelections(swapped);
  2672. if (args.shouldMoveCursor){
  2673. return newHead;
  2674. } else if (!cm.state.vim.visualMode && args.linewise && ranges[0].anchor.line + 1 == ranges[0].head.line) {
  2675. return motions.moveToFirstNonWhiteSpaceCharacter(cm, oldAnchor);
  2676. } else if (args.linewise){
  2677. return oldAnchor;
  2678. } else {
  2679. return cursorMin(ranges[0].anchor, ranges[0].head);
  2680. }
  2681. },
  2682. yank: function(cm, args, ranges, oldAnchor) {
  2683. var vim = cm.state.vim;
  2684. var text = cm.getSelection();
  2685. var endPos = vim.visualMode
  2686. ? cursorMin(vim.sel.anchor, vim.sel.head, ranges[0].head, ranges[0].anchor)
  2687. : oldAnchor;
  2688. vimGlobalState.registerController.pushText(
  2689. args.registerName, 'yank',
  2690. text, args.linewise, vim.visualBlock);
  2691. return endPos;
  2692. }
  2693. };
  2694. function defineOperator(name, fn) {
  2695. operators[name] = fn;
  2696. }
  2697. var actions = {
  2698. jumpListWalk: function(cm, actionArgs, vim) {
  2699. if (vim.visualMode) {
  2700. return;
  2701. }
  2702. var repeat = actionArgs.repeat;
  2703. var forward = actionArgs.forward;
  2704. var jumpList = vimGlobalState.jumpList;
  2705. var mark = jumpList.move(cm, forward ? repeat : -repeat);
  2706. var markPos = mark ? mark.find() : undefined;
  2707. markPos = markPos ? markPos : cm.getCursor();
  2708. cm.setCursor(markPos);
  2709. cm.ace.curOp.command.scrollIntoView = "center-animate"; // ace_patch
  2710. },
  2711. scroll: function(cm, actionArgs, vim) {
  2712. if (vim.visualMode) {
  2713. return;
  2714. }
  2715. var repeat = actionArgs.repeat || 1;
  2716. var lineHeight = cm.defaultTextHeight();
  2717. var top = cm.getScrollInfo().top;
  2718. var delta = lineHeight * repeat;
  2719. var newPos = actionArgs.forward ? top + delta : top - delta;
  2720. var cursor = copyCursor(cm.getCursor());
  2721. var cursorCoords = cm.charCoords(cursor, 'local');
  2722. if (actionArgs.forward) {
  2723. if (newPos > cursorCoords.top) {
  2724. cursor.line += (newPos - cursorCoords.top) / lineHeight;
  2725. cursor.line = Math.ceil(cursor.line);
  2726. cm.setCursor(cursor);
  2727. cursorCoords = cm.charCoords(cursor, 'local');
  2728. cm.scrollTo(null, cursorCoords.top);
  2729. } else {
  2730. cm.scrollTo(null, newPos);
  2731. }
  2732. } else {
  2733. var newBottom = newPos + cm.getScrollInfo().clientHeight;
  2734. if (newBottom < cursorCoords.bottom) {
  2735. cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight;
  2736. cursor.line = Math.floor(cursor.line);
  2737. cm.setCursor(cursor);
  2738. cursorCoords = cm.charCoords(cursor, 'local');
  2739. cm.scrollTo(
  2740. null, cursorCoords.bottom - cm.getScrollInfo().clientHeight);
  2741. } else {
  2742. cm.scrollTo(null, newPos);
  2743. }
  2744. }
  2745. },
  2746. scrollToCursor: function(cm, actionArgs) {
  2747. var lineNum = cm.getCursor().line;
  2748. var charCoords = cm.charCoords(Pos(lineNum, 0), 'local');
  2749. var height = cm.getScrollInfo().clientHeight;
  2750. var y = charCoords.top;
  2751. var lineHeight = charCoords.bottom - y;
  2752. switch (actionArgs.position) {
  2753. case 'center': y = y - (height / 2) + lineHeight;
  2754. break;
  2755. case 'bottom': y = y - height + lineHeight;
  2756. break;
  2757. }
  2758. cm.scrollTo(null, y);
  2759. },
  2760. replayMacro: function(cm, actionArgs, vim) {
  2761. var registerName = actionArgs.selectedCharacter;
  2762. var repeat = actionArgs.repeat;
  2763. var macroModeState = vimGlobalState.macroModeState;
  2764. if (registerName == '@') {
  2765. registerName = macroModeState.latestRegister;
  2766. } else {
  2767. macroModeState.latestRegister = registerName;
  2768. }
  2769. while(repeat--){
  2770. executeMacroRegister(cm, vim, macroModeState, registerName);
  2771. }
  2772. },
  2773. enterMacroRecordMode: function(cm, actionArgs) {
  2774. var macroModeState = vimGlobalState.macroModeState;
  2775. var registerName = actionArgs.selectedCharacter;
  2776. if (vimGlobalState.registerController.isValidRegister(registerName)) {
  2777. macroModeState.enterMacroRecordMode(cm, registerName);
  2778. }
  2779. },
  2780. toggleOverwrite: function(cm) {
  2781. if (!cm.state.overwrite) {
  2782. cm.toggleOverwrite(true);
  2783. cm.setOption('keyMap', 'vim-replace');
  2784. CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
  2785. } else {
  2786. cm.toggleOverwrite(false);
  2787. cm.setOption('keyMap', 'vim-insert');
  2788. CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
  2789. }
  2790. },
  2791. enterInsertMode: function(cm, actionArgs, vim) {
  2792. if (cm.getOption('readOnly')) { return; }
  2793. vim.insertMode = true;
  2794. vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1;
  2795. var insertAt = (actionArgs) ? actionArgs.insertAt : null;
  2796. var sel = vim.sel;
  2797. var head = actionArgs.head || cm.getCursor('head');
  2798. var height = cm.listSelections().length;
  2799. if (insertAt == 'eol') {
  2800. head = Pos(head.line, lineLength(cm, head.line));
  2801. } else if (insertAt == 'bol') {
  2802. head = Pos(head.line, 0);
  2803. } else if (insertAt == 'charAfter') {
  2804. head = offsetCursor(head, 0, 1);
  2805. } else if (insertAt == 'firstNonBlank') {
  2806. head = motions.moveToFirstNonWhiteSpaceCharacter(cm, head);
  2807. } else if (insertAt == 'startOfSelectedArea') {
  2808. if (!vim.visualMode)
  2809. return;
  2810. if (!vim.visualBlock) {
  2811. if (sel.head.line < sel.anchor.line) {
  2812. head = sel.head;
  2813. } else {
  2814. head = Pos(sel.anchor.line, 0);
  2815. }
  2816. } else {
  2817. head = Pos(
  2818. Math.min(sel.head.line, sel.anchor.line),
  2819. Math.min(sel.head.ch, sel.anchor.ch));
  2820. height = Math.abs(sel.head.line - sel.anchor.line) + 1;
  2821. }
  2822. } else if (insertAt == 'endOfSelectedArea') {
  2823. if (!vim.visualMode)
  2824. return;
  2825. if (!vim.visualBlock) {
  2826. if (sel.head.line >= sel.anchor.line) {
  2827. head = offsetCursor(sel.head, 0, 1);
  2828. } else {
  2829. head = Pos(sel.anchor.line, 0);
  2830. }
  2831. } else {
  2832. head = Pos(
  2833. Math.min(sel.head.line, sel.anchor.line),
  2834. Math.max(sel.head.ch + 1, sel.anchor.ch));
  2835. height = Math.abs(sel.head.line - sel.anchor.line) + 1;
  2836. }
  2837. } else if (insertAt == 'inplace') {
  2838. if (vim.visualMode){
  2839. return;
  2840. }
  2841. } else if (insertAt == 'lastEdit') {
  2842. head = getLastEditPos(cm) || head;
  2843. }
  2844. cm.setOption('disableInput', false);
  2845. if (actionArgs && actionArgs.replace) {
  2846. cm.toggleOverwrite(true);
  2847. cm.setOption('keyMap', 'vim-replace');
  2848. CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
  2849. } else {
  2850. cm.toggleOverwrite(false);
  2851. cm.setOption('keyMap', 'vim-insert');
  2852. CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
  2853. }
  2854. if (!vimGlobalState.macroModeState.isPlaying) {
  2855. cm.on('change', onChange);
  2856. CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
  2857. }
  2858. if (vim.visualMode) {
  2859. exitVisualMode(cm);
  2860. }
  2861. selectForInsert(cm, head, height);
  2862. },
  2863. toggleVisualMode: function(cm, actionArgs, vim) {
  2864. var repeat = actionArgs.repeat;
  2865. var anchor = cm.getCursor();
  2866. var head;
  2867. if (!vim.visualMode) {
  2868. vim.visualMode = true;
  2869. vim.visualLine = !!actionArgs.linewise;
  2870. vim.visualBlock = !!actionArgs.blockwise;
  2871. head = clipCursorToContent(
  2872. cm, Pos(anchor.line, anchor.ch + repeat - 1),
  2873. true /** includeLineBreak */);
  2874. vim.sel = {
  2875. anchor: anchor,
  2876. head: head
  2877. };
  2878. CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
  2879. updateCmSelection(cm);
  2880. updateMark(cm, vim, '<', cursorMin(anchor, head));
  2881. updateMark(cm, vim, '>', cursorMax(anchor, head));
  2882. } else if (vim.visualLine ^ actionArgs.linewise ||
  2883. vim.visualBlock ^ actionArgs.blockwise) {
  2884. vim.visualLine = !!actionArgs.linewise;
  2885. vim.visualBlock = !!actionArgs.blockwise;
  2886. CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
  2887. updateCmSelection(cm);
  2888. } else {
  2889. exitVisualMode(cm);
  2890. }
  2891. },
  2892. reselectLastSelection: function(cm, _actionArgs, vim) {
  2893. var lastSelection = vim.lastSelection;
  2894. if (vim.visualMode) {
  2895. updateLastSelection(cm, vim);
  2896. }
  2897. if (lastSelection) {
  2898. var anchor = lastSelection.anchorMark.find();
  2899. var head = lastSelection.headMark.find();
  2900. if (!anchor || !head) {
  2901. return;
  2902. }
  2903. vim.sel = {
  2904. anchor: anchor,
  2905. head: head
  2906. };
  2907. vim.visualMode = true;
  2908. vim.visualLine = lastSelection.visualLine;
  2909. vim.visualBlock = lastSelection.visualBlock;
  2910. updateCmSelection(cm);
  2911. updateMark(cm, vim, '<', cursorMin(anchor, head));
  2912. updateMark(cm, vim, '>', cursorMax(anchor, head));
  2913. CodeMirror.signal(cm, 'vim-mode-change', {
  2914. mode: 'visual',
  2915. subMode: vim.visualLine ? 'linewise' :
  2916. vim.visualBlock ? 'blockwise' : ''});
  2917. }
  2918. },
  2919. joinLines: function(cm, actionArgs, vim) {
  2920. var curStart, curEnd;
  2921. if (vim.visualMode) {
  2922. curStart = cm.getCursor('anchor');
  2923. curEnd = cm.getCursor('head');
  2924. if (cursorIsBefore(curEnd, curStart)) {
  2925. var tmp = curEnd;
  2926. curEnd = curStart;
  2927. curStart = tmp;
  2928. }
  2929. curEnd.ch = lineLength(cm, curEnd.line) - 1;
  2930. } else {
  2931. var repeat = Math.max(actionArgs.repeat, 2);
  2932. curStart = cm.getCursor();
  2933. curEnd = clipCursorToContent(cm, Pos(curStart.line + repeat - 1,
  2934. Infinity));
  2935. }
  2936. var finalCh = 0;
  2937. for (var i = curStart.line; i < curEnd.line; i++) {
  2938. finalCh = lineLength(cm, curStart.line);
  2939. var tmp = Pos(curStart.line + 1,
  2940. lineLength(cm, curStart.line + 1));
  2941. var text = cm.getRange(curStart, tmp);
  2942. text = actionArgs.keepSpaces
  2943. ? text.replace(/\n\r?/g, '')
  2944. : text.replace(/\n\s*/g, ' ');
  2945. cm.replaceRange(text, curStart, tmp);
  2946. }
  2947. var curFinalPos = Pos(curStart.line, finalCh);
  2948. if (vim.visualMode) {
  2949. exitVisualMode(cm, false);
  2950. }
  2951. cm.setCursor(curFinalPos);
  2952. },
  2953. newLineAndEnterInsertMode: function(cm, actionArgs, vim) {
  2954. vim.insertMode = true;
  2955. var insertAt = copyCursor(cm.getCursor());
  2956. if (insertAt.line === cm.firstLine() && !actionArgs.after) {
  2957. cm.replaceRange('\n', Pos(cm.firstLine(), 0));
  2958. cm.setCursor(cm.firstLine(), 0);
  2959. } else {
  2960. insertAt.line = (actionArgs.after) ? insertAt.line :
  2961. insertAt.line - 1;
  2962. insertAt.ch = lineLength(cm, insertAt.line);
  2963. cm.setCursor(insertAt);
  2964. var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||
  2965. CodeMirror.commands.newlineAndIndent;
  2966. newlineFn(cm);
  2967. }
  2968. this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim);
  2969. },
  2970. paste: function(cm, actionArgs, vim) {
  2971. var cur = copyCursor(cm.getCursor());
  2972. var register = vimGlobalState.registerController.getRegister(
  2973. actionArgs.registerName);
  2974. var text = register.toString();
  2975. if (!text) {
  2976. return;
  2977. }
  2978. if (actionArgs.matchIndent) {
  2979. var tabSize = cm.getOption("tabSize");
  2980. var whitespaceLength = function(str) {
  2981. var tabs = (str.split("\t").length - 1);
  2982. var spaces = (str.split(" ").length - 1);
  2983. return tabs * tabSize + spaces * 1;
  2984. };
  2985. var currentLine = cm.getLine(cm.getCursor().line);
  2986. var indent = whitespaceLength(currentLine.match(/^\s*/)[0]);
  2987. var chompedText = text.replace(/\n$/, '');
  2988. var wasChomped = text !== chompedText;
  2989. var firstIndent = whitespaceLength(text.match(/^\s*/)[0]);
  2990. var text = chompedText.replace(/^\s*/gm, function(wspace) {
  2991. var newIndent = indent + (whitespaceLength(wspace) - firstIndent);
  2992. if (newIndent < 0) {
  2993. return "";
  2994. }
  2995. else if (cm.getOption("indentWithTabs")) {
  2996. var quotient = Math.floor(newIndent / tabSize);
  2997. return Array(quotient + 1).join('\t');
  2998. }
  2999. else {
  3000. return Array(newIndent + 1).join(' ');
  3001. }
  3002. });
  3003. text += wasChomped ? "\n" : "";
  3004. }
  3005. if (actionArgs.repeat > 1) {
  3006. var text = Array(actionArgs.repeat + 1).join(text);
  3007. }
  3008. var linewise = register.linewise;
  3009. var blockwise = register.blockwise;
  3010. if (blockwise) {
  3011. text = text.split('\n');
  3012. if (linewise) {
  3013. text.pop();
  3014. }
  3015. for (var i = 0; i < text.length; i++) {
  3016. text[i] = (text[i] == '') ? ' ' : text[i];
  3017. }
  3018. cur.ch += actionArgs.after ? 1 : 0;
  3019. cur.ch = Math.min(lineLength(cm, cur.line), cur.ch);
  3020. } else if (linewise) {
  3021. if(vim.visualMode) {
  3022. text = vim.visualLine ? text.slice(0, -1) : '\n' + text.slice(0, text.length - 1) + '\n';
  3023. } else if (actionArgs.after) {
  3024. text = '\n' + text.slice(0, text.length - 1);
  3025. cur.ch = lineLength(cm, cur.line);
  3026. } else {
  3027. cur.ch = 0;
  3028. }
  3029. } else {
  3030. cur.ch += actionArgs.after ? 1 : 0;
  3031. }
  3032. var curPosFinal;
  3033. var idx;
  3034. if (vim.visualMode) {
  3035. vim.lastPastedText = text;
  3036. var lastSelectionCurEnd;
  3037. var selectedArea = getSelectedAreaRange(cm, vim);
  3038. var selectionStart = selectedArea[0];
  3039. var selectionEnd = selectedArea[1];
  3040. var selectedText = cm.getSelection();
  3041. var selections = cm.listSelections();
  3042. var emptyStrings = new Array(selections.length).join('1').split('1');
  3043. if (vim.lastSelection) {
  3044. lastSelectionCurEnd = vim.lastSelection.headMark.find();
  3045. }
  3046. vimGlobalState.registerController.unnamedRegister.setText(selectedText);
  3047. if (blockwise) {
  3048. cm.replaceSelections(emptyStrings);
  3049. selectionEnd = Pos(selectionStart.line + text.length-1, selectionStart.ch);
  3050. cm.setCursor(selectionStart);
  3051. selectBlock(cm, selectionEnd);
  3052. cm.replaceSelections(text);
  3053. curPosFinal = selectionStart;
  3054. } else if (vim.visualBlock) {
  3055. cm.replaceSelections(emptyStrings);
  3056. cm.setCursor(selectionStart);
  3057. cm.replaceRange(text, selectionStart, selectionStart);
  3058. curPosFinal = selectionStart;
  3059. } else {
  3060. cm.replaceRange(text, selectionStart, selectionEnd);
  3061. curPosFinal = cm.posFromIndex(cm.indexFromPos(selectionStart) + text.length - 1);
  3062. }
  3063. if(lastSelectionCurEnd) {
  3064. vim.lastSelection.headMark = cm.setBookmark(lastSelectionCurEnd);
  3065. }
  3066. if (linewise) {
  3067. curPosFinal.ch=0;
  3068. }
  3069. } else {
  3070. if (blockwise) {
  3071. cm.setCursor(cur);
  3072. for (var i = 0; i < text.length; i++) {
  3073. var line = cur.line+i;
  3074. if (line > cm.lastLine()) {
  3075. cm.replaceRange('\n', Pos(line, 0));
  3076. }
  3077. var lastCh = lineLength(cm, line);
  3078. if (lastCh < cur.ch) {
  3079. extendLineToColumn(cm, line, cur.ch);
  3080. }
  3081. }
  3082. cm.setCursor(cur);
  3083. selectBlock(cm, Pos(cur.line + text.length-1, cur.ch));
  3084. cm.replaceSelections(text);
  3085. curPosFinal = cur;
  3086. } else {
  3087. cm.replaceRange(text, cur);
  3088. if (linewise && actionArgs.after) {
  3089. curPosFinal = Pos(
  3090. cur.line + 1,
  3091. findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1)));
  3092. } else if (linewise && !actionArgs.after) {
  3093. curPosFinal = Pos(
  3094. cur.line,
  3095. findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line)));
  3096. } else if (!linewise && actionArgs.after) {
  3097. idx = cm.indexFromPos(cur);
  3098. curPosFinal = cm.posFromIndex(idx + text.length - 1);
  3099. } else {
  3100. idx = cm.indexFromPos(cur);
  3101. curPosFinal = cm.posFromIndex(idx + text.length);
  3102. }
  3103. }
  3104. }
  3105. if (vim.visualMode) {
  3106. exitVisualMode(cm, false);
  3107. }
  3108. cm.setCursor(curPosFinal);
  3109. },
  3110. undo: function(cm, actionArgs) {
  3111. cm.operation(function() {
  3112. repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();
  3113. cm.setCursor(cm.getCursor('anchor'));
  3114. });
  3115. },
  3116. redo: function(cm, actionArgs) {
  3117. repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();
  3118. },
  3119. setRegister: function(_cm, actionArgs, vim) {
  3120. vim.inputState.registerName = actionArgs.selectedCharacter;
  3121. },
  3122. setMark: function(cm, actionArgs, vim) {
  3123. var markName = actionArgs.selectedCharacter;
  3124. updateMark(cm, vim, markName, cm.getCursor());
  3125. },
  3126. replace: function(cm, actionArgs, vim) {
  3127. var replaceWith = actionArgs.selectedCharacter;
  3128. var curStart = cm.getCursor();
  3129. var replaceTo;
  3130. var curEnd;
  3131. var selections = cm.listSelections();
  3132. if (vim.visualMode) {
  3133. curStart = cm.getCursor('start');
  3134. curEnd = cm.getCursor('end');
  3135. } else {
  3136. var line = cm.getLine(curStart.line);
  3137. replaceTo = curStart.ch + actionArgs.repeat;
  3138. if (replaceTo > line.length) {
  3139. replaceTo=line.length;
  3140. }
  3141. curEnd = Pos(curStart.line, replaceTo);
  3142. }
  3143. if (replaceWith=='\n') {
  3144. if (!vim.visualMode) cm.replaceRange('', curStart, curEnd);
  3145. (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm);
  3146. } else {
  3147. var replaceWithStr = cm.getRange(curStart, curEnd);
  3148. replaceWithStr = replaceWithStr.replace(/[^\n]/g, replaceWith);
  3149. if (vim.visualBlock) {
  3150. var spaces = new Array(cm.getOption("tabSize")+1).join(' ');
  3151. replaceWithStr = cm.getSelection();
  3152. replaceWithStr = replaceWithStr.replace(/\t/g, spaces).replace(/[^\n]/g, replaceWith).split('\n');
  3153. cm.replaceSelections(replaceWithStr);
  3154. } else {
  3155. cm.replaceRange(replaceWithStr, curStart, curEnd);
  3156. }
  3157. if (vim.visualMode) {
  3158. curStart = cursorIsBefore(selections[0].anchor, selections[0].head) ?
  3159. selections[0].anchor : selections[0].head;
  3160. cm.setCursor(curStart);
  3161. exitVisualMode(cm, false);
  3162. } else {
  3163. cm.setCursor(offsetCursor(curEnd, 0, -1));
  3164. }
  3165. }
  3166. },
  3167. incrementNumberToken: function(cm, actionArgs) {
  3168. var cur = cm.getCursor();
  3169. var lineStr = cm.getLine(cur.line);
  3170. var re = /(-?)(?:(0x)([\da-f]+)|(0b|0|)(\d+))/gi;
  3171. var match;
  3172. var start;
  3173. var end;
  3174. var numberStr;
  3175. while ((match = re.exec(lineStr)) !== null) {
  3176. start = match.index;
  3177. end = start + match[0].length;
  3178. if (cur.ch < end)break;
  3179. }
  3180. if (!actionArgs.backtrack && (end <= cur.ch))return;
  3181. if (match) {
  3182. var baseStr = match[2] || match[4]
  3183. var digits = match[3] || match[5]
  3184. var increment = actionArgs.increase ? 1 : -1;
  3185. var base = {'0b': 2, '0': 8, '': 10, '0x': 16}[baseStr.toLowerCase()];
  3186. var number = parseInt(match[1] + digits, base) + (increment * actionArgs.repeat);
  3187. numberStr = number.toString(base);
  3188. var zeroPadding = baseStr ? new Array(digits.length - numberStr.length + 1 + match[1].length).join('0') : ''
  3189. if (numberStr.charAt(0) === '-') {
  3190. numberStr = '-' + baseStr + zeroPadding + numberStr.substr(1);
  3191. } else {
  3192. numberStr = baseStr + zeroPadding + numberStr;
  3193. }
  3194. var from = Pos(cur.line, start);
  3195. var to = Pos(cur.line, end);
  3196. cm.replaceRange(numberStr, from, to);
  3197. } else {
  3198. return;
  3199. }
  3200. cm.setCursor(Pos(cur.line, start + numberStr.length - 1));
  3201. },
  3202. repeatLastEdit: function(cm, actionArgs, vim) {
  3203. var lastEditInputState = vim.lastEditInputState;
  3204. if (!lastEditInputState) { return; }
  3205. var repeat = actionArgs.repeat;
  3206. if (repeat && actionArgs.repeatIsExplicit) {
  3207. vim.lastEditInputState.repeatOverride = repeat;
  3208. } else {
  3209. repeat = vim.lastEditInputState.repeatOverride || repeat;
  3210. }
  3211. repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);
  3212. },
  3213. indent: function(cm, actionArgs) {
  3214. cm.indentLine(cm.getCursor().line, actionArgs.indentRight);
  3215. },
  3216. exitInsertMode: exitInsertMode
  3217. };
  3218. function defineAction(name, fn) {
  3219. actions[name] = fn;
  3220. }
  3221. function clipCursorToContent(cm, cur, includeLineBreak) {
  3222. var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() );
  3223. var maxCh = lineLength(cm, line) - 1;
  3224. maxCh = (includeLineBreak) ? maxCh + 1 : maxCh;
  3225. var ch = Math.min(Math.max(0, cur.ch), maxCh);
  3226. return Pos(line, ch);
  3227. }
  3228. function copyArgs(args) {
  3229. var ret = {};
  3230. for (var prop in args) {
  3231. if (args.hasOwnProperty(prop)) {
  3232. ret[prop] = args[prop];
  3233. }
  3234. }
  3235. return ret;
  3236. }
  3237. function offsetCursor(cur, offsetLine, offsetCh) {
  3238. if (typeof offsetLine === 'object') {
  3239. offsetCh = offsetLine.ch;
  3240. offsetLine = offsetLine.line;
  3241. }
  3242. return Pos(cur.line + offsetLine, cur.ch + offsetCh);
  3243. }
  3244. function commandMatches(keys, keyMap, context, inputState) {
  3245. var match, partial = [], full = [];
  3246. for (var i = 0; i < keyMap.length; i++) {
  3247. var command = keyMap[i];
  3248. if (context == 'insert' && command.context != 'insert' ||
  3249. command.context && command.context != context ||
  3250. inputState.operator && command.type == 'action' ||
  3251. !(match = commandMatch(keys, command.keys))) { continue; }
  3252. if (match == 'partial') { partial.push(command); }
  3253. if (match == 'full') { full.push(command); }
  3254. }
  3255. return {
  3256. partial: partial.length && partial,
  3257. full: full.length && full
  3258. };
  3259. }
  3260. function commandMatch(pressed, mapped) {
  3261. if (mapped.slice(-11) == '<character>') {
  3262. var prefixLen = mapped.length - 11;
  3263. var pressedPrefix = pressed.slice(0, prefixLen);
  3264. var mappedPrefix = mapped.slice(0, prefixLen);
  3265. return pressedPrefix == mappedPrefix && pressed.length > prefixLen ? 'full' :
  3266. mappedPrefix.indexOf(pressedPrefix) == 0 ? 'partial' : false;
  3267. } else {
  3268. return pressed == mapped ? 'full' :
  3269. mapped.indexOf(pressed) == 0 ? 'partial' : false;
  3270. }
  3271. }
  3272. function lastChar(keys) {
  3273. var match = /^.*(<[^>]+>)$/.exec(keys);
  3274. var selectedCharacter = match ? match[1] : keys.slice(-1);
  3275. if (selectedCharacter.length > 1){
  3276. switch(selectedCharacter){
  3277. case '<CR>':
  3278. selectedCharacter='\n';
  3279. break;
  3280. case '<Space>':
  3281. selectedCharacter=' ';
  3282. break;
  3283. default:
  3284. selectedCharacter='';
  3285. break;
  3286. }
  3287. }
  3288. return selectedCharacter;
  3289. }
  3290. function repeatFn(cm, fn, repeat) {
  3291. return function() {
  3292. for (var i = 0; i < repeat; i++) {
  3293. fn(cm);
  3294. }
  3295. };
  3296. }
  3297. function copyCursor(cur) {
  3298. return Pos(cur.line, cur.ch);
  3299. }
  3300. function cursorEqual(cur1, cur2) {
  3301. return cur1.ch == cur2.ch && cur1.line == cur2.line;
  3302. }
  3303. function cursorIsBefore(cur1, cur2) {
  3304. if (cur1.line < cur2.line) {
  3305. return true;
  3306. }
  3307. if (cur1.line == cur2.line && cur1.ch < cur2.ch) {
  3308. return true;
  3309. }
  3310. return false;
  3311. }
  3312. function cursorMin(cur1, cur2) {
  3313. if (arguments.length > 2) {
  3314. cur2 = cursorMin.apply(undefined, Array.prototype.slice.call(arguments, 1));
  3315. }
  3316. return cursorIsBefore(cur1, cur2) ? cur1 : cur2;
  3317. }
  3318. function cursorMax(cur1, cur2) {
  3319. if (arguments.length > 2) {
  3320. cur2 = cursorMax.apply(undefined, Array.prototype.slice.call(arguments, 1));
  3321. }
  3322. return cursorIsBefore(cur1, cur2) ? cur2 : cur1;
  3323. }
  3324. function cursorIsBetween(cur1, cur2, cur3) {
  3325. var cur1before2 = cursorIsBefore(cur1, cur2);
  3326. var cur2before3 = cursorIsBefore(cur2, cur3);
  3327. return cur1before2 && cur2before3;
  3328. }
  3329. function lineLength(cm, lineNum) {
  3330. return cm.getLine(lineNum).length;
  3331. }
  3332. function trim(s) {
  3333. if (s.trim) {
  3334. return s.trim();
  3335. }
  3336. return s.replace(/^\s+|\s+$/g, '');
  3337. }
  3338. function escapeRegex(s) {
  3339. return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1');
  3340. }
  3341. function extendLineToColumn(cm, lineNum, column) {
  3342. var endCh = lineLength(cm, lineNum);
  3343. var spaces = new Array(column-endCh+1).join(' ');
  3344. cm.setCursor(Pos(lineNum, endCh));
  3345. cm.replaceRange(spaces, cm.getCursor());
  3346. }
  3347. function selectBlock(cm, selectionEnd) {
  3348. var selections = [], ranges = cm.listSelections();
  3349. var head = copyCursor(cm.clipPos(selectionEnd));
  3350. var isClipped = !cursorEqual(selectionEnd, head);
  3351. var curHead = cm.getCursor('head');
  3352. var primIndex = getIndex(ranges, curHead);
  3353. var wasClipped = cursorEqual(ranges[primIndex].head, ranges[primIndex].anchor);
  3354. var max = ranges.length - 1;
  3355. var index = max - primIndex > primIndex ? max : 0;
  3356. var base = ranges[index].anchor;
  3357. var firstLine = Math.min(base.line, head.line);
  3358. var lastLine = Math.max(base.line, head.line);
  3359. var baseCh = base.ch, headCh = head.ch;
  3360. var dir = ranges[index].head.ch - baseCh;
  3361. var newDir = headCh - baseCh;
  3362. if (dir > 0 && newDir <= 0) {
  3363. baseCh++;
  3364. if (!isClipped) { headCh--; }
  3365. } else if (dir < 0 && newDir >= 0) {
  3366. baseCh--;
  3367. if (!wasClipped) { headCh++; }
  3368. } else if (dir < 0 && newDir == -1) {
  3369. baseCh--;
  3370. headCh++;
  3371. }
  3372. for (var line = firstLine; line <= lastLine; line++) {
  3373. var range = {anchor: new Pos(line, baseCh), head: new Pos(line, headCh)};
  3374. selections.push(range);
  3375. }
  3376. cm.setSelections(selections);
  3377. selectionEnd.ch = headCh;
  3378. base.ch = baseCh;
  3379. return base;
  3380. }
  3381. function selectForInsert(cm, head, height) {
  3382. var sel = [];
  3383. for (var i = 0; i < height; i++) {
  3384. var lineHead = offsetCursor(head, i, 0);
  3385. sel.push({anchor: lineHead, head: lineHead});
  3386. }
  3387. cm.setSelections(sel, 0);
  3388. }
  3389. function getIndex(ranges, cursor, end) {
  3390. for (var i = 0; i < ranges.length; i++) {
  3391. var atAnchor = end != 'head' && cursorEqual(ranges[i].anchor, cursor);
  3392. var atHead = end != 'anchor' && cursorEqual(ranges[i].head, cursor);
  3393. if (atAnchor || atHead) {
  3394. return i;
  3395. }
  3396. }
  3397. return -1;
  3398. }
  3399. function getSelectedAreaRange(cm, vim) {
  3400. var lastSelection = vim.lastSelection;
  3401. var getCurrentSelectedAreaRange = function() {
  3402. var selections = cm.listSelections();
  3403. var start = selections[0];
  3404. var end = selections[selections.length-1];
  3405. var selectionStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head;
  3406. var selectionEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor;
  3407. return [selectionStart, selectionEnd];
  3408. };
  3409. var getLastSelectedAreaRange = function() {
  3410. var selectionStart = cm.getCursor();
  3411. var selectionEnd = cm.getCursor();
  3412. var block = lastSelection.visualBlock;
  3413. if (block) {
  3414. var width = block.width;
  3415. var height = block.height;
  3416. selectionEnd = Pos(selectionStart.line + height, selectionStart.ch + width);
  3417. var selections = [];
  3418. for (var i = selectionStart.line; i < selectionEnd.line; i++) {
  3419. var anchor = Pos(i, selectionStart.ch);
  3420. var head = Pos(i, selectionEnd.ch);
  3421. var range = {anchor: anchor, head: head};
  3422. selections.push(range);
  3423. }
  3424. cm.setSelections(selections);
  3425. } else {
  3426. var start = lastSelection.anchorMark.find();
  3427. var end = lastSelection.headMark.find();
  3428. var line = end.line - start.line;
  3429. var ch = end.ch - start.ch;
  3430. selectionEnd = {line: selectionEnd.line + line, ch: line ? selectionEnd.ch : ch + selectionEnd.ch};
  3431. if (lastSelection.visualLine) {
  3432. selectionStart = Pos(selectionStart.line, 0);
  3433. selectionEnd = Pos(selectionEnd.line, lineLength(cm, selectionEnd.line));
  3434. }
  3435. cm.setSelection(selectionStart, selectionEnd);
  3436. }
  3437. return [selectionStart, selectionEnd];
  3438. };
  3439. if (!vim.visualMode) {
  3440. return getLastSelectedAreaRange();
  3441. } else {
  3442. return getCurrentSelectedAreaRange();
  3443. }
  3444. }
  3445. function updateLastSelection(cm, vim) {
  3446. var anchor = vim.sel.anchor;
  3447. var head = vim.sel.head;
  3448. if (vim.lastPastedText) {
  3449. head = cm.posFromIndex(cm.indexFromPos(anchor) + vim.lastPastedText.length);
  3450. vim.lastPastedText = null;
  3451. }
  3452. vim.lastSelection = {'anchorMark': cm.setBookmark(anchor),
  3453. 'headMark': cm.setBookmark(head),
  3454. 'anchor': copyCursor(anchor),
  3455. 'head': copyCursor(head),
  3456. 'visualMode': vim.visualMode,
  3457. 'visualLine': vim.visualLine,
  3458. 'visualBlock': vim.visualBlock};
  3459. }
  3460. function expandSelection(cm, start, end) {
  3461. var sel = cm.state.vim.sel;
  3462. var head = sel.head;
  3463. var anchor = sel.anchor;
  3464. var tmp;
  3465. if (cursorIsBefore(end, start)) {
  3466. tmp = end;
  3467. end = start;
  3468. start = tmp;
  3469. }
  3470. if (cursorIsBefore(head, anchor)) {
  3471. head = cursorMin(start, head);
  3472. anchor = cursorMax(anchor, end);
  3473. } else {
  3474. anchor = cursorMin(start, anchor);
  3475. head = cursorMax(head, end);
  3476. head = offsetCursor(head, 0, -1);
  3477. if (head.ch == -1 && head.line != cm.firstLine()) {
  3478. head = Pos(head.line - 1, lineLength(cm, head.line - 1));
  3479. }
  3480. }
  3481. return [anchor, head];
  3482. }
  3483. function updateCmSelection(cm, sel, mode) {
  3484. var vim = cm.state.vim;
  3485. sel = sel || vim.sel;
  3486. var mode = mode ||
  3487. vim.visualLine ? 'line' : vim.visualBlock ? 'block' : 'char';
  3488. var cmSel = makeCmSelection(cm, sel, mode);
  3489. cm.setSelections(cmSel.ranges, cmSel.primary);
  3490. updateFakeCursor(cm);
  3491. }
  3492. function makeCmSelection(cm, sel, mode, exclusive) {
  3493. var head = copyCursor(sel.head);
  3494. var anchor = copyCursor(sel.anchor);
  3495. if (mode == 'char') {
  3496. var headOffset = !exclusive && !cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
  3497. var anchorOffset = cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
  3498. head = offsetCursor(sel.head, 0, headOffset);
  3499. anchor = offsetCursor(sel.anchor, 0, anchorOffset);
  3500. return {
  3501. ranges: [{anchor: anchor, head: head}],
  3502. primary: 0
  3503. };
  3504. } else if (mode == 'line') {
  3505. if (!cursorIsBefore(sel.head, sel.anchor)) {
  3506. anchor.ch = 0;
  3507. var lastLine = cm.lastLine();
  3508. if (head.line > lastLine) {
  3509. head.line = lastLine;
  3510. }
  3511. head.ch = lineLength(cm, head.line);
  3512. } else {
  3513. head.ch = 0;
  3514. anchor.ch = lineLength(cm, anchor.line);
  3515. }
  3516. return {
  3517. ranges: [{anchor: anchor, head: head}],
  3518. primary: 0
  3519. };
  3520. } else if (mode == 'block') {
  3521. var top = Math.min(anchor.line, head.line),
  3522. left = Math.min(anchor.ch, head.ch),
  3523. bottom = Math.max(anchor.line, head.line),
  3524. right = Math.max(anchor.ch, head.ch) + 1;
  3525. var height = bottom - top + 1;
  3526. var primary = head.line == top ? 0 : height - 1;
  3527. var ranges = [];
  3528. for (var i = 0; i < height; i++) {
  3529. ranges.push({
  3530. anchor: Pos(top + i, left),
  3531. head: Pos(top + i, right)
  3532. });
  3533. }
  3534. return {
  3535. ranges: ranges,
  3536. primary: primary
  3537. };
  3538. }
  3539. }
  3540. function getHead(cm) {
  3541. var cur = cm.getCursor('head');
  3542. if (cm.getSelection().length == 1) {
  3543. cur = cursorMin(cur, cm.getCursor('anchor'));
  3544. }
  3545. return cur;
  3546. }
  3547. function exitVisualMode(cm, moveHead) {
  3548. var vim = cm.state.vim;
  3549. if (moveHead !== false) {
  3550. cm.setCursor(clipCursorToContent(cm, vim.sel.head));
  3551. }
  3552. updateLastSelection(cm, vim);
  3553. vim.visualMode = false;
  3554. vim.visualLine = false;
  3555. vim.visualBlock = false;
  3556. CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
  3557. if (vim.fakeCursor) {
  3558. vim.fakeCursor.clear();
  3559. }
  3560. }
  3561. function clipToLine(cm, curStart, curEnd) {
  3562. var selection = cm.getRange(curStart, curEnd);
  3563. if (/\n\s*$/.test(selection)) {
  3564. var lines = selection.split('\n');
  3565. lines.pop();
  3566. var line;
  3567. for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {
  3568. curEnd.line--;
  3569. curEnd.ch = 0;
  3570. }
  3571. if (line) {
  3572. curEnd.line--;
  3573. curEnd.ch = lineLength(cm, curEnd.line);
  3574. } else {
  3575. curEnd.ch = 0;
  3576. }
  3577. }
  3578. }
  3579. function expandSelectionToLine(_cm, curStart, curEnd) {
  3580. curStart.ch = 0;
  3581. curEnd.ch = 0;
  3582. curEnd.line++;
  3583. }
  3584. function findFirstNonWhiteSpaceCharacter(text) {
  3585. if (!text) {
  3586. return 0;
  3587. }
  3588. var firstNonWS = text.search(/\S/);
  3589. return firstNonWS == -1 ? text.length : firstNonWS;
  3590. }
  3591. function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) {
  3592. var cur = getHead(cm);
  3593. var line = cm.getLine(cur.line);
  3594. var idx = cur.ch;
  3595. var test = noSymbol ? wordCharTest[0] : bigWordCharTest [0];
  3596. while (!test(line.charAt(idx))) {
  3597. idx++;
  3598. if (idx >= line.length) { return null; }
  3599. }
  3600. if (bigWord) {
  3601. test = bigWordCharTest[0];
  3602. } else {
  3603. test = wordCharTest[0];
  3604. if (!test(line.charAt(idx))) {
  3605. test = wordCharTest[1];
  3606. }
  3607. }
  3608. var end = idx, start = idx;
  3609. while (test(line.charAt(end)) && end < line.length) { end++; }
  3610. while (test(line.charAt(start)) && start >= 0) { start--; }
  3611. start++;
  3612. if (inclusive) {
  3613. var wordEnd = end;
  3614. while (/\s/.test(line.charAt(end)) && end < line.length) { end++; }
  3615. if (wordEnd == end) {
  3616. var wordStart = start;
  3617. while (/\s/.test(line.charAt(start - 1)) && start > 0) { start--; }
  3618. if (!start) { start = wordStart; }
  3619. }
  3620. }
  3621. return { start: Pos(cur.line, start), end: Pos(cur.line, end) };
  3622. }
  3623. function recordJumpPosition(cm, oldCur, newCur) {
  3624. if (!cursorEqual(oldCur, newCur)) {
  3625. vimGlobalState.jumpList.add(cm, oldCur, newCur);
  3626. }
  3627. }
  3628. function recordLastCharacterSearch(increment, args) {
  3629. vimGlobalState.lastCharacterSearch.increment = increment;
  3630. vimGlobalState.lastCharacterSearch.forward = args.forward;
  3631. vimGlobalState.lastCharacterSearch.selectedCharacter = args.selectedCharacter;
  3632. }
  3633. var symbolToMode = {
  3634. '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',
  3635. '[': 'section', ']': 'section',
  3636. '*': 'comment', '/': 'comment',
  3637. 'm': 'method', 'M': 'method',
  3638. '#': 'preprocess'
  3639. };
  3640. var findSymbolModes = {
  3641. bracket: {
  3642. isComplete: function(state) {
  3643. if (state.nextCh === state.symb) {
  3644. state.depth++;
  3645. if (state.depth >= 1)return true;
  3646. } else if (state.nextCh === state.reverseSymb) {
  3647. state.depth--;
  3648. }
  3649. return false;
  3650. }
  3651. },
  3652. section: {
  3653. init: function(state) {
  3654. state.curMoveThrough = true;
  3655. state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';
  3656. },
  3657. isComplete: function(state) {
  3658. return state.index === 0 && state.nextCh === state.symb;
  3659. }
  3660. },
  3661. comment: {
  3662. isComplete: function(state) {
  3663. var found = state.lastCh === '*' && state.nextCh === '/';
  3664. state.lastCh = state.nextCh;
  3665. return found;
  3666. }
  3667. },
  3668. method: {
  3669. init: function(state) {
  3670. state.symb = (state.symb === 'm' ? '{' : '}');
  3671. state.reverseSymb = state.symb === '{' ? '}' : '{';
  3672. },
  3673. isComplete: function(state) {
  3674. if (state.nextCh === state.symb)return true;
  3675. return false;
  3676. }
  3677. },
  3678. preprocess: {
  3679. init: function(state) {
  3680. state.index = 0;
  3681. },
  3682. isComplete: function(state) {
  3683. if (state.nextCh === '#') {
  3684. var token = state.lineText.match(/#(\w+)/)[1];
  3685. if (token === 'endif') {
  3686. if (state.forward && state.depth === 0) {
  3687. return true;
  3688. }
  3689. state.depth++;
  3690. } else if (token === 'if') {
  3691. if (!state.forward && state.depth === 0) {
  3692. return true;
  3693. }
  3694. state.depth--;
  3695. }
  3696. if (token === 'else' && state.depth === 0)return true;
  3697. }
  3698. return false;
  3699. }
  3700. }
  3701. };
  3702. function findSymbol(cm, repeat, forward, symb) {
  3703. var cur = copyCursor(cm.getCursor());
  3704. var increment = forward ? 1 : -1;
  3705. var endLine = forward ? cm.lineCount() : -1;
  3706. var curCh = cur.ch;
  3707. var line = cur.line;
  3708. var lineText = cm.getLine(line);
  3709. var state = {
  3710. lineText: lineText,
  3711. nextCh: lineText.charAt(curCh),
  3712. lastCh: null,
  3713. index: curCh,
  3714. symb: symb,
  3715. reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],
  3716. forward: forward,
  3717. depth: 0,
  3718. curMoveThrough: false
  3719. };
  3720. var mode = symbolToMode[symb];
  3721. if (!mode)return cur;
  3722. var init = findSymbolModes[mode].init;
  3723. var isComplete = findSymbolModes[mode].isComplete;
  3724. if (init) { init(state); }
  3725. while (line !== endLine && repeat) {
  3726. state.index += increment;
  3727. state.nextCh = state.lineText.charAt(state.index);
  3728. if (!state.nextCh) {
  3729. line += increment;
  3730. state.lineText = cm.getLine(line) || '';
  3731. if (increment > 0) {
  3732. state.index = 0;
  3733. } else {
  3734. var lineLen = state.lineText.length;
  3735. state.index = (lineLen > 0) ? (lineLen-1) : 0;
  3736. }
  3737. state.nextCh = state.lineText.charAt(state.index);
  3738. }
  3739. if (isComplete(state)) {
  3740. cur.line = line;
  3741. cur.ch = state.index;
  3742. repeat--;
  3743. }
  3744. }
  3745. if (state.nextCh || state.curMoveThrough) {
  3746. return Pos(line, state.index);
  3747. }
  3748. return cur;
  3749. }
  3750. function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {
  3751. var lineNum = cur.line;
  3752. var pos = cur.ch;
  3753. var line = cm.getLine(lineNum);
  3754. var dir = forward ? 1 : -1;
  3755. var charTests = bigWord ? bigWordCharTest: wordCharTest;
  3756. if (emptyLineIsWord && line == '') {
  3757. lineNum += dir;
  3758. line = cm.getLine(lineNum);
  3759. if (!isLine(cm, lineNum)) {
  3760. return null;
  3761. }
  3762. pos = (forward) ? 0 : line.length;
  3763. }
  3764. while (true) {
  3765. if (emptyLineIsWord && line == '') {
  3766. return { from: 0, to: 0, line: lineNum };
  3767. }
  3768. var stop = (dir > 0) ? line.length : -1;
  3769. var wordStart = stop, wordEnd = stop;
  3770. while (pos != stop) {
  3771. var foundWord = false;
  3772. for (var i = 0; i < charTests.length && !foundWord; ++i) {
  3773. if (charTests[i](line.charAt(pos))) {
  3774. wordStart = pos;
  3775. while (pos != stop && charTests[i](line.charAt(pos))) {
  3776. pos += dir;
  3777. }
  3778. wordEnd = pos;
  3779. foundWord = wordStart != wordEnd;
  3780. if (wordStart == cur.ch && lineNum == cur.line &&
  3781. wordEnd == wordStart + dir) {
  3782. continue;
  3783. } else {
  3784. return {
  3785. from: Math.min(wordStart, wordEnd + 1),
  3786. to: Math.max(wordStart, wordEnd),
  3787. line: lineNum };
  3788. }
  3789. }
  3790. }
  3791. if (!foundWord) {
  3792. pos += dir;
  3793. }
  3794. }
  3795. lineNum += dir;
  3796. if (!isLine(cm, lineNum)) {
  3797. return null;
  3798. }
  3799. line = cm.getLine(lineNum);
  3800. pos = (dir > 0) ? 0 : line.length;
  3801. }
  3802. }
  3803. function moveToWord(cm, cur, repeat, forward, wordEnd, bigWord) {
  3804. var curStart = copyCursor(cur);
  3805. var words = [];
  3806. if (forward && !wordEnd || !forward && wordEnd) {
  3807. repeat++;
  3808. }
  3809. var emptyLineIsWord = !(forward && wordEnd);
  3810. for (var i = 0; i < repeat; i++) {
  3811. var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord);
  3812. if (!word) {
  3813. var eodCh = lineLength(cm, cm.lastLine());
  3814. words.push(forward
  3815. ? {line: cm.lastLine(), from: eodCh, to: eodCh}
  3816. : {line: 0, from: 0, to: 0});
  3817. break;
  3818. }
  3819. words.push(word);
  3820. cur = Pos(word.line, forward ? (word.to - 1) : word.from);
  3821. }
  3822. var shortCircuit = words.length != repeat;
  3823. var firstWord = words[0];
  3824. var lastWord = words.pop();
  3825. if (forward && !wordEnd) {
  3826. if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) {
  3827. lastWord = words.pop();
  3828. }
  3829. return Pos(lastWord.line, lastWord.from);
  3830. } else if (forward && wordEnd) {
  3831. return Pos(lastWord.line, lastWord.to - 1);
  3832. } else if (!forward && wordEnd) {
  3833. if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) {
  3834. lastWord = words.pop();
  3835. }
  3836. return Pos(lastWord.line, lastWord.to);
  3837. } else {
  3838. return Pos(lastWord.line, lastWord.from);
  3839. }
  3840. }
  3841. function moveToCharacter(cm, repeat, forward, character) {
  3842. var cur = cm.getCursor();
  3843. var start = cur.ch;
  3844. var idx;
  3845. for (var i = 0; i < repeat; i ++) {
  3846. var line = cm.getLine(cur.line);
  3847. idx = charIdxInLine(start, line, character, forward, true);
  3848. if (idx == -1) {
  3849. return null;
  3850. }
  3851. start = idx;
  3852. }
  3853. return Pos(cm.getCursor().line, idx);
  3854. }
  3855. function moveToColumn(cm, repeat) {
  3856. var line = cm.getCursor().line;
  3857. return clipCursorToContent(cm, Pos(line, repeat - 1));
  3858. }
  3859. function updateMark(cm, vim, markName, pos) {
  3860. if (!inArray(markName, validMarks)) {
  3861. return;
  3862. }
  3863. if (vim.marks[markName]) {
  3864. vim.marks[markName].clear();
  3865. }
  3866. vim.marks[markName] = cm.setBookmark(pos);
  3867. }
  3868. function charIdxInLine(start, line, character, forward, includeChar) {
  3869. var idx;
  3870. if (forward) {
  3871. idx = line.indexOf(character, start + 1);
  3872. if (idx != -1 && !includeChar) {
  3873. idx -= 1;
  3874. }
  3875. } else {
  3876. idx = line.lastIndexOf(character, start - 1);
  3877. if (idx != -1 && !includeChar) {
  3878. idx += 1;
  3879. }
  3880. }
  3881. return idx;
  3882. }
  3883. function findParagraph(cm, head, repeat, dir, inclusive) {
  3884. var line = head.line;
  3885. var min = cm.firstLine();
  3886. var max = cm.lastLine();
  3887. var start, end, i = line;
  3888. function isEmpty(i) { return !/\S/.test(cm.getLine(i)); } // ace_patch
  3889. function isBoundary(i, dir, any) {
  3890. if (any) { return isEmpty(i) != isEmpty(i + dir); }
  3891. return !isEmpty(i) && isEmpty(i + dir);
  3892. }
  3893. function skipFold(i) {
  3894. dir = dir > 0 ? 1 : -1;
  3895. var foldLine = cm.ace.session.getFoldLine(i);
  3896. if (foldLine) {
  3897. if (i + dir > foldLine.start.row && i + dir < foldLine.end.row)
  3898. dir = (dir > 0 ? foldLine.end.row : foldLine.start.row) - i;
  3899. }
  3900. }
  3901. if (dir) {
  3902. while (min <= i && i <= max && repeat > 0) {
  3903. skipFold(i);
  3904. if (isBoundary(i, dir)) { repeat--; }
  3905. i += dir;
  3906. }
  3907. return new Pos(i, 0);
  3908. }
  3909. var vim = cm.state.vim;
  3910. if (vim.visualLine && isBoundary(line, 1, true)) {
  3911. var anchor = vim.sel.anchor;
  3912. if (isBoundary(anchor.line, -1, true)) {
  3913. if (!inclusive || anchor.line != line) {
  3914. line += 1;
  3915. }
  3916. }
  3917. }
  3918. var startState = isEmpty(line);
  3919. for (i = line; i <= max && repeat; i++) {
  3920. if (isBoundary(i, 1, true)) {
  3921. if (!inclusive || isEmpty(i) != startState) {
  3922. repeat--;
  3923. }
  3924. }
  3925. }
  3926. end = new Pos(i, 0);
  3927. if (i > max && !startState) { startState = true; }
  3928. else { inclusive = false; }
  3929. for (i = line; i > min; i--) {
  3930. if (!inclusive || isEmpty(i) == startState || i == line) {
  3931. if (isBoundary(i, -1, true)) { break; }
  3932. }
  3933. }
  3934. start = new Pos(i, 0);
  3935. return { start: start, end: end };
  3936. }
  3937. function findSentence(cm, cur, repeat, dir) {
  3938. function nextChar(cm, idx) {
  3939. if (idx.pos + idx.dir < 0 || idx.pos + idx.dir >= idx.line.length) {
  3940. idx.ln += idx.dir;
  3941. if (!isLine(cm, idx.ln)) {
  3942. idx.line = null;
  3943. idx.ln = null;
  3944. idx.pos = null;
  3945. return;
  3946. }
  3947. idx.line = cm.getLine(idx.ln);
  3948. idx.pos = (idx.dir > 0) ? 0 : idx.line.length - 1;
  3949. }
  3950. else {
  3951. idx.pos += idx.dir;
  3952. }
  3953. }
  3954. function forward(cm, ln, pos, dir) {
  3955. var line = cm.getLine(ln);
  3956. var stop = (line === "");
  3957. var curr = {
  3958. line: line,
  3959. ln: ln,
  3960. pos: pos,
  3961. dir: dir,
  3962. }
  3963. var last_valid = {
  3964. ln: curr.ln,
  3965. pos: curr.pos,
  3966. }
  3967. var skip_empty_lines = (curr.line === "");
  3968. nextChar(cm, curr);
  3969. while (curr.line !== null) {
  3970. last_valid.ln = curr.ln;
  3971. last_valid.pos = curr.pos;
  3972. if (curr.line === "" && !skip_empty_lines) {
  3973. return { ln: curr.ln, pos: curr.pos, };
  3974. }
  3975. else if (stop && curr.line !== "" && !isWhiteSpaceString(curr.line[curr.pos])) {
  3976. return { ln: curr.ln, pos: curr.pos, };
  3977. }
  3978. else if (isEndOfSentenceSymbol(curr.line[curr.pos])
  3979. && !stop
  3980. && (curr.pos === curr.line.length - 1
  3981. || isWhiteSpaceString(curr.line[curr.pos + 1]))) {
  3982. stop = true;
  3983. }
  3984. nextChar(cm, curr);
  3985. }
  3986. var line = cm.getLine(last_valid.ln);
  3987. last_valid.pos = 0;
  3988. for(var i = line.length - 1; i >= 0; --i) {
  3989. if (!isWhiteSpaceString(line[i])) {
  3990. last_valid.pos = i;
  3991. break;
  3992. }
  3993. }
  3994. return last_valid;
  3995. }
  3996. function reverse(cm, ln, pos, dir) {
  3997. var line = cm.getLine(ln);
  3998. var curr = {
  3999. line: line,
  4000. ln: ln,
  4001. pos: pos,
  4002. dir: dir,
  4003. }
  4004. var last_valid = {
  4005. ln: curr.ln,
  4006. pos: null,
  4007. };
  4008. var skip_empty_lines = (curr.line === "");
  4009. nextChar(cm, curr);
  4010. while (curr.line !== null) {
  4011. if (curr.line === "" && !skip_empty_lines) {
  4012. if (last_valid.pos !== null) {
  4013. return last_valid;
  4014. }
  4015. else {
  4016. return { ln: curr.ln, pos: curr.pos };
  4017. }
  4018. }
  4019. else if (isEndOfSentenceSymbol(curr.line[curr.pos])
  4020. && last_valid.pos !== null
  4021. && !(curr.ln === last_valid.ln && curr.pos + 1 === last_valid.pos)) {
  4022. return last_valid;
  4023. }
  4024. else if (curr.line !== "" && !isWhiteSpaceString(curr.line[curr.pos])) {
  4025. skip_empty_lines = false;
  4026. last_valid = { ln: curr.ln, pos: curr.pos }
  4027. }
  4028. nextChar(cm, curr);
  4029. }
  4030. var line = cm.getLine(last_valid.ln);
  4031. last_valid.pos = 0;
  4032. for(var i = 0; i < line.length; ++i) {
  4033. if (!isWhiteSpaceString(line[i])) {
  4034. last_valid.pos = i;
  4035. break;
  4036. }
  4037. }
  4038. return last_valid;
  4039. }
  4040. var curr_index = {
  4041. ln: cur.line,
  4042. pos: cur.ch,
  4043. };
  4044. while (repeat > 0) {
  4045. if (dir < 0) {
  4046. curr_index = reverse(cm, curr_index.ln, curr_index.pos, dir);
  4047. }
  4048. else {
  4049. curr_index = forward(cm, curr_index.ln, curr_index.pos, dir);
  4050. }
  4051. repeat--;
  4052. }
  4053. return Pos(curr_index.ln, curr_index.pos);
  4054. }
  4055. function selectCompanionObject(cm, head, symb, inclusive) {
  4056. var cur = head, start, end;
  4057. var bracketRegexp = ({
  4058. '(': /[()]/, ')': /[()]/,
  4059. '[': /[[\]]/, ']': /[[\]]/,
  4060. '{': /[{}]/, '}': /[{}]/,
  4061. '<': /[<>]/, '>': /[<>]/})[symb];
  4062. var openSym = ({
  4063. '(': '(', ')': '(',
  4064. '[': '[', ']': '[',
  4065. '{': '{', '}': '{',
  4066. '<': '<', '>': '<'})[symb];
  4067. var curChar = cm.getLine(cur.line).charAt(cur.ch);
  4068. var offset = curChar === openSym ? 1 : 0;
  4069. start = cm.scanForBracket(Pos(cur.line, cur.ch + offset), -1, undefined, {'bracketRegex': bracketRegexp});
  4070. end = cm.scanForBracket(Pos(cur.line, cur.ch + offset), 1, undefined, {'bracketRegex': bracketRegexp});
  4071. if (!start || !end) {
  4072. return { start: cur, end: cur };
  4073. }
  4074. start = start.pos;
  4075. end = end.pos;
  4076. if ((start.line == end.line && start.ch > end.ch)
  4077. || (start.line > end.line)) {
  4078. var tmp = start;
  4079. start = end;
  4080. end = tmp;
  4081. }
  4082. if (inclusive) {
  4083. end.ch += 1;
  4084. } else {
  4085. start.ch += 1;
  4086. }
  4087. return { start: start, end: end };
  4088. }
  4089. function findBeginningAndEnd(cm, head, symb, inclusive) {
  4090. var cur = copyCursor(head);
  4091. var line = cm.getLine(cur.line);
  4092. var chars = line.split('');
  4093. var start, end, i, len;
  4094. var firstIndex = chars.indexOf(symb);
  4095. if (cur.ch < firstIndex) {
  4096. cur.ch = firstIndex;
  4097. }
  4098. else if (firstIndex < cur.ch && chars[cur.ch] == symb) {
  4099. end = cur.ch; // assign end to the current cursor
  4100. --cur.ch; // make sure to look backwards
  4101. }
  4102. if (chars[cur.ch] == symb && !end) {
  4103. start = cur.ch + 1; // assign start to ahead of the cursor
  4104. } else {
  4105. for (i = cur.ch; i > -1 && !start; i--) {
  4106. if (chars[i] == symb) {
  4107. start = i + 1;
  4108. }
  4109. }
  4110. }
  4111. if (start && !end) {
  4112. for (i = start, len = chars.length; i < len && !end; i++) {
  4113. if (chars[i] == symb) {
  4114. end = i;
  4115. }
  4116. }
  4117. }
  4118. if (!start || !end) {
  4119. return { start: cur, end: cur };
  4120. }
  4121. if (inclusive) {
  4122. --start; ++end;
  4123. }
  4124. return {
  4125. start: Pos(cur.line, start),
  4126. end: Pos(cur.line, end)
  4127. };
  4128. }
  4129. defineOption('pcre', true, 'boolean');
  4130. function SearchState() {}
  4131. SearchState.prototype = {
  4132. getQuery: function() {
  4133. return vimGlobalState.query;
  4134. },
  4135. setQuery: function(query) {
  4136. vimGlobalState.query = query;
  4137. },
  4138. getOverlay: function() {
  4139. return this.searchOverlay;
  4140. },
  4141. setOverlay: function(overlay) {
  4142. this.searchOverlay = overlay;
  4143. },
  4144. isReversed: function() {
  4145. return vimGlobalState.isReversed;
  4146. },
  4147. setReversed: function(reversed) {
  4148. vimGlobalState.isReversed = reversed;
  4149. },
  4150. getScrollbarAnnotate: function() {
  4151. return this.annotate;
  4152. },
  4153. setScrollbarAnnotate: function(annotate) {
  4154. this.annotate = annotate;
  4155. }
  4156. };
  4157. function getSearchState(cm) {
  4158. var vim = cm.state.vim;
  4159. return vim.searchState_ || (vim.searchState_ = new SearchState());
  4160. }
  4161. function dialog(cm, template, shortText, onClose, options) {
  4162. if (cm.openDialog) {
  4163. cm.openDialog(template, onClose, { bottom: true, value: options.value,
  4164. onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp,
  4165. selectValueOnOpen: false, onClose: function() {
  4166. if (cm.state.vim) {
  4167. cm.state.vim.status = "";
  4168. cm.ace.renderer.$loop.schedule(cm.ace.renderer.CHANGE_CURSOR);
  4169. }
  4170. }});
  4171. }
  4172. else {
  4173. onClose(prompt(shortText, ''));
  4174. }
  4175. }
  4176. function splitBySlash(argString) {
  4177. return splitBySeparator(argString, '/');
  4178. }
  4179. function findUnescapedSlashes(argString) {
  4180. return findUnescapedSeparators(argString, '/');
  4181. }
  4182. function splitBySeparator(argString, separator) {
  4183. var slashes = findUnescapedSeparators(argString, separator) || [];
  4184. if (!slashes.length) return [];
  4185. var tokens = [];
  4186. if (slashes[0] !== 0) return;
  4187. for (var i = 0; i < slashes.length; i++) {
  4188. if (typeof slashes[i] == 'number')
  4189. tokens.push(argString.substring(slashes[i] + 1, slashes[i+1]));
  4190. }
  4191. return tokens;
  4192. }
  4193. function findUnescapedSeparators(str, separator) {
  4194. if (!separator)
  4195. separator = '/';
  4196. var escapeNextChar = false;
  4197. var slashes = [];
  4198. for (var i = 0; i < str.length; i++) {
  4199. var c = str.charAt(i);
  4200. if (!escapeNextChar && c == separator) {
  4201. slashes.push(i);
  4202. }
  4203. escapeNextChar = !escapeNextChar && (c == '\\');
  4204. }
  4205. return slashes;
  4206. }
  4207. function translateRegex(str) {
  4208. var specials = '|(){';
  4209. var unescape = '}';
  4210. var escapeNextChar = false;
  4211. var out = [];
  4212. for (var i = -1; i < str.length; i++) {
  4213. var c = str.charAt(i) || '';
  4214. var n = str.charAt(i+1) || '';
  4215. var specialComesNext = (n && specials.indexOf(n) != -1);
  4216. if (escapeNextChar) {
  4217. if (c !== '\\' || !specialComesNext) {
  4218. out.push(c);
  4219. }
  4220. escapeNextChar = false;
  4221. } else {
  4222. if (c === '\\') {
  4223. escapeNextChar = true;
  4224. if (n && unescape.indexOf(n) != -1) {
  4225. specialComesNext = true;
  4226. }
  4227. if (!specialComesNext || n === '\\') {
  4228. out.push(c);
  4229. }
  4230. } else {
  4231. out.push(c);
  4232. if (specialComesNext && n !== '\\') {
  4233. out.push('\\');
  4234. }
  4235. }
  4236. }
  4237. }
  4238. return out.join('');
  4239. }
  4240. var charUnescapes = {'\\n': '\n', '\\r': '\r', '\\t': '\t'};
  4241. function translateRegexReplace(str) {
  4242. var escapeNextChar = false;
  4243. var out = [];
  4244. for (var i = -1; i < str.length; i++) {
  4245. var c = str.charAt(i) || '';
  4246. var n = str.charAt(i+1) || '';
  4247. if (charUnescapes[c + n]) {
  4248. out.push(charUnescapes[c+n]);
  4249. i++;
  4250. } else if (escapeNextChar) {
  4251. out.push(c);
  4252. escapeNextChar = false;
  4253. } else {
  4254. if (c === '\\') {
  4255. escapeNextChar = true;
  4256. if ((isNumber(n) || n === '$')) {
  4257. out.push('$');
  4258. } else if (n !== '/' && n !== '\\') {
  4259. out.push('\\');
  4260. }
  4261. } else {
  4262. if (c === '$') {
  4263. out.push('$');
  4264. }
  4265. out.push(c);
  4266. if (n === '/') {
  4267. out.push('\\');
  4268. }
  4269. }
  4270. }
  4271. }
  4272. return out.join('');
  4273. }
  4274. var unescapes = {'\\/': '/', '\\\\': '\\', '\\n': '\n', '\\r': '\r', '\\t': '\t'};
  4275. function unescapeRegexReplace(str) {
  4276. var stream = new CodeMirror.StringStream(str);
  4277. var output = [];
  4278. while (!stream.eol()) {
  4279. while (stream.peek() && stream.peek() != '\\') {
  4280. output.push(stream.next());
  4281. }
  4282. var matched = false;
  4283. for (var matcher in unescapes) {
  4284. if (stream.match(matcher, true)) {
  4285. matched = true;
  4286. output.push(unescapes[matcher]);
  4287. break;
  4288. }
  4289. }
  4290. if (!matched) {
  4291. output.push(stream.next());
  4292. }
  4293. }
  4294. return output.join('');
  4295. }
  4296. function parseQuery(query, ignoreCase, smartCase) {
  4297. var lastSearchRegister = vimGlobalState.registerController.getRegister('/');
  4298. lastSearchRegister.setText(query);
  4299. if (query instanceof RegExp) { return query; }
  4300. var slashes = findUnescapedSlashes(query);
  4301. var regexPart;
  4302. var forceIgnoreCase;
  4303. if (!slashes.length) {
  4304. regexPart = query;
  4305. } else {
  4306. regexPart = query.substring(0, slashes[0]);
  4307. var flagsPart = query.substring(slashes[0]);
  4308. forceIgnoreCase = (flagsPart.indexOf('i') != -1);
  4309. }
  4310. if (!regexPart) {
  4311. return null;
  4312. }
  4313. if (!getOption('pcre')) {
  4314. regexPart = translateRegex(regexPart);
  4315. }
  4316. if (smartCase) {
  4317. ignoreCase = (/^[^A-Z]*$/).test(regexPart);
  4318. }
  4319. var regexp = new RegExp(regexPart,
  4320. (ignoreCase || forceIgnoreCase) ? 'i' : undefined);
  4321. return regexp;
  4322. }
  4323. function showConfirm(cm, text) {
  4324. if (cm.openNotification) {
  4325. cm.openNotification('<span style="color: red">' + text + '</span>',
  4326. {bottom: true, duration: 5000});
  4327. } else {
  4328. alert(text);
  4329. }
  4330. }
  4331. function makePrompt(prefix, desc) {
  4332. var raw = '<span style="font-family: monospace; white-space: pre">' +
  4333. (prefix || "") + '<input type="text" autocorrect="off" autocapitalize="none" autocomplete="off"></span>';
  4334. if (desc)
  4335. raw += ' <span style="color: #888">' + desc + '</span>';
  4336. return raw;
  4337. }
  4338. var searchPromptDesc = '(Javascript regexp)';
  4339. function showPrompt(cm, options) {
  4340. var shortText = (options.prefix || '') + ' ' + (options.desc || '');
  4341. var prompt = makePrompt(options.prefix, options.desc);
  4342. dialog(cm, prompt, shortText, options.onClose, options);
  4343. }
  4344. function regexEqual(r1, r2) {
  4345. if (r1 instanceof RegExp && r2 instanceof RegExp) {
  4346. var props = ['global', 'multiline', 'ignoreCase', 'source'];
  4347. for (var i = 0; i < props.length; i++) {
  4348. var prop = props[i];
  4349. if (r1[prop] !== r2[prop]) {
  4350. return false;
  4351. }
  4352. }
  4353. return true;
  4354. }
  4355. return false;
  4356. }
  4357. function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {
  4358. if (!rawQuery) {
  4359. return;
  4360. }
  4361. var state = getSearchState(cm);
  4362. var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase);
  4363. if (!query) {
  4364. return;
  4365. }
  4366. highlightSearchMatches(cm, query);
  4367. if (regexEqual(query, state.getQuery())) {
  4368. return query;
  4369. }
  4370. state.setQuery(query);
  4371. return query;
  4372. }
  4373. function searchOverlay(query) {
  4374. if (query.source.charAt(0) == '^') {
  4375. var matchSol = true;
  4376. }
  4377. return {
  4378. token: function(stream) {
  4379. if (matchSol && !stream.sol()) {
  4380. stream.skipToEnd();
  4381. return;
  4382. }
  4383. var match = stream.match(query, false);
  4384. if (match) {
  4385. if (match[0].length == 0) {
  4386. stream.next();
  4387. return 'searching';
  4388. }
  4389. if (!stream.sol()) {
  4390. stream.backUp(1);
  4391. if (!query.exec(stream.next() + match[0])) {
  4392. stream.next();
  4393. return null;
  4394. }
  4395. }
  4396. stream.match(query);
  4397. return 'searching';
  4398. }
  4399. while (!stream.eol()) {
  4400. stream.next();
  4401. if (stream.match(query, false)) break;
  4402. }
  4403. },
  4404. query: query
  4405. };
  4406. }
  4407. function highlightSearchMatches(cm, query) {
  4408. var searchState = getSearchState(cm);
  4409. var overlay = searchState.getOverlay();
  4410. if (!overlay || query != overlay.query) {
  4411. if (overlay) {
  4412. cm.removeOverlay(overlay);
  4413. }
  4414. overlay = searchOverlay(query);
  4415. cm.addOverlay(overlay);
  4416. if (cm.showMatchesOnScrollbar) {
  4417. if (searchState.getScrollbarAnnotate()) {
  4418. searchState.getScrollbarAnnotate().clear();
  4419. }
  4420. searchState.setScrollbarAnnotate(cm.showMatchesOnScrollbar(query));
  4421. }
  4422. searchState.setOverlay(overlay);
  4423. }
  4424. }
  4425. function findNext(cm, prev, query, repeat) {
  4426. if (repeat === undefined) { repeat = 1; }
  4427. return cm.operation(function() {
  4428. var pos = cm.getCursor();
  4429. var cursor = cm.getSearchCursor(query, pos);
  4430. for (var i = 0; i < repeat; i++) {
  4431. var found = cursor.find(prev);
  4432. if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); }
  4433. if (!found) {
  4434. cursor = cm.getSearchCursor(query,
  4435. (prev) ? Pos(cm.lastLine()) : Pos(cm.firstLine(), 0) );
  4436. if (!cursor.find(prev)) {
  4437. return;
  4438. }
  4439. }
  4440. }
  4441. return cursor.from();
  4442. });
  4443. }
  4444. function clearSearchHighlight(cm) {
  4445. var state = getSearchState(cm);
  4446. cm.removeOverlay(getSearchState(cm).getOverlay());
  4447. state.setOverlay(null);
  4448. if (state.getScrollbarAnnotate()) {
  4449. state.getScrollbarAnnotate().clear();
  4450. state.setScrollbarAnnotate(null);
  4451. }
  4452. }
  4453. function isInRange(pos, start, end) {
  4454. if (typeof pos != 'number') {
  4455. pos = pos.line;
  4456. }
  4457. if (start instanceof Array) {
  4458. return inArray(pos, start);
  4459. } else {
  4460. if (end) {
  4461. return (pos >= start && pos <= end);
  4462. } else {
  4463. return pos == start;
  4464. }
  4465. }
  4466. }
  4467. function getUserVisibleLines(cm) {
  4468. var renderer = cm.ace.renderer;
  4469. return {
  4470. top: renderer.getFirstFullyVisibleRow(),
  4471. bottom: renderer.getLastFullyVisibleRow()
  4472. }
  4473. }
  4474. function getMarkPos(cm, vim, markName) {
  4475. if (markName == '\'' || markName == '`') {
  4476. return vimGlobalState.jumpList.find(cm, -1) || Pos(0, 0);
  4477. } else if (markName == '.') {
  4478. return getLastEditPos(cm);
  4479. }
  4480. var mark = vim.marks[markName];
  4481. return mark && mark.find();
  4482. }
  4483. function getLastEditPos(cm) {
  4484. var undoManager = cm.ace.session.$undoManager;
  4485. if (undoManager && undoManager.$lastDelta)
  4486. return toCmPos(undoManager.$lastDelta.end);
  4487. }
  4488. var ExCommandDispatcher = function() {
  4489. this.buildCommandMap_();
  4490. };
  4491. ExCommandDispatcher.prototype = {
  4492. processCommand: function(cm, input, opt_params) {
  4493. var that = this;
  4494. cm.operation(function () {
  4495. cm.curOp.isVimOp = true;
  4496. that._processCommand(cm, input, opt_params);
  4497. });
  4498. },
  4499. _processCommand: function(cm, input, opt_params) {
  4500. var vim = cm.state.vim;
  4501. var commandHistoryRegister = vimGlobalState.registerController.getRegister(':');
  4502. var previousCommand = commandHistoryRegister.toString();
  4503. if (vim.visualMode) {
  4504. exitVisualMode(cm);
  4505. }
  4506. var inputStream = new CodeMirror.StringStream(input);
  4507. commandHistoryRegister.setText(input);
  4508. var params = opt_params || {};
  4509. params.input = input;
  4510. try {
  4511. this.parseInput_(cm, inputStream, params);
  4512. } catch(e) {
  4513. showConfirm(cm, e);
  4514. throw e;
  4515. }
  4516. var command;
  4517. var commandName;
  4518. if (!params.commandName) {
  4519. if (params.line !== undefined) {
  4520. commandName = 'move';
  4521. }
  4522. } else {
  4523. command = this.matchCommand_(params.commandName);
  4524. if (command) {
  4525. commandName = command.name;
  4526. if (command.excludeFromCommandHistory) {
  4527. commandHistoryRegister.setText(previousCommand);
  4528. }
  4529. this.parseCommandArgs_(inputStream, params, command);
  4530. if (command.type == 'exToKey') {
  4531. for (var i = 0; i < command.toKeys.length; i++) {
  4532. CodeMirror.Vim.handleKey(cm, command.toKeys[i], 'mapping');
  4533. }
  4534. return;
  4535. } else if (command.type == 'exToEx') {
  4536. this.processCommand(cm, command.toInput);
  4537. return;
  4538. }
  4539. }
  4540. }
  4541. if (!commandName) {
  4542. showConfirm(cm, 'Not an editor command ":' + input + '"');
  4543. return;
  4544. }
  4545. try {
  4546. exCommands[commandName](cm, params);
  4547. if ((!command || !command.possiblyAsync) && params.callback) {
  4548. params.callback();
  4549. }
  4550. } catch(e) {
  4551. showConfirm(cm, e);
  4552. throw e;
  4553. }
  4554. },
  4555. parseInput_: function(cm, inputStream, result) {
  4556. inputStream.eatWhile(':');
  4557. if (inputStream.eat('%')) {
  4558. result.line = cm.firstLine();
  4559. result.lineEnd = cm.lastLine();
  4560. } else {
  4561. result.line = this.parseLineSpec_(cm, inputStream);
  4562. if (result.line !== undefined && inputStream.eat(',')) {
  4563. result.lineEnd = this.parseLineSpec_(cm, inputStream);
  4564. }
  4565. }
  4566. var commandMatch = inputStream.match(/^(\w+)/);
  4567. if (commandMatch) {
  4568. result.commandName = commandMatch[1];
  4569. } else {
  4570. result.commandName = inputStream.match(/.*/)[0];
  4571. }
  4572. return result;
  4573. },
  4574. parseLineSpec_: function(cm, inputStream) {
  4575. var numberMatch = inputStream.match(/^(\d+)/);
  4576. if (numberMatch) {
  4577. return parseInt(numberMatch[1], 10) - 1;
  4578. }
  4579. switch (inputStream.next()) {
  4580. case '.':
  4581. return this.parseLineSpecOffset_(inputStream, cm.getCursor().line);
  4582. case '$':
  4583. return this.parseLineSpecOffset_(inputStream, cm.lastLine());
  4584. case '\'':
  4585. var markName = inputStream.next();
  4586. var markPos = getMarkPos(cm, cm.state.vim, markName);
  4587. if (!markPos) throw new Error('Mark not set');
  4588. return this.parseLineSpecOffset_(inputStream, markPos.line);
  4589. case '-':
  4590. case '+':
  4591. inputStream.backUp(1);
  4592. return this.parseLineSpecOffset_(inputStream, cm.getCursor().line);
  4593. default:
  4594. inputStream.backUp(1);
  4595. return undefined;
  4596. }
  4597. },
  4598. parseLineSpecOffset_: function(inputStream, line) {
  4599. var offsetMatch = inputStream.match(/^([+-])?(\d+)/);
  4600. if (offsetMatch) {
  4601. var offset = parseInt(offsetMatch[2], 10);
  4602. if (offsetMatch[1] == "-") {
  4603. line -= offset;
  4604. } else {
  4605. line += offset;
  4606. }
  4607. }
  4608. return line;
  4609. },
  4610. parseCommandArgs_: function(inputStream, params, command) {
  4611. if (inputStream.eol()) {
  4612. return;
  4613. }
  4614. params.argString = inputStream.match(/.*/)[0];
  4615. var delim = command.argDelimiter || /\s+/;
  4616. var args = trim(params.argString).split(delim);
  4617. if (args.length && args[0]) {
  4618. params.args = args;
  4619. }
  4620. },
  4621. matchCommand_: function(commandName) {
  4622. for (var i = commandName.length; i > 0; i--) {
  4623. var prefix = commandName.substring(0, i);
  4624. if (this.commandMap_[prefix]) {
  4625. var command = this.commandMap_[prefix];
  4626. if (command.name.indexOf(commandName) === 0) {
  4627. return command;
  4628. }
  4629. }
  4630. }
  4631. return null;
  4632. },
  4633. buildCommandMap_: function() {
  4634. this.commandMap_ = {};
  4635. for (var i = 0; i < defaultExCommandMap.length; i++) {
  4636. var command = defaultExCommandMap[i];
  4637. var key = command.shortName || command.name;
  4638. this.commandMap_[key] = command;
  4639. }
  4640. },
  4641. map: function(lhs, rhs, ctx) {
  4642. if (lhs != ':' && lhs.charAt(0) == ':') {
  4643. if (ctx) { throw Error('Mode not supported for ex mappings'); }
  4644. var commandName = lhs.substring(1);
  4645. if (rhs != ':' && rhs.charAt(0) == ':') {
  4646. this.commandMap_[commandName] = {
  4647. name: commandName,
  4648. type: 'exToEx',
  4649. toInput: rhs.substring(1),
  4650. user: true
  4651. };
  4652. } else {
  4653. this.commandMap_[commandName] = {
  4654. name: commandName,
  4655. type: 'exToKey',
  4656. toKeys: rhs,
  4657. user: true
  4658. };
  4659. }
  4660. } else {
  4661. if (rhs != ':' && rhs.charAt(0) == ':') {
  4662. var mapping = {
  4663. keys: lhs,
  4664. type: 'keyToEx',
  4665. exArgs: { input: rhs.substring(1) }
  4666. };
  4667. if (ctx) { mapping.context = ctx; }
  4668. defaultKeymap.unshift(mapping);
  4669. } else {
  4670. var mapping = {
  4671. keys: lhs,
  4672. type: 'keyToKey',
  4673. toKeys: rhs
  4674. };
  4675. if (ctx) { mapping.context = ctx; }
  4676. defaultKeymap.unshift(mapping);
  4677. }
  4678. }
  4679. },
  4680. unmap: function(lhs, ctx) {
  4681. if (lhs != ':' && lhs.charAt(0) == ':') {
  4682. if (ctx) { throw Error('Mode not supported for ex mappings'); }
  4683. var commandName = lhs.substring(1);
  4684. if (this.commandMap_[commandName] && this.commandMap_[commandName].user) {
  4685. delete this.commandMap_[commandName];
  4686. return;
  4687. }
  4688. } else {
  4689. var keys = lhs;
  4690. for (var i = 0; i < defaultKeymap.length; i++) {
  4691. if (keys == defaultKeymap[i].keys
  4692. && defaultKeymap[i].context === ctx) {
  4693. defaultKeymap.splice(i, 1);
  4694. return;
  4695. }
  4696. }
  4697. }
  4698. }
  4699. };
  4700. var exCommands = {
  4701. colorscheme: function(cm, params) {
  4702. if (!params.args || params.args.length < 1) {
  4703. showConfirm(cm, cm.getOption('theme'));
  4704. return;
  4705. }
  4706. cm.setOption('theme', params.args[0]);
  4707. },
  4708. map: function(cm, params, ctx) {
  4709. var mapArgs = params.args;
  4710. if (!mapArgs || mapArgs.length < 2) {
  4711. if (cm) {
  4712. showConfirm(cm, 'Invalid mapping: ' + params.input);
  4713. }
  4714. return;
  4715. }
  4716. exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx);
  4717. },
  4718. imap: function(cm, params) { this.map(cm, params, 'insert'); },
  4719. nmap: function(cm, params) { this.map(cm, params, 'normal'); },
  4720. vmap: function(cm, params) { this.map(cm, params, 'visual'); },
  4721. unmap: function(cm, params, ctx) {
  4722. var mapArgs = params.args;
  4723. if (!mapArgs || mapArgs.length < 1) {
  4724. if (cm) {
  4725. showConfirm(cm, 'No such mapping: ' + params.input);
  4726. }
  4727. return;
  4728. }
  4729. exCommandDispatcher.unmap(mapArgs[0], ctx);
  4730. },
  4731. move: function(cm, params) {
  4732. commandDispatcher.processCommand(cm, cm.state.vim, {
  4733. type: 'motion',
  4734. motion: 'moveToLineOrEdgeOfDocument',
  4735. motionArgs: { forward: false, explicitRepeat: true,
  4736. linewise: true },
  4737. repeatOverride: params.line+1});
  4738. },
  4739. set: function(cm, params) {
  4740. var setArgs = params.args;
  4741. var setCfg = params.setCfg || {};
  4742. if (!setArgs || setArgs.length < 1) {
  4743. if (cm) {
  4744. showConfirm(cm, 'Invalid mapping: ' + params.input);
  4745. }
  4746. return;
  4747. }
  4748. var expr = setArgs[0].split('=');
  4749. var optionName = expr[0];
  4750. var value = expr[1];
  4751. var forceGet = false;
  4752. if (optionName.charAt(optionName.length - 1) == '?') {
  4753. if (value) { throw Error('Trailing characters: ' + params.argString); }
  4754. optionName = optionName.substring(0, optionName.length - 1);
  4755. forceGet = true;
  4756. }
  4757. if (value === undefined && optionName.substring(0, 2) == 'no') {
  4758. optionName = optionName.substring(2);
  4759. value = false;
  4760. }
  4761. var optionIsBoolean = options[optionName] && options[optionName].type == 'boolean';
  4762. if (optionIsBoolean && value == undefined) {
  4763. value = true;
  4764. }
  4765. if (!optionIsBoolean && value === undefined || forceGet) {
  4766. var oldValue = getOption(optionName, cm, setCfg);
  4767. if (oldValue instanceof Error) {
  4768. showConfirm(cm, oldValue.message);
  4769. } else if (oldValue === true || oldValue === false) {
  4770. showConfirm(cm, ' ' + (oldValue ? '' : 'no') + optionName);
  4771. } else {
  4772. showConfirm(cm, ' ' + optionName + '=' + oldValue);
  4773. }
  4774. } else {
  4775. var setOptionReturn = setOption(optionName, value, cm, setCfg);
  4776. if (setOptionReturn instanceof Error) {
  4777. showConfirm(cm, setOptionReturn.message);
  4778. }
  4779. }
  4780. },
  4781. setlocal: function (cm, params) {
  4782. params.setCfg = {scope: 'local'};
  4783. this.set(cm, params);
  4784. },
  4785. setglobal: function (cm, params) {
  4786. params.setCfg = {scope: 'global'};
  4787. this.set(cm, params);
  4788. },
  4789. registers: function(cm, params) {
  4790. var regArgs = params.args;
  4791. var registers = vimGlobalState.registerController.registers;
  4792. var regInfo = '----------Registers----------<br><br>';
  4793. if (!regArgs) {
  4794. for (var registerName in registers) {
  4795. var text = registers[registerName].toString();
  4796. if (text.length) {
  4797. regInfo += '"' + registerName + ' ' + text + '<br>';
  4798. }
  4799. }
  4800. } else {
  4801. var registerName;
  4802. regArgs = regArgs.join('');
  4803. for (var i = 0; i < regArgs.length; i++) {
  4804. registerName = regArgs.charAt(i);
  4805. if (!vimGlobalState.registerController.isValidRegister(registerName)) {
  4806. continue;
  4807. }
  4808. var register = registers[registerName] || new Register();
  4809. regInfo += '"' + registerName + ' ' + register.toString() + '<br>';
  4810. }
  4811. }
  4812. showConfirm(cm, regInfo);
  4813. },
  4814. sort: function(cm, params) {
  4815. var reverse, ignoreCase, unique, number, pattern;
  4816. function parseArgs() {
  4817. if (params.argString) {
  4818. var args = new CodeMirror.StringStream(params.argString);
  4819. if (args.eat('!')) { reverse = true; }
  4820. if (args.eol()) { return; }
  4821. if (!args.eatSpace()) { return 'Invalid arguments'; }
  4822. var opts = args.match(/([dinuox]+)?\s*(\/.+\/)?\s*/);
  4823. if (!opts && !args.eol()) { return 'Invalid arguments'; }
  4824. if (opts[1]) {
  4825. ignoreCase = opts[1].indexOf('i') != -1;
  4826. unique = opts[1].indexOf('u') != -1;
  4827. var decimal = opts[1].indexOf('d') != -1 || opts[1].indexOf('n') != -1 && 1;
  4828. var hex = opts[1].indexOf('x') != -1 && 1;
  4829. var octal = opts[1].indexOf('o') != -1 && 1;
  4830. if (decimal + hex + octal > 1) { return 'Invalid arguments'; }
  4831. number = decimal && 'decimal' || hex && 'hex' || octal && 'octal';
  4832. }
  4833. if (opts[2]) {
  4834. pattern = new RegExp(opts[2].substr(1, opts[2].length - 2), ignoreCase ? 'i' : '');
  4835. }
  4836. }
  4837. }
  4838. var err = parseArgs();
  4839. if (err) {
  4840. showConfirm(cm, err + ': ' + params.argString);
  4841. return;
  4842. }
  4843. var lineStart = params.line || cm.firstLine();
  4844. var lineEnd = params.lineEnd || params.line || cm.lastLine();
  4845. if (lineStart == lineEnd) { return; }
  4846. var curStart = Pos(lineStart, 0);
  4847. var curEnd = Pos(lineEnd, lineLength(cm, lineEnd));
  4848. var text = cm.getRange(curStart, curEnd).split('\n');
  4849. var numberRegex = pattern ? pattern :
  4850. (number == 'decimal') ? /(-?)([\d]+)/ :
  4851. (number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i :
  4852. (number == 'octal') ? /([0-7]+)/ : null;
  4853. var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null;
  4854. var numPart = [], textPart = [];
  4855. if (number || pattern) {
  4856. for (var i = 0; i < text.length; i++) {
  4857. var matchPart = pattern ? text[i].match(pattern) : null;
  4858. if (matchPart && matchPart[0] != '') {
  4859. numPart.push(matchPart);
  4860. } else if (!pattern && numberRegex.exec(text[i])) {
  4861. numPart.push(text[i]);
  4862. } else {
  4863. textPart.push(text[i]);
  4864. }
  4865. }
  4866. } else {
  4867. textPart = text;
  4868. }
  4869. function compareFn(a, b) {
  4870. if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
  4871. if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); }
  4872. var anum = number && numberRegex.exec(a);
  4873. var bnum = number && numberRegex.exec(b);
  4874. if (!anum) { return a < b ? -1 : 1; }
  4875. anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix);
  4876. bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix);
  4877. return anum - bnum;
  4878. }
  4879. function comparePatternFn(a, b) {
  4880. if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
  4881. if (ignoreCase) { a[0] = a[0].toLowerCase(); b[0] = b[0].toLowerCase(); }
  4882. return (a[0] < b[0]) ? -1 : 1;
  4883. }
  4884. numPart.sort(pattern ? comparePatternFn : compareFn);
  4885. if (pattern) {
  4886. for (var i = 0; i < numPart.length; i++) {
  4887. numPart[i] = numPart[i].input;
  4888. }
  4889. } else if (!number) { textPart.sort(compareFn); }
  4890. text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart);
  4891. if (unique) { // Remove duplicate lines
  4892. var textOld = text;
  4893. var lastLine;
  4894. text = [];
  4895. for (var i = 0; i < textOld.length; i++) {
  4896. if (textOld[i] != lastLine) {
  4897. text.push(textOld[i]);
  4898. }
  4899. lastLine = textOld[i];
  4900. }
  4901. }
  4902. cm.replaceRange(text.join('\n'), curStart, curEnd);
  4903. },
  4904. global: function(cm, params) {
  4905. var argString = params.argString;
  4906. if (!argString) {
  4907. showConfirm(cm, 'Regular Expression missing from global');
  4908. return;
  4909. }
  4910. var lineStart = (params.line !== undefined) ? params.line : cm.firstLine();
  4911. var lineEnd = params.lineEnd || params.line || cm.lastLine();
  4912. var tokens = splitBySlash(argString);
  4913. var regexPart = argString, cmd;
  4914. if (tokens.length) {
  4915. regexPart = tokens[0];
  4916. cmd = tokens.slice(1, tokens.length).join('/');
  4917. }
  4918. if (regexPart) {
  4919. try {
  4920. updateSearchQuery(cm, regexPart, true /** ignoreCase */,
  4921. true /** smartCase */);
  4922. } catch (e) {
  4923. showConfirm(cm, 'Invalid regex: ' + regexPart);
  4924. return;
  4925. }
  4926. }
  4927. var query = getSearchState(cm).getQuery();
  4928. var matchedLines = [], content = '';
  4929. for (var i = lineStart; i <= lineEnd; i++) {
  4930. var matched = query.test(cm.getLine(i));
  4931. if (matched) {
  4932. matchedLines.push(i+1);
  4933. content+= cm.getLine(i) + '<br>';
  4934. }
  4935. }
  4936. if (!cmd) {
  4937. showConfirm(cm, content);
  4938. return;
  4939. }
  4940. var index = 0;
  4941. var nextCommand = function() {
  4942. if (index < matchedLines.length) {
  4943. var command = matchedLines[index] + cmd;
  4944. exCommandDispatcher.processCommand(cm, command, {
  4945. callback: nextCommand
  4946. });
  4947. }
  4948. index++;
  4949. };
  4950. nextCommand();
  4951. },
  4952. substitute: function(cm, params) {
  4953. if (!cm.getSearchCursor) {
  4954. throw new Error('Search feature not available. Requires searchcursor.js or ' +
  4955. 'any other getSearchCursor implementation.');
  4956. }
  4957. var argString = params.argString;
  4958. var tokens = argString ? splitBySeparator(argString, argString[0]) : [];
  4959. var regexPart, replacePart = '', trailing, flagsPart, count;
  4960. var confirm = false; // Whether to confirm each replace.
  4961. var global = false; // True to replace all instances on a line, false to replace only 1.
  4962. if (tokens.length) {
  4963. regexPart = tokens[0];
  4964. if (getOption('pcre') && regexPart !== '') {
  4965. regexPart = new RegExp(regexPart).source; //normalize not escaped characters
  4966. }
  4967. replacePart = tokens[1];
  4968. if (regexPart && regexPart[regexPart.length - 1] === '$') {
  4969. regexPart = regexPart.slice(0, regexPart.length - 1) + '\\n';
  4970. replacePart = replacePart ? replacePart + '\n' : '\n';
  4971. }
  4972. if (replacePart !== undefined) {
  4973. if (getOption('pcre')) {
  4974. replacePart = unescapeRegexReplace(replacePart.replace(/([^\\])&/g,"$1$$&"));
  4975. } else {
  4976. replacePart = translateRegexReplace(replacePart);
  4977. }
  4978. vimGlobalState.lastSubstituteReplacePart = replacePart;
  4979. }
  4980. trailing = tokens[2] ? tokens[2].split(' ') : [];
  4981. } else {
  4982. if (argString && argString.length) {
  4983. showConfirm(cm, 'Substitutions should be of the form ' +
  4984. ':s/pattern/replace/');
  4985. return;
  4986. }
  4987. }
  4988. if (trailing) {
  4989. flagsPart = trailing[0];
  4990. count = parseInt(trailing[1]);
  4991. if (flagsPart) {
  4992. if (flagsPart.indexOf('c') != -1) {
  4993. confirm = true;
  4994. flagsPart.replace('c', '');
  4995. }
  4996. if (flagsPart.indexOf('g') != -1) {
  4997. global = true;
  4998. flagsPart.replace('g', '');
  4999. }
  5000. if (getOption('pcre')) {
  5001. regexPart = regexPart + '/' + flagsPart;
  5002. } else {
  5003. regexPart = regexPart.replace(/\//g, "\\/") + '/' + flagsPart;
  5004. }
  5005. }
  5006. }
  5007. if (regexPart) {
  5008. try {
  5009. updateSearchQuery(cm, regexPart, true /** ignoreCase */,
  5010. true /** smartCase */);
  5011. } catch (e) {
  5012. showConfirm(cm, 'Invalid regex: ' + regexPart);
  5013. return;
  5014. }
  5015. }
  5016. replacePart = replacePart || vimGlobalState.lastSubstituteReplacePart;
  5017. if (replacePart === undefined) {
  5018. showConfirm(cm, 'No previous substitute regular expression');
  5019. return;
  5020. }
  5021. var state = getSearchState(cm);
  5022. var query = state.getQuery();
  5023. var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line;
  5024. var lineEnd = params.lineEnd || lineStart;
  5025. if (lineStart == cm.firstLine() && lineEnd == cm.lastLine()) {
  5026. lineEnd = Infinity;
  5027. }
  5028. if (count) {
  5029. lineStart = lineEnd;
  5030. lineEnd = lineStart + count - 1;
  5031. }
  5032. var startPos = clipCursorToContent(cm, Pos(lineStart, 0));
  5033. var cursor = cm.getSearchCursor(query, startPos);
  5034. doReplace(cm, confirm, global, lineStart, lineEnd, cursor, query, replacePart, params.callback);
  5035. },
  5036. redo: CodeMirror.commands.redo,
  5037. undo: CodeMirror.commands.undo,
  5038. write: function(cm) {
  5039. if (CodeMirror.commands.save) {
  5040. CodeMirror.commands.save(cm);
  5041. } else if (cm.save) {
  5042. cm.save();
  5043. }
  5044. },
  5045. nohlsearch: function(cm) {
  5046. clearSearchHighlight(cm);
  5047. },
  5048. yank: function (cm) {
  5049. var cur = copyCursor(cm.getCursor());
  5050. var line = cur.line;
  5051. var lineText = cm.getLine(line);
  5052. vimGlobalState.registerController.pushText(
  5053. '0', 'yank', lineText, true, true);
  5054. },
  5055. delmarks: function(cm, params) {
  5056. if (!params.argString || !trim(params.argString)) {
  5057. showConfirm(cm, 'Argument required');
  5058. return;
  5059. }
  5060. var state = cm.state.vim;
  5061. var stream = new CodeMirror.StringStream(trim(params.argString));
  5062. while (!stream.eol()) {
  5063. stream.eatSpace();
  5064. var count = stream.pos;
  5065. if (!stream.match(/[a-zA-Z]/, false)) {
  5066. showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
  5067. return;
  5068. }
  5069. var sym = stream.next();
  5070. if (stream.match('-', true)) {
  5071. if (!stream.match(/[a-zA-Z]/, false)) {
  5072. showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
  5073. return;
  5074. }
  5075. var startMark = sym;
  5076. var finishMark = stream.next();
  5077. if (isLowerCase(startMark) && isLowerCase(finishMark) ||
  5078. isUpperCase(startMark) && isUpperCase(finishMark)) {
  5079. var start = startMark.charCodeAt(0);
  5080. var finish = finishMark.charCodeAt(0);
  5081. if (start >= finish) {
  5082. showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
  5083. return;
  5084. }
  5085. for (var j = 0; j <= finish - start; j++) {
  5086. var mark = String.fromCharCode(start + j);
  5087. delete state.marks[mark];
  5088. }
  5089. } else {
  5090. showConfirm(cm, 'Invalid argument: ' + startMark + '-');
  5091. return;
  5092. }
  5093. } else {
  5094. delete state.marks[sym];
  5095. }
  5096. }
  5097. }
  5098. };
  5099. var exCommandDispatcher = new ExCommandDispatcher();
  5100. function doReplace(cm, confirm, global, lineStart, lineEnd, searchCursor, query,
  5101. replaceWith, callback) {
  5102. cm.state.vim.exMode = true;
  5103. var done = false;
  5104. var lastPos = searchCursor.from();
  5105. function replaceAll() {
  5106. cm.operation(function() {
  5107. while (!done) {
  5108. replace();
  5109. next();
  5110. }
  5111. stop();
  5112. });
  5113. }
  5114. function replace() {
  5115. var text = cm.getRange(searchCursor.from(), searchCursor.to());
  5116. var newText = text.replace(query, replaceWith);
  5117. searchCursor.replace(newText);
  5118. }
  5119. function next() {
  5120. while(searchCursor.findNext() &&
  5121. isInRange(searchCursor.from(), lineStart, lineEnd)) {
  5122. if (!global && lastPos && searchCursor.from().line == lastPos.line) {
  5123. continue;
  5124. }
  5125. cm.scrollIntoView(searchCursor.from(), 30);
  5126. cm.setSelection(searchCursor.from(), searchCursor.to());
  5127. lastPos = searchCursor.from();
  5128. done = false;
  5129. return;
  5130. }
  5131. done = true;
  5132. }
  5133. function stop(close) {
  5134. if (close) { close(); }
  5135. cm.focus();
  5136. if (lastPos) {
  5137. cm.setCursor(lastPos);
  5138. var vim = cm.state.vim;
  5139. vim.exMode = false;
  5140. vim.lastHPos = vim.lastHSPos = lastPos.ch;
  5141. }
  5142. if (callback) { callback(); }
  5143. }
  5144. function onPromptKeyDown(e, _value, close) {
  5145. CodeMirror.e_stop(e);
  5146. var keyName = CodeMirror.keyName(e);
  5147. switch (keyName) {
  5148. case 'Y':
  5149. replace(); next(); break;
  5150. case 'N':
  5151. next(); break;
  5152. case 'A':
  5153. var savedCallback = callback;
  5154. callback = undefined;
  5155. cm.operation(replaceAll);
  5156. callback = savedCallback;
  5157. break;
  5158. case 'L':
  5159. replace();
  5160. case 'Q':
  5161. case 'Esc':
  5162. case 'Ctrl-C':
  5163. case 'Ctrl-[':
  5164. stop(close);
  5165. break;
  5166. }
  5167. if (done) { stop(close); }
  5168. return true;
  5169. }
  5170. next();
  5171. if (done) {
  5172. showConfirm(cm, 'No matches for ' + query.source);
  5173. return;
  5174. }
  5175. if (!confirm) {
  5176. replaceAll();
  5177. if (callback) { callback(); }
  5178. return;
  5179. }
  5180. showPrompt(cm, {
  5181. prefix: 'replace with <strong>' + replaceWith + '</strong> (y/n/a/q/l)',
  5182. onKeyDown: onPromptKeyDown
  5183. });
  5184. }
  5185. CodeMirror.keyMap.vim = {
  5186. attach: attachVimMap,
  5187. detach: detachVimMap,
  5188. call: cmKey
  5189. };
  5190. function exitInsertMode(cm) {
  5191. var vim = cm.state.vim;
  5192. var macroModeState = vimGlobalState.macroModeState;
  5193. var insertModeChangeRegister = vimGlobalState.registerController.getRegister('.');
  5194. var isPlaying = macroModeState.isPlaying;
  5195. var lastChange = macroModeState.lastInsertModeChanges;
  5196. if (!isPlaying) {
  5197. cm.off('change', onChange);
  5198. CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
  5199. }
  5200. if (!isPlaying && vim.insertModeRepeat > 1) {
  5201. repeatLastEdit(cm, vim, vim.insertModeRepeat - 1,
  5202. true /** repeatForInsert */);
  5203. vim.lastEditInputState.repeatOverride = vim.insertModeRepeat;
  5204. }
  5205. delete vim.insertModeRepeat;
  5206. vim.insertMode = false;
  5207. cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1);
  5208. cm.setOption('keyMap', 'vim');
  5209. cm.setOption('disableInput', true);
  5210. cm.toggleOverwrite(false); // exit replace mode if we were in it.
  5211. insertModeChangeRegister.setText(lastChange.changes.join(''));
  5212. CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
  5213. if (macroModeState.isRecording) {
  5214. logInsertModeChange(macroModeState);
  5215. }
  5216. }
  5217. function _mapCommand(command) {
  5218. defaultKeymap.unshift(command);
  5219. }
  5220. function mapCommand(keys, type, name, args, extra) {
  5221. var command = {keys: keys, type: type};
  5222. command[type] = name;
  5223. command[type + "Args"] = args;
  5224. for (var key in extra)
  5225. command[key] = extra[key];
  5226. _mapCommand(command);
  5227. }
  5228. defineOption('insertModeEscKeysTimeout', 200, 'number');
  5229. CodeMirror.keyMap['vim-insert'] = {
  5230. fallthrough: ['default'],
  5231. attach: attachVimMap,
  5232. detach: detachVimMap,
  5233. call: cmKey
  5234. };
  5235. CodeMirror.keyMap['vim-replace'] = {
  5236. 'Backspace': 'goCharLeft',
  5237. fallthrough: ['vim-insert'],
  5238. attach: attachVimMap,
  5239. detach: detachVimMap,
  5240. call: cmKey
  5241. };
  5242. function executeMacroRegister(cm, vim, macroModeState, registerName) {
  5243. var register = vimGlobalState.registerController.getRegister(registerName);
  5244. if (registerName == ':') {
  5245. if (register.keyBuffer[0]) {
  5246. exCommandDispatcher.processCommand(cm, register.keyBuffer[0]);
  5247. }
  5248. macroModeState.isPlaying = false;
  5249. return;
  5250. }
  5251. var keyBuffer = register.keyBuffer;
  5252. var imc = 0;
  5253. macroModeState.isPlaying = true;
  5254. macroModeState.replaySearchQueries = register.searchQueries.slice(0);
  5255. for (var i = 0; i < keyBuffer.length; i++) {
  5256. var text = keyBuffer[i];
  5257. var match, key;
  5258. while (text) {
  5259. match = (/<\w+-.+?>|<\w+>|./).exec(text);
  5260. key = match[0];
  5261. text = text.substring(match.index + key.length);
  5262. CodeMirror.Vim.handleKey(cm, key, 'macro');
  5263. if (vim.insertMode) {
  5264. var changes = register.insertModeChanges[imc++].changes;
  5265. vimGlobalState.macroModeState.lastInsertModeChanges.changes =
  5266. changes;
  5267. repeatInsertModeChanges(cm, changes, 1);
  5268. exitInsertMode(cm);
  5269. }
  5270. }
  5271. }
  5272. macroModeState.isPlaying = false;
  5273. }
  5274. function logKey(macroModeState, key) {
  5275. if (macroModeState.isPlaying) { return; }
  5276. var registerName = macroModeState.latestRegister;
  5277. var register = vimGlobalState.registerController.getRegister(registerName);
  5278. if (register) {
  5279. register.pushText(key);
  5280. }
  5281. }
  5282. function logInsertModeChange(macroModeState) {
  5283. if (macroModeState.isPlaying) { return; }
  5284. var registerName = macroModeState.latestRegister;
  5285. var register = vimGlobalState.registerController.getRegister(registerName);
  5286. if (register && register.pushInsertModeChanges) {
  5287. register.pushInsertModeChanges(macroModeState.lastInsertModeChanges);
  5288. }
  5289. }
  5290. function logSearchQuery(macroModeState, query) {
  5291. if (macroModeState.isPlaying) { return; }
  5292. var registerName = macroModeState.latestRegister;
  5293. var register = vimGlobalState.registerController.getRegister(registerName);
  5294. if (register && register.pushSearchQuery) {
  5295. register.pushSearchQuery(query);
  5296. }
  5297. }
  5298. function onChange(cm, changeObj) {
  5299. var macroModeState = vimGlobalState.macroModeState;
  5300. var lastChange = macroModeState.lastInsertModeChanges;
  5301. if (!macroModeState.isPlaying) {
  5302. while(changeObj) {
  5303. lastChange.expectCursorActivityForChange = true;
  5304. if (lastChange.ignoreCount > 1) {
  5305. lastChange.ignoreCount--;
  5306. } else if (changeObj.origin == '+input' || changeObj.origin == 'paste'
  5307. || changeObj.origin === undefined /* only in testing */) {
  5308. var selectionCount = cm.listSelections().length;
  5309. if (selectionCount > 1)
  5310. lastChange.ignoreCount = selectionCount;
  5311. var text = changeObj.text.join('\n');
  5312. if (lastChange.maybeReset) {
  5313. lastChange.changes = [];
  5314. lastChange.maybeReset = false;
  5315. }
  5316. if (text) {
  5317. if (cm.state.overwrite && !/\n/.test(text)) {
  5318. lastChange.changes.push([text]);
  5319. } else {
  5320. lastChange.changes.push(text);
  5321. }
  5322. }
  5323. }
  5324. changeObj = changeObj.next;
  5325. }
  5326. }
  5327. }
  5328. function onCursorActivity(cm) {
  5329. var vim = cm.state.vim;
  5330. if (vim.insertMode) {
  5331. var macroModeState = vimGlobalState.macroModeState;
  5332. if (macroModeState.isPlaying) { return; }
  5333. var lastChange = macroModeState.lastInsertModeChanges;
  5334. if (lastChange.expectCursorActivityForChange) {
  5335. lastChange.expectCursorActivityForChange = false;
  5336. } else {
  5337. lastChange.maybeReset = true;
  5338. }
  5339. } else if (!cm.curOp.isVimOp) {
  5340. handleExternalSelection(cm, vim);
  5341. }
  5342. if (vim.visualMode) {
  5343. updateFakeCursor(cm);
  5344. }
  5345. }
  5346. function updateFakeCursor(cm) {
  5347. var vim = cm.state.vim;
  5348. var from = clipCursorToContent(cm, copyCursor(vim.sel.head));
  5349. var to = offsetCursor(from, 0, 1);
  5350. if (vim.fakeCursor) {
  5351. vim.fakeCursor.clear();
  5352. }
  5353. vim.fakeCursor = cm.markText(from, to, {className: 'cm-animate-fat-cursor'});
  5354. }
  5355. function handleExternalSelection(cm, vim, keepHPos) {
  5356. var anchor = cm.getCursor('anchor');
  5357. var head = cm.getCursor('head');
  5358. if (vim.visualMode && !cm.somethingSelected()) {
  5359. exitVisualMode(cm, false);
  5360. } else if (!vim.visualMode && !vim.insertMode && cm.somethingSelected()) {
  5361. vim.visualMode = true;
  5362. vim.visualLine = false;
  5363. CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
  5364. }
  5365. if (vim.visualMode) {
  5366. var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0;
  5367. var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0;
  5368. head = offsetCursor(head, 0, headOffset);
  5369. anchor = offsetCursor(anchor, 0, anchorOffset);
  5370. vim.sel = {
  5371. anchor: anchor,
  5372. head: head
  5373. };
  5374. updateMark(cm, vim, '<', cursorMin(head, anchor));
  5375. updateMark(cm, vim, '>', cursorMax(head, anchor));
  5376. } else if (!vim.insertMode && !keepHPos) {
  5377. vim.lastHPos = cm.getCursor().ch;
  5378. }
  5379. }
  5380. function InsertModeKey(keyName) {
  5381. this.keyName = keyName;
  5382. }
  5383. function onKeyEventTargetKeyDown(e) {
  5384. var macroModeState = vimGlobalState.macroModeState;
  5385. var lastChange = macroModeState.lastInsertModeChanges;
  5386. var keyName = CodeMirror.keyName(e);
  5387. if (!keyName) { return; }
  5388. function onKeyFound() {
  5389. if (lastChange.maybeReset) {
  5390. lastChange.changes = [];
  5391. lastChange.maybeReset = false;
  5392. }
  5393. lastChange.changes.push(new InsertModeKey(keyName));
  5394. return true;
  5395. }
  5396. if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
  5397. CodeMirror.lookupKey(keyName, 'vim-insert', onKeyFound);
  5398. }
  5399. }
  5400. function repeatLastEdit(cm, vim, repeat, repeatForInsert) {
  5401. var macroModeState = vimGlobalState.macroModeState;
  5402. macroModeState.isPlaying = true;
  5403. var isAction = !!vim.lastEditActionCommand;
  5404. var cachedInputState = vim.inputState;
  5405. function repeatCommand() {
  5406. if (isAction) {
  5407. commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand);
  5408. } else {
  5409. commandDispatcher.evalInput(cm, vim);
  5410. }
  5411. }
  5412. function repeatInsert(repeat) {
  5413. if (macroModeState.lastInsertModeChanges.changes.length > 0) {
  5414. repeat = !vim.lastEditActionCommand ? 1 : repeat;
  5415. var changeObject = macroModeState.lastInsertModeChanges;
  5416. repeatInsertModeChanges(cm, changeObject.changes, repeat);
  5417. }
  5418. }
  5419. vim.inputState = vim.lastEditInputState;
  5420. if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) {
  5421. for (var i = 0; i < repeat; i++) {
  5422. repeatCommand();
  5423. repeatInsert(1);
  5424. }
  5425. } else {
  5426. if (!repeatForInsert) {
  5427. repeatCommand();
  5428. }
  5429. repeatInsert(repeat);
  5430. }
  5431. vim.inputState = cachedInputState;
  5432. if (vim.insertMode && !repeatForInsert) {
  5433. exitInsertMode(cm);
  5434. }
  5435. macroModeState.isPlaying = false;
  5436. }
  5437. function repeatInsertModeChanges(cm, changes, repeat) {
  5438. function keyHandler(binding) {
  5439. if (typeof binding == 'string') {
  5440. CodeMirror.commands[binding](cm);
  5441. } else {
  5442. binding(cm);
  5443. }
  5444. return true;
  5445. }
  5446. var head = cm.getCursor('head');
  5447. var visualBlock = vimGlobalState.macroModeState.lastInsertModeChanges.visualBlock;
  5448. if (visualBlock) {
  5449. selectForInsert(cm, head, visualBlock + 1);
  5450. repeat = cm.listSelections().length;
  5451. cm.setCursor(head);
  5452. }
  5453. for (var i = 0; i < repeat; i++) {
  5454. if (visualBlock) {
  5455. cm.setCursor(offsetCursor(head, i, 0));
  5456. }
  5457. for (var j = 0; j < changes.length; j++) {
  5458. var change = changes[j];
  5459. if (change instanceof InsertModeKey) {
  5460. CodeMirror.lookupKey(change.keyName, 'vim-insert', keyHandler);
  5461. } else if (typeof change == "string") {
  5462. var cur = cm.getCursor();
  5463. cm.replaceRange(change, cur, cur);
  5464. } else {
  5465. var start = cm.getCursor();
  5466. var end = offsetCursor(start, 0, change[0].length);
  5467. cm.replaceRange(change[0], start, end);
  5468. }
  5469. }
  5470. }
  5471. if (visualBlock) {
  5472. cm.setCursor(offsetCursor(head, 0, 1));
  5473. }
  5474. }
  5475. resetVimGlobalState();
  5476. CodeMirror.Vim = Vim();
  5477. Vim = CodeMirror.Vim;
  5478. var specialKey = {'return':'CR',backspace:'BS','delete':'Del',esc:'Esc',
  5479. left:'Left',right:'Right',up:'Up',down:'Down',space: 'Space',
  5480. home:'Home',end:'End',pageup:'PageUp',pagedown:'PageDown', enter: 'CR'
  5481. };
  5482. function lookupKey(hashId, key, e) {
  5483. if (key.length > 1 && key[0] == "n") {
  5484. key = key.replace("numpad", "");
  5485. }
  5486. key = specialKey[key] || key;
  5487. var name = '';
  5488. if (e.ctrlKey) { name += 'C-'; }
  5489. if (e.altKey) { name += 'A-'; }
  5490. if ((name || key.length > 1) && e.shiftKey) { name += 'S-'; }
  5491. name += key;
  5492. if (name.length > 1) { name = '<' + name + '>'; }
  5493. return name;
  5494. }
  5495. var handleKey = Vim.handleKey.bind(Vim);
  5496. Vim.handleKey = function(cm, key, origin) {
  5497. return cm.operation(function() {
  5498. return handleKey(cm, key, origin);
  5499. }, true);
  5500. }
  5501. function cloneVimState(state) {
  5502. var n = new state.constructor();
  5503. Object.keys(state).forEach(function(key) {
  5504. var o = state[key];
  5505. if (Array.isArray(o))
  5506. o = o.slice();
  5507. else if (o && typeof o == "object" && o.constructor != Object)
  5508. o = cloneVimState(o);
  5509. n[key] = o;
  5510. });
  5511. if (state.sel) {
  5512. n.sel = {
  5513. head: state.sel.head && copyCursor(state.sel.head),
  5514. anchor: state.sel.anchor && copyCursor(state.sel.anchor)
  5515. };
  5516. }
  5517. return n;
  5518. }
  5519. function multiSelectHandleKey(cm, key, origin) {
  5520. var isHandled = false;
  5521. var vim = Vim.maybeInitVimState_(cm);
  5522. var visualBlock = vim.visualBlock || vim.wasInVisualBlock;
  5523. var wasMultiselect = cm.ace.inMultiSelectMode;
  5524. if (vim.wasInVisualBlock && !wasMultiselect) {
  5525. vim.wasInVisualBlock = false;
  5526. } else if (wasMultiselect && vim.visualBlock) {
  5527. vim.wasInVisualBlock = true;
  5528. }
  5529. if (key == '<Esc>' && !vim.insertMode && !vim.visualMode && wasMultiselect) {
  5530. cm.ace.exitMultiSelectMode();
  5531. } else if (visualBlock || !wasMultiselect || cm.ace.inVirtualSelectionMode) {
  5532. isHandled = Vim.handleKey(cm, key, origin);
  5533. } else {
  5534. var old = cloneVimState(vim);
  5535. cm.operation(function() {
  5536. cm.ace.forEachSelection(function() {
  5537. var sel = cm.ace.selection;
  5538. cm.state.vim.lastHPos = sel.$desiredColumn == null ? sel.lead.column : sel.$desiredColumn;
  5539. var head = cm.getCursor("head");
  5540. var anchor = cm.getCursor("anchor");
  5541. var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0;
  5542. var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0;
  5543. head = offsetCursor(head, 0, headOffset);
  5544. anchor = offsetCursor(anchor, 0, anchorOffset);
  5545. cm.state.vim.sel.head = head;
  5546. cm.state.vim.sel.anchor = anchor;
  5547. isHandled = handleKey(cm, key, origin);
  5548. sel.$desiredColumn = cm.state.vim.lastHPos == -1 ? null : cm.state.vim.lastHPos;
  5549. if (cm.virtualSelectionMode()) {
  5550. cm.state.vim = cloneVimState(old);
  5551. }
  5552. });
  5553. if (cm.curOp.cursorActivity && !isHandled)
  5554. cm.curOp.cursorActivity = false;
  5555. }, true);
  5556. }
  5557. if (isHandled && !vim.visualMode && !vim.insert && vim.visualMode != cm.somethingSelected()) {
  5558. handleExternalSelection(cm, vim, true);
  5559. }
  5560. return isHandled;
  5561. }
  5562. exports.CodeMirror = CodeMirror;
  5563. var getVim = Vim.maybeInitVimState_;
  5564. exports.handler = {
  5565. $id: "ace/keyboard/vim",
  5566. drawCursor: function(element, pixelPos, config, sel, session) {
  5567. var vim = this.state.vim || {};
  5568. var w = config.characterWidth;
  5569. var h = config.lineHeight;
  5570. var top = pixelPos.top;
  5571. var left = pixelPos.left;
  5572. if (!vim.insertMode) {
  5573. var isbackwards = !sel.cursor
  5574. ? session.selection.isBackwards() || session.selection.isEmpty()
  5575. : Range.comparePoints(sel.cursor, sel.start) <= 0;
  5576. if (!isbackwards && left > w)
  5577. left -= w;
  5578. }
  5579. if (!vim.insertMode && vim.status) {
  5580. h = h / 2;
  5581. top += h;
  5582. }
  5583. dom.translate(element, left, top);
  5584. dom.setStyle(element.style, "width", w + "px");
  5585. dom.setStyle(element.style, "height", h + "px");
  5586. },
  5587. handleKeyboard: function(data, hashId, key, keyCode, e) {
  5588. var editor = data.editor;
  5589. var cm = editor.state.cm;
  5590. var vim = getVim(cm);
  5591. if (keyCode == -1) return;
  5592. if (!vim.insertMode) {
  5593. if (hashId == -1) {
  5594. if (key.charCodeAt(0) > 0xFF) {
  5595. if (data.inputKey) {
  5596. key = data.inputKey;
  5597. if (key && data.inputHash == 4)
  5598. key = key.toUpperCase();
  5599. }
  5600. }
  5601. data.inputChar = key;
  5602. }
  5603. else if (hashId == 4 || hashId == 0) {
  5604. if (data.inputKey == key && data.inputHash == hashId && data.inputChar) {
  5605. key = data.inputChar;
  5606. hashId = -1
  5607. }
  5608. else {
  5609. data.inputChar = null;
  5610. data.inputKey = key;
  5611. data.inputHash = hashId;
  5612. }
  5613. }
  5614. else {
  5615. data.inputChar = data.inputKey = null;
  5616. }
  5617. }
  5618. if (key == "c" && hashId == 1) { // key == "ctrl-c"
  5619. if (!useragent.isMac && editor.getCopyText()) {
  5620. editor.once("copy", function() {
  5621. editor.selection.clearSelection();
  5622. });
  5623. return {command: "null", passEvent: true};
  5624. }
  5625. }
  5626. if (key == "esc" && !vim.insertMode && !vim.visualMode && !cm.ace.inMultiSelectMode) {
  5627. var searchState = getSearchState(cm);
  5628. var overlay = searchState.getOverlay();
  5629. if (overlay) cm.removeOverlay(overlay);
  5630. }
  5631. if (hashId == -1 || hashId & 1 || hashId === 0 && key.length > 1) {
  5632. var insertMode = vim.insertMode;
  5633. var name = lookupKey(hashId, key, e || {});
  5634. if (vim.status == null)
  5635. vim.status = "";
  5636. var isHandled = multiSelectHandleKey(cm, name, 'user');
  5637. vim = getVim(cm); // may be changed by multiSelectHandleKey
  5638. if (isHandled && vim.status != null)
  5639. vim.status += name;
  5640. else if (vim.status == null)
  5641. vim.status = "";
  5642. cm._signal("changeStatus");
  5643. if (!isHandled && (hashId != -1 || insertMode))
  5644. return;
  5645. return {command: "null", passEvent: !isHandled};
  5646. }
  5647. },
  5648. attach: function(editor) {
  5649. if (!editor.state) editor.state = {};
  5650. var cm = new CodeMirror(editor);
  5651. editor.state.cm = cm;
  5652. editor.$vimModeHandler = this;
  5653. CodeMirror.keyMap.vim.attach(cm);
  5654. getVim(cm).status = null;
  5655. cm.on('vim-command-done', function() {
  5656. if (cm.virtualSelectionMode()) return;
  5657. getVim(cm).status = null;
  5658. cm.ace._signal("changeStatus");
  5659. cm.ace.session.markUndoGroup();
  5660. });
  5661. cm.on("changeStatus", function() {
  5662. cm.ace.renderer.updateCursor();
  5663. cm.ace._signal("changeStatus");
  5664. });
  5665. cm.on("vim-mode-change", function() {
  5666. if (cm.virtualSelectionMode()) return;
  5667. updateInputMode();
  5668. cm._signal("changeStatus");
  5669. });
  5670. function updateInputMode() {
  5671. var isIntsert = getVim(cm).insertMode;
  5672. cm.ace.renderer.setStyle("normal-mode", !isIntsert);
  5673. editor.textInput.setCommandMode(!isIntsert);
  5674. editor.renderer.$keepTextAreaAtCursor = isIntsert;
  5675. editor.renderer.$blockCursor = !isIntsert;
  5676. }
  5677. updateInputMode();
  5678. editor.renderer.$cursorLayer.drawCursor = this.drawCursor.bind(cm);
  5679. },
  5680. detach: function(editor) {
  5681. var cm = editor.state.cm;
  5682. CodeMirror.keyMap.vim.detach(cm);
  5683. cm.destroy();
  5684. editor.state.cm = null;
  5685. editor.$vimModeHandler = null;
  5686. editor.renderer.$cursorLayer.drawCursor = null;
  5687. editor.renderer.setStyle("normal-mode", false);
  5688. editor.textInput.setCommandMode(false);
  5689. editor.renderer.$keepTextAreaAtCursor = true;
  5690. },
  5691. getStatusText: function(editor) {
  5692. var cm = editor.state.cm;
  5693. var vim = getVim(cm);
  5694. if (vim.insertMode)
  5695. return "INSERT";
  5696. var status = "";
  5697. if (vim.visualMode) {
  5698. status += "VISUAL";
  5699. if (vim.visualLine)
  5700. status += " LINE";
  5701. if (vim.visualBlock)
  5702. status += " BLOCK";
  5703. }
  5704. if (vim.status)
  5705. status += (status ? " " : "") + vim.status;
  5706. return status;
  5707. }
  5708. };
  5709. Vim.defineOption({
  5710. name: "wrap",
  5711. set: function(value, cm) {
  5712. if (cm) {cm.ace.setOption("wrap", value)}
  5713. },
  5714. type: "boolean"
  5715. }, false);
  5716. Vim.defineEx('write', 'w', function() {
  5717. console.log(':write is not implemented')
  5718. });
  5719. defaultKeymap.push(
  5720. { keys: 'zc', type: 'action', action: 'fold', actionArgs: { open: false } },
  5721. { keys: 'zC', type: 'action', action: 'fold', actionArgs: { open: false, all: true } },
  5722. { keys: 'zo', type: 'action', action: 'fold', actionArgs: { open: true } },
  5723. { keys: 'zO', type: 'action', action: 'fold', actionArgs: { open: true, all: true } },
  5724. { keys: 'za', type: 'action', action: 'fold', actionArgs: { toggle: true } },
  5725. { keys: 'zA', type: 'action', action: 'fold', actionArgs: { toggle: true, all: true } },
  5726. { keys: 'zf', type: 'action', action: 'fold', actionArgs: { open: true, all: true } },
  5727. { keys: 'zd', type: 'action', action: 'fold', actionArgs: { open: true, all: true } },
  5728. { keys: '<C-A-k>', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorAbove" } },
  5729. { keys: '<C-A-j>', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorBelow" } },
  5730. { keys: '<C-A-S-k>', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorAboveSkipCurrent" } },
  5731. { keys: '<C-A-S-j>', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorBelowSkipCurrent" } },
  5732. { keys: '<C-A-h>', type: 'action', action: 'aceCommand', actionArgs: { name: "selectMoreBefore" } },
  5733. { keys: '<C-A-l>', type: 'action', action: 'aceCommand', actionArgs: { name: "selectMoreAfter" } },
  5734. { keys: '<C-A-S-h>', type: 'action', action: 'aceCommand', actionArgs: { name: "selectNextBefore" } },
  5735. { keys: '<C-A-S-l>', type: 'action', action: 'aceCommand', actionArgs: { name: "selectNextAfter" } }
  5736. );
  5737. actions.aceCommand = function(cm, actionArgs, vim) {
  5738. cm.vimCmd = actionArgs;
  5739. if (cm.ace.inVirtualSelectionMode)
  5740. cm.ace.on("beforeEndOperation", delayedExecAceCommand);
  5741. else
  5742. delayedExecAceCommand(null, cm.ace);
  5743. };
  5744. function delayedExecAceCommand(op, ace) {
  5745. ace.off("beforeEndOperation", delayedExecAceCommand);
  5746. var cmd = ace.state.cm.vimCmd;
  5747. if (cmd) {
  5748. ace.execCommand(cmd.exec ? cmd : cmd.name, cmd.args);
  5749. }
  5750. ace.curOp = ace.prevOp;
  5751. }
  5752. actions.fold = function(cm, actionArgs, vim) {
  5753. cm.ace.execCommand(['toggleFoldWidget', 'toggleFoldWidget', 'foldOther', 'unfoldall'
  5754. ][(actionArgs.all ? 2 : 0) + (actionArgs.open ? 1 : 0)]);
  5755. };
  5756. exports.handler.defaultKeymap = defaultKeymap;
  5757. exports.handler.actions = actions;
  5758. exports.Vim = Vim;
  5759. }); (function() {
  5760. window.ace_require(["ace/keyboard/vim"], function(m) {
  5761. if (typeof module == "object" && typeof exports == "object" && module) {
  5762. module.exports = m;
  5763. }
  5764. });
  5765. })();