keybinding-vim.js 201 KB

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