keybinding-vim.js 207 KB

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