keybinding-vim.js 214 KB

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