keybinding-vim.js 200 KB

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