keybinding-vim.js 212 KB

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