keybinding-vim.js 205 KB

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