vim.js 185 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. /**
  4. * Supported keybindings:
  5. *
  6. * Motion:
  7. * h, j, k, l
  8. * gj, gk
  9. * e, E, w, W, b, B, ge, gE
  10. * f<character>, F<character>, t<character>, T<character>
  11. * $, ^, 0, -, +, _
  12. * gg, G
  13. * %
  14. * '<character>, `<character>
  15. *
  16. * Operator:
  17. * d, y, c
  18. * dd, yy, cc
  19. * g~, g~g~
  20. * >, <, >>, <<
  21. *
  22. * Operator-Motion:
  23. * x, X, D, Y, C, ~
  24. *
  25. * Action:
  26. * a, i, s, A, I, S, o, O
  27. * zz, z., z<CR>, zt, zb, z-
  28. * J
  29. * u, Ctrl-r
  30. * m<character>
  31. * r<character>
  32. *
  33. * Modes:
  34. * ESC - leave insert mode, visual mode, and clear input state.
  35. * Ctrl-[, Ctrl-c - same as ESC.
  36. *
  37. * Registers: unnamed, -, a-z, A-Z, 0-9
  38. * (Does not respect the special case for number registers when delete
  39. * operator is made with these commands: %, (, ), , /, ?, n, N, {, } )
  40. * TODO: Implement the remaining registers.
  41. * Marks: a-z, A-Z, and 0-9
  42. * TODO: Implement the remaining special marks. They have more complex
  43. * behavior.
  44. *
  45. * Events:
  46. * 'vim-mode-change' - raised on the editor anytime the current mode changes,
  47. * Event object: {mode: "visual", subMode: "linewise"}
  48. *
  49. * Code structure:
  50. * 1. Default keymap
  51. * 2. Variable declarations and short basic helpers
  52. * 3. Instance (External API) implementation
  53. * 4. Internal state tracking objects (input state, counter) implementation
  54. * and instanstiation
  55. * 5. Key handler (the main command dispatcher) implementation
  56. * 6. Motion, operator, and action implementations
  57. * 7. Helper functions for the key handler, motions, operators, and actions
  58. * 8. Set up Vim to work as a keymap for CodeMirror.
  59. */
  60. (function(mod) {
  61. if (typeof exports == "object" && typeof module == "object") // CommonJS
  62. mod(require("../lib/codemirror"), require("../addon/search/searchcursor"), require("../addon/dialog/dialog"), require("../addon/edit/matchbrackets.js"));
  63. else if (typeof define == "function" && define.amd) // AMD
  64. define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/dialog/dialog", "../addon/edit/matchbrackets"], mod);
  65. else // Plain browser env
  66. mod(CodeMirror);
  67. })(function(CodeMirror) {
  68. 'use strict';
  69. var defaultKeymap = [
  70. // Key to key mapping. This goes first to make it possible to override
  71. // existing mappings.
  72. { keys: '<Left>', type: 'keyToKey', toKeys: 'h' },
  73. { keys: '<Right>', type: 'keyToKey', toKeys: 'l' },
  74. { keys: '<Up>', type: 'keyToKey', toKeys: 'k' },
  75. { keys: '<Down>', type: 'keyToKey', toKeys: 'j' },
  76. { keys: '<Space>', type: 'keyToKey', toKeys: 'l' },
  77. { keys: '<BS>', type: 'keyToKey', toKeys: 'h' },
  78. { keys: '<C-Space>', type: 'keyToKey', toKeys: 'W' },
  79. { keys: '<C-BS>', type: 'keyToKey', toKeys: 'B' },
  80. { keys: '<S-Space>', type: 'keyToKey', toKeys: 'w' },
  81. { keys: '<S-BS>', type: 'keyToKey', toKeys: 'b' },
  82. { keys: '<C-n>', type: 'keyToKey', toKeys: 'j' },
  83. { keys: '<C-p>', type: 'keyToKey', toKeys: 'k' },
  84. { keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>' },
  85. { keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>' },
  86. { keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
  87. { keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
  88. { keys: 's', type: 'keyToKey', toKeys: 'cl', context: 'normal' },
  89. { keys: 's', type: 'keyToKey', toKeys: 'xi', context: 'visual'},
  90. { keys: 'S', type: 'keyToKey', toKeys: 'cc', context: 'normal' },
  91. { keys: 'S', type: 'keyToKey', toKeys: 'dcc', context: 'visual' },
  92. { keys: '<Home>', type: 'keyToKey', toKeys: '0' },
  93. { keys: '<End>', type: 'keyToKey', toKeys: '$' },
  94. { keys: '<PageUp>', type: 'keyToKey', toKeys: '<C-b>' },
  95. { keys: '<PageDown>', type: 'keyToKey', toKeys: '<C-f>' },
  96. { keys: '<CR>', type: 'keyToKey', toKeys: 'j^', context: 'normal' },
  97. // Motions
  98. { keys: 'H', type: 'motion', motion: 'moveToTopLine', motionArgs: { linewise: true, toJumplist: true }},
  99. { keys: 'M', type: 'motion', motion: 'moveToMiddleLine', motionArgs: { linewise: true, toJumplist: true }},
  100. { keys: 'L', type: 'motion', motion: 'moveToBottomLine', motionArgs: { linewise: true, toJumplist: true }},
  101. { keys: 'h', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: false }},
  102. { keys: 'l', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: true }},
  103. { keys: 'j', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, linewise: true }},
  104. { keys: 'k', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, linewise: true }},
  105. { keys: 'gj', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: true }},
  106. { keys: 'gk', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: false }},
  107. { keys: 'w', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false }},
  108. { keys: 'W', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false, bigWord: true }},
  109. { keys: 'e', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, inclusive: true }},
  110. { keys: 'E', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, bigWord: true, inclusive: true }},
  111. { keys: 'b', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }},
  112. { keys: 'B', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false, bigWord: true }},
  113. { keys: 'ge', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, inclusive: true }},
  114. { keys: 'gE', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, bigWord: true, inclusive: true }},
  115. { keys: '{', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: false, toJumplist: true }},
  116. { keys: '}', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: true, toJumplist: true }},
  117. { keys: '<C-f>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: true }},
  118. { keys: '<C-b>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: false }},
  119. { keys: '<C-d>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: true, explicitRepeat: true }},
  120. { keys: '<C-u>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: false, explicitRepeat: true }},
  121. { keys: 'gg', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},
  122. { keys: 'G', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},
  123. { keys: '0', type: 'motion', motion: 'moveToStartOfLine' },
  124. { keys: '^', type: 'motion', motion: 'moveToFirstNonWhiteSpaceCharacter' },
  125. { keys: '+', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true }},
  126. { keys: '-', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, toFirstChar:true }},
  127. { keys: '_', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},
  128. { keys: '$', type: 'motion', motion: 'moveToEol', motionArgs: { inclusive: true }},
  129. { keys: '%', type: 'motion', motion: 'moveToMatchedSymbol', motionArgs: { inclusive: true, toJumplist: true }},
  130. { keys: 'f<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: true , inclusive: true }},
  131. { keys: 'F<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: false }},
  132. { keys: 't<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: true, inclusive: true }},
  133. { keys: 'T<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: false }},
  134. { keys: ';', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: true }},
  135. { keys: ',', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: false }},
  136. { keys: '\'<character>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true, linewise: true}},
  137. { keys: '`<character>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true}},
  138. { keys: ']`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
  139. { keys: '[`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
  140. { keys: ']\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
  141. { keys: '[\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
  142. // the next two aren't motions but must come before more general motion declarations
  143. { keys: ']p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true, matchIndent: true}},
  144. { keys: '[p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true, matchIndent: true}},
  145. { keys: ']<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: true, toJumplist: true}},
  146. { keys: '[<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: false, toJumplist: true}},
  147. { keys: '|', type: 'motion', motion: 'moveToColumn'},
  148. { keys: 'o', type: 'motion', motion: 'moveToOtherHighlightedEnd', context:'visual'},
  149. { keys: 'O', type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: {sameLine: true}, context:'visual'},
  150. // Operators
  151. { keys: 'd', type: 'operator', operator: 'delete' },
  152. { keys: 'y', type: 'operator', operator: 'yank' },
  153. { keys: 'c', type: 'operator', operator: 'change' },
  154. { keys: '>', type: 'operator', operator: 'indent', operatorArgs: { indentRight: true }},
  155. { keys: '<', type: 'operator', operator: 'indent', operatorArgs: { indentRight: false }},
  156. { keys: 'g~', type: 'operator', operator: 'changeCase' },
  157. { keys: 'gu', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, isEdit: true },
  158. { keys: 'gU', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, isEdit: true },
  159. { keys: 'n', type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: true }},
  160. { keys: 'N', type: 'motion', motion: 'findNext', motionArgs: { forward: false, toJumplist: true }},
  161. // Operator-Motion dual commands
  162. { keys: 'x', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorMotionArgs: { visualLine: false }},
  163. { keys: 'X', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: false }, operatorMotionArgs: { visualLine: true }},
  164. { keys: 'D', type: 'operatorMotion', operator: 'delete', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
  165. { keys: 'D', type: 'operator', operator: 'delete', operatorArgs: { linewise: true }, context: 'visual'},
  166. { keys: 'Y', type: 'operatorMotion', operator: 'yank', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
  167. { keys: 'Y', type: 'operator', operator: 'yank', operatorArgs: { linewise: true }, context: 'visual'},
  168. { keys: 'C', type: 'operatorMotion', operator: 'change', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
  169. { keys: 'C', type: 'operator', operator: 'change', operatorArgs: { linewise: true }, context: 'visual'},
  170. { keys: '~', type: 'operatorMotion', operator: 'changeCase', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorArgs: { shouldMoveCursor: true }, context: 'normal'},
  171. { keys: '~', type: 'operator', operator: 'changeCase', context: 'visual'},
  172. { keys: '<C-w>', type: 'operatorMotion', operator: 'delete', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }, context: 'insert' },
  173. // Actions
  174. { keys: '<C-i>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: true }},
  175. { keys: '<C-o>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: false }},
  176. { keys: '<C-e>', type: 'action', action: 'scroll', actionArgs: { forward: true, linewise: true }},
  177. { keys: '<C-y>', type: 'action', action: 'scroll', actionArgs: { forward: false, linewise: true }},
  178. { keys: 'a', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'charAfter' }, context: 'normal' },
  179. { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'eol' }, context: 'normal' },
  180. { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' },
  181. { keys: 'i', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'inplace' }, context: 'normal' },
  182. { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'firstNonBlank'}, context: 'normal' },
  183. { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'startOfSelectedArea' }, context: 'visual' },
  184. { keys: 'o', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: true }, context: 'normal' },
  185. { keys: 'O', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: false }, context: 'normal' },
  186. { keys: 'v', type: 'action', action: 'toggleVisualMode' },
  187. { keys: 'V', type: 'action', action: 'toggleVisualMode', actionArgs: { linewise: true }},
  188. { keys: '<C-v>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }},
  189. { keys: 'gv', type: 'action', action: 'reselectLastSelection' },
  190. { keys: 'J', type: 'action', action: 'joinLines', isEdit: true },
  191. { keys: 'p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true }},
  192. { keys: 'P', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true }},
  193. { keys: 'r<character>', type: 'action', action: 'replace', isEdit: true },
  194. { keys: '@<character>', type: 'action', action: 'replayMacro' },
  195. { keys: 'q<character>', type: 'action', action: 'enterMacroRecordMode' },
  196. // Handle Replace-mode as a special case of insert mode.
  197. { keys: 'R', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { replace: true }},
  198. { keys: 'u', type: 'action', action: 'undo', context: 'normal' },
  199. { keys: 'u', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, context: 'visual', isEdit: true },
  200. { keys: 'U', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, context: 'visual', isEdit: true },
  201. { keys: '<C-r>', type: 'action', action: 'redo' },
  202. { keys: 'm<character>', type: 'action', action: 'setMark' },
  203. { keys: '"<character>', type: 'action', action: 'setRegister' },
  204. { keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }},
  205. { keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
  206. { keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }},
  207. { keys: 'z<CR>', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
  208. { keys: 'z-', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }},
  209. { keys: 'zb', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
  210. { keys: '.', type: 'action', action: 'repeatLastEdit' },
  211. { keys: '<C-a>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: true, backtrack: false}},
  212. { keys: '<C-x>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: false, backtrack: false}},
  213. // Text object motions
  214. { keys: 'a<character>', type: 'motion', motion: 'textObjectManipulation' },
  215. { keys: 'i<character>', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }},
  216. // Search
  217. { keys: '/', type: 'search', searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},
  218. { keys: '?', type: 'search', searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},
  219. { keys: '*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
  220. { keys: '#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
  221. { keys: 'g*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},
  222. { keys: 'g#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},
  223. // Ex command
  224. { keys: ':', type: 'ex' }
  225. ];
  226. var Pos = CodeMirror.Pos;
  227. var modifierCodes = [16, 17, 18, 91];
  228. var specialKey = {Enter:'CR',Backspace:'BS',Delete:'Del'};
  229. var mac = /Mac/.test(navigator.platform);
  230. var Vim = function() {
  231. function lookupKey(e) {
  232. var keyCode = e.keyCode;
  233. if (modifierCodes.indexOf(keyCode) != -1) { return; }
  234. var hasModifier = e.ctrlKey || e.metaKey;
  235. var key = CodeMirror.keyNames[keyCode];
  236. key = specialKey[key] || key;
  237. var name = '';
  238. if (e.ctrlKey) { name += 'C-'; }
  239. if (e.altKey) { name += 'A-'; }
  240. if (mac && e.metaKey || (!hasModifier && e.shiftKey) && key.length < 2) {
  241. // Shift key bindings can only specified for special characters.
  242. return;
  243. } else if (e.shiftKey && !/^[A-Za-z]$/.test(key)) {
  244. name += 'S-';
  245. }
  246. if (key.length == 1) { key = key.toLowerCase(); }
  247. name += key;
  248. if (name.length > 1) { name = '<' + name + '>'; }
  249. return name;
  250. }
  251. // Keys with modifiers are handled using keydown due to limitations of
  252. // keypress event.
  253. function handleKeyDown(cm, e) {
  254. var name = lookupKey(e);
  255. if (!name) { return; }
  256. CodeMirror.signal(cm, 'vim-keypress', name);
  257. if (CodeMirror.Vim.handleKey(cm, name, 'user')) {
  258. CodeMirror.e_stop(e);
  259. }
  260. }
  261. // Keys without modifiers are handled using keypress to work best with
  262. // non-standard keyboard layouts.
  263. function handleKeyPress(cm, e) {
  264. var code = e.charCode || e.keyCode;
  265. if (e.ctrlKey || e.metaKey || e.altKey ||
  266. e.shiftKey && code < 32) { return; }
  267. var name = String.fromCharCode(code);
  268. CodeMirror.signal(cm, 'vim-keypress', name);
  269. if (CodeMirror.Vim.handleKey(cm, name, 'user')) {
  270. CodeMirror.e_stop(e);
  271. }
  272. }
  273. function enterVimMode(cm) {
  274. cm.setOption('disableInput', true);
  275. cm.setOption('showCursorWhenSelecting', false);
  276. CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
  277. cm.on('cursorActivity', onCursorActivity);
  278. maybeInitVimState(cm);
  279. CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm));
  280. cm.on('keypress', handleKeyPress);
  281. cm.on('keydown', handleKeyDown);
  282. }
  283. function leaveVimMode(cm) {
  284. cm.setOption('disableInput', false);
  285. cm.off('cursorActivity', onCursorActivity);
  286. CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm));
  287. cm.state.vim = null;
  288. cm.off('keypress', handleKeyPress);
  289. cm.off('keydown', handleKeyDown);
  290. }
  291. function detachVimMap(cm, next) {
  292. if (this == CodeMirror.keyMap.vim)
  293. CodeMirror.rmClass(cm.getWrapperElement(), "cm-fat-cursor");
  294. if (!next || next.attach != attachVimMap)
  295. leaveVimMode(cm, false);
  296. }
  297. function attachVimMap(cm, prev) {
  298. if (this == CodeMirror.keyMap.vim)
  299. CodeMirror.addClass(cm.getWrapperElement(), "cm-fat-cursor");
  300. if (!prev || prev.attach != attachVimMap)
  301. enterVimMode(cm);
  302. }
  303. // Deprecated, simply setting the keymap works again.
  304. CodeMirror.defineOption('vimMode', false, function(cm, val, prev) {
  305. if (val && cm.getOption("keyMap") != "vim")
  306. cm.setOption("keyMap", "vim");
  307. else if (!val && prev != CodeMirror.Init && /^vim/.test(cm.getOption("keyMap")))
  308. cm.setOption("keyMap", "default");
  309. });
  310. function getOnPasteFn(cm) {
  311. var vim = cm.state.vim;
  312. if (!vim.onPasteFn) {
  313. vim.onPasteFn = function() {
  314. if (!vim.insertMode) {
  315. cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
  316. actions.enterInsertMode(cm, {}, vim);
  317. }
  318. };
  319. }
  320. return vim.onPasteFn;
  321. }
  322. var numberRegex = /[\d]/;
  323. var wordRegexp = [(/\w/), (/[^\w\s]/)], bigWordRegexp = [(/\S/)];
  324. function makeKeyRange(start, size) {
  325. var keys = [];
  326. for (var i = start; i < start + size; i++) {
  327. keys.push(String.fromCharCode(i));
  328. }
  329. return keys;
  330. }
  331. var upperCaseAlphabet = makeKeyRange(65, 26);
  332. var lowerCaseAlphabet = makeKeyRange(97, 26);
  333. var numbers = makeKeyRange(48, 10);
  334. var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']);
  335. var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"', '.', ':', '/']);
  336. function isLine(cm, line) {
  337. return line >= cm.firstLine() && line <= cm.lastLine();
  338. }
  339. function isLowerCase(k) {
  340. return (/^[a-z]$/).test(k);
  341. }
  342. function isMatchableSymbol(k) {
  343. return '()[]{}'.indexOf(k) != -1;
  344. }
  345. function isNumber(k) {
  346. return numberRegex.test(k);
  347. }
  348. function isUpperCase(k) {
  349. return (/^[A-Z]$/).test(k);
  350. }
  351. function isWhiteSpaceString(k) {
  352. return (/^\s*$/).test(k);
  353. }
  354. function inArray(val, arr) {
  355. for (var i = 0; i < arr.length; i++) {
  356. if (arr[i] == val) {
  357. return true;
  358. }
  359. }
  360. return false;
  361. }
  362. var options = {};
  363. function defineOption(name, defaultValue, type) {
  364. if (defaultValue === undefined) { throw Error('defaultValue is required'); }
  365. if (!type) { type = 'string'; }
  366. options[name] = {
  367. type: type,
  368. defaultValue: defaultValue
  369. };
  370. setOption(name, defaultValue);
  371. }
  372. function setOption(name, value) {
  373. var option = options[name];
  374. if (!option) {
  375. throw Error('Unknown option: ' + name);
  376. }
  377. if (option.type == 'boolean') {
  378. if (value && value !== true) {
  379. throw Error('Invalid argument: ' + name + '=' + value);
  380. } else if (value !== false) {
  381. // Boolean options are set to true if value is not defined.
  382. value = true;
  383. }
  384. }
  385. option.value = option.type == 'boolean' ? !!value : value;
  386. }
  387. function getOption(name) {
  388. var option = options[name];
  389. if (!option) {
  390. throw Error('Unknown option: ' + name);
  391. }
  392. return option.value;
  393. }
  394. var createCircularJumpList = function() {
  395. var size = 100;
  396. var pointer = -1;
  397. var head = 0;
  398. var tail = 0;
  399. var buffer = new Array(size);
  400. function add(cm, oldCur, newCur) {
  401. var current = pointer % size;
  402. var curMark = buffer[current];
  403. function useNextSlot(cursor) {
  404. var next = ++pointer % size;
  405. var trashMark = buffer[next];
  406. if (trashMark) {
  407. trashMark.clear();
  408. }
  409. buffer[next] = cm.setBookmark(cursor);
  410. }
  411. if (curMark) {
  412. var markPos = curMark.find();
  413. // avoid recording redundant cursor position
  414. if (markPos && !cursorEqual(markPos, oldCur)) {
  415. useNextSlot(oldCur);
  416. }
  417. } else {
  418. useNextSlot(oldCur);
  419. }
  420. useNextSlot(newCur);
  421. head = pointer;
  422. tail = pointer - size + 1;
  423. if (tail < 0) {
  424. tail = 0;
  425. }
  426. }
  427. function move(cm, offset) {
  428. pointer += offset;
  429. if (pointer > head) {
  430. pointer = head;
  431. } else if (pointer < tail) {
  432. pointer = tail;
  433. }
  434. var mark = buffer[(size + pointer) % size];
  435. // skip marks that are temporarily removed from text buffer
  436. if (mark && !mark.find()) {
  437. var inc = offset > 0 ? 1 : -1;
  438. var newCur;
  439. var oldCur = cm.getCursor();
  440. do {
  441. pointer += inc;
  442. mark = buffer[(size + pointer) % size];
  443. // skip marks that are the same as current position
  444. if (mark &&
  445. (newCur = mark.find()) &&
  446. !cursorEqual(oldCur, newCur)) {
  447. break;
  448. }
  449. } while (pointer < head && pointer > tail);
  450. }
  451. return mark;
  452. }
  453. return {
  454. cachedCursor: undefined, //used for # and * jumps
  455. add: add,
  456. move: move
  457. };
  458. };
  459. // Returns an object to track the changes associated insert mode. It
  460. // clones the object that is passed in, or creates an empty object one if
  461. // none is provided.
  462. var createInsertModeChanges = function(c) {
  463. if (c) {
  464. // Copy construction
  465. return {
  466. changes: c.changes,
  467. expectCursorActivityForChange: c.expectCursorActivityForChange
  468. };
  469. }
  470. return {
  471. // Change list
  472. changes: [],
  473. // Set to true on change, false on cursorActivity.
  474. expectCursorActivityForChange: false
  475. };
  476. };
  477. function MacroModeState() {
  478. this.latestRegister = undefined;
  479. this.isPlaying = false;
  480. this.isRecording = false;
  481. this.replaySearchQueries = [];
  482. this.onRecordingDone = undefined;
  483. this.lastInsertModeChanges = createInsertModeChanges();
  484. }
  485. MacroModeState.prototype = {
  486. exitMacroRecordMode: function() {
  487. var macroModeState = vimGlobalState.macroModeState;
  488. if (macroModeState.onRecordingDone) {
  489. macroModeState.onRecordingDone(); // close dialog
  490. }
  491. macroModeState.onRecordingDone = undefined;
  492. macroModeState.isRecording = false;
  493. },
  494. enterMacroRecordMode: function(cm, registerName) {
  495. var register =
  496. vimGlobalState.registerController.getRegister(registerName);
  497. if (register) {
  498. register.clear();
  499. this.latestRegister = registerName;
  500. if (cm.openDialog) {
  501. this.onRecordingDone = cm.openDialog(
  502. '(recording)['+registerName+']', null, {bottom:true});
  503. }
  504. this.isRecording = true;
  505. }
  506. }
  507. };
  508. function maybeInitVimState(cm) {
  509. if (!cm.state.vim) {
  510. // Store instance state in the CodeMirror object.
  511. cm.state.vim = {
  512. inputState: new InputState(),
  513. // Vim's input state that triggered the last edit, used to repeat
  514. // motions and operators with '.'.
  515. lastEditInputState: undefined,
  516. // Vim's action command before the last edit, used to repeat actions
  517. // with '.' and insert mode repeat.
  518. lastEditActionCommand: undefined,
  519. // When using jk for navigation, if you move from a longer line to a
  520. // shorter line, the cursor may clip to the end of the shorter line.
  521. // If j is pressed again and cursor goes to the next line, the
  522. // cursor should go back to its horizontal position on the longer
  523. // line if it can. This is to keep track of the horizontal position.
  524. lastHPos: -1,
  525. // Doing the same with screen-position for gj/gk
  526. lastHSPos: -1,
  527. // The last motion command run. Cleared if a non-motion command gets
  528. // executed in between.
  529. lastMotion: null,
  530. marks: {},
  531. // Mark for rendering fake cursor for visual mode.
  532. fakeCursor: null,
  533. insertMode: false,
  534. // Repeat count for changes made in insert mode, triggered by key
  535. // sequences like 3,i. Only exists when insertMode is true.
  536. insertModeRepeat: undefined,
  537. visualMode: false,
  538. // If we are in visual line mode. No effect if visualMode is false.
  539. visualLine: false,
  540. visualBlock: false,
  541. lastSelection: null,
  542. lastPastedText: null,
  543. sel: {
  544. }
  545. };
  546. }
  547. return cm.state.vim;
  548. }
  549. var vimGlobalState;
  550. function resetVimGlobalState() {
  551. vimGlobalState = {
  552. // The current search query.
  553. searchQuery: null,
  554. // Whether we are searching backwards.
  555. searchIsReversed: false,
  556. // Replace part of the last substituted pattern
  557. lastSubstituteReplacePart: undefined,
  558. jumpList: createCircularJumpList(),
  559. macroModeState: new MacroModeState,
  560. // Recording latest f, t, F or T motion command.
  561. lastChararacterSearch: {increment:0, forward:true, selectedCharacter:''},
  562. registerController: new RegisterController({}),
  563. // search history buffer
  564. searchHistoryController: new HistoryController({}),
  565. // ex Command history buffer
  566. exCommandHistoryController : new HistoryController({})
  567. };
  568. for (var optionName in options) {
  569. var option = options[optionName];
  570. option.value = option.defaultValue;
  571. }
  572. }
  573. var lastInsertModeKeyTimer;
  574. var vimApi= {
  575. buildKeyMap: function() {
  576. // TODO: Convert keymap into dictionary format for fast lookup.
  577. },
  578. // Testing hook, though it might be useful to expose the register
  579. // controller anyways.
  580. getRegisterController: function() {
  581. return vimGlobalState.registerController;
  582. },
  583. // Testing hook.
  584. resetVimGlobalState_: resetVimGlobalState,
  585. // Testing hook.
  586. getVimGlobalState_: function() {
  587. return vimGlobalState;
  588. },
  589. // Testing hook.
  590. maybeInitVimState_: maybeInitVimState,
  591. InsertModeKey: InsertModeKey,
  592. map: function(lhs, rhs, ctx) {
  593. // Add user defined key bindings.
  594. exCommandDispatcher.map(lhs, rhs, ctx);
  595. },
  596. setOption: setOption,
  597. getOption: getOption,
  598. defineOption: defineOption,
  599. defineEx: function(name, prefix, func){
  600. if (name.indexOf(prefix) !== 0) {
  601. throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered');
  602. }
  603. exCommands[name]=func;
  604. exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'};
  605. },
  606. // This is the outermost function called by CodeMirror, after keys have
  607. // been mapped to their Vim equivalents.
  608. handleKey: function(cm, key, origin) {
  609. var vim = maybeInitVimState(cm);
  610. function handleMacroRecording() {
  611. var macroModeState = vimGlobalState.macroModeState;
  612. if (macroModeState.isRecording) {
  613. if (key == 'q') {
  614. macroModeState.exitMacroRecordMode();
  615. clearInputState(cm);
  616. return true;
  617. }
  618. if (origin != 'mapping') {
  619. logKey(macroModeState, key);
  620. }
  621. }
  622. }
  623. function handleEsc() {
  624. if (key == '<Esc>') {
  625. // Clear input state and get back to normal mode.
  626. clearInputState(cm);
  627. if (vim.visualMode) {
  628. exitVisualMode(cm);
  629. } else if (vim.insertMode) {
  630. exitInsertMode(cm);
  631. }
  632. return true;
  633. }
  634. }
  635. function doKeyToKey(keys) {
  636. // TODO: prevent infinite recursion.
  637. var match;
  638. while (keys) {
  639. // Pull off one command key, which is either a single character
  640. // or a special sequence wrapped in '<' and '>', e.g. '<Space>'.
  641. match = (/<\w+-.+?>|<\w+>|./).exec(keys);
  642. key = match[0];
  643. keys = keys.substring(match.index + key.length);
  644. CodeMirror.Vim.handleKey(cm, key, 'mapping');
  645. }
  646. }
  647. function handleKeyInsertMode() {
  648. if (handleEsc()) { return true; }
  649. var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
  650. var keysAreChars = key.length == 1;
  651. var match = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
  652. // Need to check all key substrings in insert mode.
  653. while (keys.length > 1 && match.type != 'full') {
  654. var keys = vim.inputState.keyBuffer = keys.slice(1);
  655. var thisMatch = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
  656. if (thisMatch.type != 'none') { match = thisMatch; }
  657. }
  658. if (match.type == 'none') { clearInputState(cm); return false; }
  659. else if (match.type == 'partial') {
  660. if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
  661. lastInsertModeKeyTimer = window.setTimeout(
  662. function() { if (vim.insertMode && vim.inputState.keyBuffer) { clearInputState(cm); } },
  663. getOption('insertModeEscKeysTimeout'));
  664. return !keysAreChars;
  665. }
  666. if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
  667. if (keysAreChars) {
  668. var here = cm.getCursor();
  669. cm.replaceRange('', offsetCursor(here, 0, -(keys.length - 1)), here, '+input');
  670. }
  671. clearInputState(cm);
  672. var command = match.command;
  673. if (command.type == 'keyToKey') {
  674. doKeyToKey(command.toKeys);
  675. } else {
  676. commandDispatcher.processCommand(cm, vim, command);
  677. }
  678. return true;
  679. }
  680. function handleKeyNonInsertMode() {
  681. if (handleMacroRecording() || handleEsc()) { return true; };
  682. var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
  683. if (/^[1-9]\d*$/.test(keys)) { return true; }
  684. var keysMatcher = /^(\d*)(.*)$/.exec(keys);
  685. if (!keysMatcher) { clearInputState(cm); return false; }
  686. var context = vim.visualMode ? 'visual' :
  687. 'normal';
  688. var match = commandDispatcher.matchCommand(keysMatcher[2] || keysMatcher[1], defaultKeymap, vim.inputState, context);
  689. if (match.type == 'none') { clearInputState(cm); return false; }
  690. else if (match.type == 'partial') { return true; }
  691. vim.inputState.keyBuffer = '';
  692. var command = match.command;
  693. var keysMatcher = /^(\d*)(.*)$/.exec(keys);
  694. if (keysMatcher[1] && keysMatcher[1] != '0') {
  695. vim.inputState.pushRepeatDigit(keysMatcher[1]);
  696. }
  697. if (command.type == 'keyToKey') {
  698. doKeyToKey(command.toKeys);
  699. } else {
  700. commandDispatcher.processCommand(cm, vim, command);
  701. }
  702. return true;
  703. }
  704. return cm.operation(function() {
  705. cm.curOp.isVimOp = true;
  706. try {
  707. if (vim.insertMode) { return handleKeyInsertMode(); }
  708. else { return handleKeyNonInsertMode(); }
  709. } catch (e) {
  710. // clear VIM state in case it's in a bad state.
  711. cm.state.vim = undefined;
  712. maybeInitVimState(cm);
  713. throw e;
  714. }
  715. });
  716. },
  717. handleEx: function(cm, input) {
  718. exCommandDispatcher.processCommand(cm, input);
  719. }
  720. };
  721. // Represents the current input state.
  722. function InputState() {
  723. this.prefixRepeat = [];
  724. this.motionRepeat = [];
  725. this.operator = null;
  726. this.operatorArgs = null;
  727. this.motion = null;
  728. this.motionArgs = null;
  729. this.keyBuffer = []; // For matching multi-key commands.
  730. this.registerName = null; // Defaults to the unnamed register.
  731. }
  732. InputState.prototype.pushRepeatDigit = function(n) {
  733. if (!this.operator) {
  734. this.prefixRepeat = this.prefixRepeat.concat(n);
  735. } else {
  736. this.motionRepeat = this.motionRepeat.concat(n);
  737. }
  738. };
  739. InputState.prototype.getRepeat = function() {
  740. var repeat = 0;
  741. if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) {
  742. repeat = 1;
  743. if (this.prefixRepeat.length > 0) {
  744. repeat *= parseInt(this.prefixRepeat.join(''), 10);
  745. }
  746. if (this.motionRepeat.length > 0) {
  747. repeat *= parseInt(this.motionRepeat.join(''), 10);
  748. }
  749. }
  750. return repeat;
  751. };
  752. function clearInputState(cm, reason) {
  753. cm.state.vim.inputState = new InputState();
  754. CodeMirror.signal(cm, 'vim-command-done', reason);
  755. }
  756. /*
  757. * Register stores information about copy and paste registers. Besides
  758. * text, a register must store whether it is linewise (i.e., when it is
  759. * pasted, should it insert itself into a new line, or should the text be
  760. * inserted at the cursor position.)
  761. */
  762. function Register(text, linewise, blockwise) {
  763. this.clear();
  764. this.keyBuffer = [text || ''];
  765. this.insertModeChanges = [];
  766. this.searchQueries = [];
  767. this.linewise = !!linewise;
  768. this.blockwise = !!blockwise;
  769. }
  770. Register.prototype = {
  771. setText: function(text, linewise, blockwise) {
  772. this.keyBuffer = [text || ''];
  773. this.linewise = !!linewise;
  774. this.blockwise = !!blockwise;
  775. },
  776. pushText: function(text, linewise) {
  777. // if this register has ever been set to linewise, use linewise.
  778. if (linewise) {
  779. if (!this.linewise) {
  780. this.keyBuffer.push('\n');
  781. }
  782. this.linewise = true;
  783. }
  784. this.keyBuffer.push(text);
  785. },
  786. pushInsertModeChanges: function(changes) {
  787. this.insertModeChanges.push(createInsertModeChanges(changes));
  788. },
  789. pushSearchQuery: function(query) {
  790. this.searchQueries.push(query);
  791. },
  792. clear: function() {
  793. this.keyBuffer = [];
  794. this.insertModeChanges = [];
  795. this.searchQueries = [];
  796. this.linewise = false;
  797. },
  798. toString: function() {
  799. return this.keyBuffer.join('');
  800. }
  801. };
  802. /*
  803. * vim registers allow you to keep many independent copy and paste buffers.
  804. * See http://usevim.com/2012/04/13/registers/ for an introduction.
  805. *
  806. * RegisterController keeps the state of all the registers. An initial
  807. * state may be passed in. The unnamed register '"' will always be
  808. * overridden.
  809. */
  810. function RegisterController(registers) {
  811. this.registers = registers;
  812. this.unnamedRegister = registers['"'] = new Register();
  813. registers['.'] = new Register();
  814. registers[':'] = new Register();
  815. registers['/'] = new Register();
  816. }
  817. RegisterController.prototype = {
  818. pushText: function(registerName, operator, text, linewise, blockwise) {
  819. if (linewise && text.charAt(0) == '\n') {
  820. text = text.slice(1) + '\n';
  821. }
  822. if (linewise && text.charAt(text.length - 1) !== '\n'){
  823. text += '\n';
  824. }
  825. // Lowercase and uppercase registers refer to the same register.
  826. // Uppercase just means append.
  827. var register = this.isValidRegister(registerName) ?
  828. this.getRegister(registerName) : null;
  829. // if no register/an invalid register was specified, things go to the
  830. // default registers
  831. if (!register) {
  832. switch (operator) {
  833. case 'yank':
  834. // The 0 register contains the text from the most recent yank.
  835. this.registers['0'] = new Register(text, linewise, blockwise);
  836. break;
  837. case 'delete':
  838. case 'change':
  839. if (text.indexOf('\n') == -1) {
  840. // Delete less than 1 line. Update the small delete register.
  841. this.registers['-'] = new Register(text, linewise);
  842. } else {
  843. // Shift down the contents of the numbered registers and put the
  844. // deleted text into register 1.
  845. this.shiftNumericRegisters_();
  846. this.registers['1'] = new Register(text, linewise);
  847. }
  848. break;
  849. }
  850. // Make sure the unnamed register is set to what just happened
  851. this.unnamedRegister.setText(text, linewise, blockwise);
  852. return;
  853. }
  854. // If we've gotten to this point, we've actually specified a register
  855. var append = isUpperCase(registerName);
  856. if (append) {
  857. register.pushText(text, linewise);
  858. } else {
  859. register.setText(text, linewise, blockwise);
  860. }
  861. // The unnamed register always has the same value as the last used
  862. // register.
  863. this.unnamedRegister.setText(register.toString(), linewise);
  864. },
  865. // Gets the register named @name. If one of @name doesn't already exist,
  866. // create it. If @name is invalid, return the unnamedRegister.
  867. getRegister: function(name) {
  868. if (!this.isValidRegister(name)) {
  869. return this.unnamedRegister;
  870. }
  871. name = name.toLowerCase();
  872. if (!this.registers[name]) {
  873. this.registers[name] = new Register();
  874. }
  875. return this.registers[name];
  876. },
  877. isValidRegister: function(name) {
  878. return name && inArray(name, validRegisters);
  879. },
  880. shiftNumericRegisters_: function() {
  881. for (var i = 9; i >= 2; i--) {
  882. this.registers[i] = this.getRegister('' + (i - 1));
  883. }
  884. }
  885. };
  886. function HistoryController() {
  887. this.historyBuffer = [];
  888. this.iterator;
  889. this.initialPrefix = null;
  890. }
  891. HistoryController.prototype = {
  892. // the input argument here acts a user entered prefix for a small time
  893. // until we start autocompletion in which case it is the autocompleted.
  894. nextMatch: function (input, up) {
  895. var historyBuffer = this.historyBuffer;
  896. var dir = up ? -1 : 1;
  897. if (this.initialPrefix === null) this.initialPrefix = input;
  898. for (var i = this.iterator + dir; up ? i >= 0 : i < historyBuffer.length; i+= dir) {
  899. var element = historyBuffer[i];
  900. for (var j = 0; j <= element.length; j++) {
  901. if (this.initialPrefix == element.substring(0, j)) {
  902. this.iterator = i;
  903. return element;
  904. }
  905. }
  906. }
  907. // should return the user input in case we reach the end of buffer.
  908. if (i >= historyBuffer.length) {
  909. this.iterator = historyBuffer.length;
  910. return this.initialPrefix;
  911. }
  912. // return the last autocompleted query or exCommand as it is.
  913. if (i < 0 ) return input;
  914. },
  915. pushInput: function(input) {
  916. var index = this.historyBuffer.indexOf(input);
  917. if (index > -1) this.historyBuffer.splice(index, 1);
  918. if (input.length) this.historyBuffer.push(input);
  919. },
  920. reset: function() {
  921. this.initialPrefix = null;
  922. this.iterator = this.historyBuffer.length;
  923. }
  924. };
  925. var commandDispatcher = {
  926. matchCommand: function(keys, keyMap, inputState, context) {
  927. var matches = commandMatches(keys, keyMap, context, inputState);
  928. if (!matches.full && !matches.partial) {
  929. return {type: 'none'};
  930. } else if (!matches.full && matches.partial) {
  931. return {type: 'partial'};
  932. }
  933. var bestMatch;
  934. for (var i = 0; i < matches.full.length; i++) {
  935. var match = matches.full[i];
  936. if (!bestMatch) {
  937. bestMatch = match;
  938. }
  939. }
  940. if (bestMatch.keys.slice(-11) == '<character>') {
  941. inputState.selectedCharacter = lastChar(keys);
  942. }
  943. return {type: 'full', command: bestMatch};
  944. },
  945. processCommand: function(cm, vim, command) {
  946. vim.inputState.repeatOverride = command.repeatOverride;
  947. switch (command.type) {
  948. case 'motion':
  949. this.processMotion(cm, vim, command);
  950. break;
  951. case 'operator':
  952. this.processOperator(cm, vim, command);
  953. break;
  954. case 'operatorMotion':
  955. this.processOperatorMotion(cm, vim, command);
  956. break;
  957. case 'action':
  958. this.processAction(cm, vim, command);
  959. break;
  960. case 'search':
  961. this.processSearch(cm, vim, command);
  962. clearInputState(cm);
  963. break;
  964. case 'ex':
  965. case 'keyToEx':
  966. this.processEx(cm, vim, command);
  967. clearInputState(cm);
  968. break;
  969. default:
  970. break;
  971. }
  972. },
  973. processMotion: function(cm, vim, command) {
  974. vim.inputState.motion = command.motion;
  975. vim.inputState.motionArgs = copyArgs(command.motionArgs);
  976. this.evalInput(cm, vim);
  977. },
  978. processOperator: function(cm, vim, command) {
  979. var inputState = vim.inputState;
  980. if (inputState.operator) {
  981. if (inputState.operator == command.operator) {
  982. // Typing an operator twice like 'dd' makes the operator operate
  983. // linewise
  984. inputState.motion = 'expandToLine';
  985. inputState.motionArgs = { linewise: true };
  986. this.evalInput(cm, vim);
  987. return;
  988. } else {
  989. // 2 different operators in a row doesn't make sense.
  990. clearInputState(cm);
  991. }
  992. }
  993. inputState.operator = command.operator;
  994. inputState.operatorArgs = copyArgs(command.operatorArgs);
  995. if (vim.visualMode) {
  996. // Operating on a selection in visual mode. We don't need a motion.
  997. this.evalInput(cm, vim);
  998. }
  999. },
  1000. processOperatorMotion: function(cm, vim, command) {
  1001. var visualMode = vim.visualMode;
  1002. var operatorMotionArgs = copyArgs(command.operatorMotionArgs);
  1003. if (operatorMotionArgs) {
  1004. // Operator motions may have special behavior in visual mode.
  1005. if (visualMode && operatorMotionArgs.visualLine) {
  1006. vim.visualLine = true;
  1007. }
  1008. }
  1009. this.processOperator(cm, vim, command);
  1010. if (!visualMode) {
  1011. this.processMotion(cm, vim, command);
  1012. }
  1013. },
  1014. processAction: function(cm, vim, command) {
  1015. var inputState = vim.inputState;
  1016. var repeat = inputState.getRepeat();
  1017. var repeatIsExplicit = !!repeat;
  1018. var actionArgs = copyArgs(command.actionArgs) || {};
  1019. if (inputState.selectedCharacter) {
  1020. actionArgs.selectedCharacter = inputState.selectedCharacter;
  1021. }
  1022. // Actions may or may not have motions and operators. Do these first.
  1023. if (command.operator) {
  1024. this.processOperator(cm, vim, command);
  1025. }
  1026. if (command.motion) {
  1027. this.processMotion(cm, vim, command);
  1028. }
  1029. if (command.motion || command.operator) {
  1030. this.evalInput(cm, vim);
  1031. }
  1032. actionArgs.repeat = repeat || 1;
  1033. actionArgs.repeatIsExplicit = repeatIsExplicit;
  1034. actionArgs.registerName = inputState.registerName;
  1035. clearInputState(cm);
  1036. vim.lastMotion = null;
  1037. if (command.isEdit) {
  1038. this.recordLastEdit(vim, inputState, command);
  1039. }
  1040. actions[command.action](cm, actionArgs, vim);
  1041. },
  1042. processSearch: function(cm, vim, command) {
  1043. if (!cm.getSearchCursor) {
  1044. // Search depends on SearchCursor.
  1045. return;
  1046. }
  1047. var forward = command.searchArgs.forward;
  1048. var wholeWordOnly = command.searchArgs.wholeWordOnly;
  1049. getSearchState(cm).setReversed(!forward);
  1050. var promptPrefix = (forward) ? '/' : '?';
  1051. var originalQuery = getSearchState(cm).getQuery();
  1052. var originalScrollPos = cm.getScrollInfo();
  1053. function handleQuery(query, ignoreCase, smartCase) {
  1054. vimGlobalState.searchHistoryController.pushInput(query);
  1055. vimGlobalState.searchHistoryController.reset();
  1056. try {
  1057. updateSearchQuery(cm, query, ignoreCase, smartCase);
  1058. } catch (e) {
  1059. showConfirm(cm, 'Invalid regex: ' + query);
  1060. return;
  1061. }
  1062. commandDispatcher.processMotion(cm, vim, {
  1063. type: 'motion',
  1064. motion: 'findNext',
  1065. motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist }
  1066. });
  1067. }
  1068. function onPromptClose(query) {
  1069. cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
  1070. handleQuery(query, true /** ignoreCase */, true /** smartCase */);
  1071. var macroModeState = vimGlobalState.macroModeState;
  1072. if (macroModeState.isRecording) {
  1073. logSearchQuery(macroModeState, query);
  1074. }
  1075. }
  1076. function onPromptKeyUp(e, query, close) {
  1077. var keyName = CodeMirror.keyName(e), up;
  1078. if (keyName == 'Up' || keyName == 'Down') {
  1079. up = keyName == 'Up' ? true : false;
  1080. query = vimGlobalState.searchHistoryController.nextMatch(query, up) || '';
  1081. close(query);
  1082. } else {
  1083. if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')
  1084. vimGlobalState.searchHistoryController.reset();
  1085. }
  1086. var parsedQuery;
  1087. try {
  1088. parsedQuery = updateSearchQuery(cm, query,
  1089. true /** ignoreCase */, true /** smartCase */);
  1090. } catch (e) {
  1091. // Swallow bad regexes for incremental search.
  1092. }
  1093. if (parsedQuery) {
  1094. cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30);
  1095. } else {
  1096. clearSearchHighlight(cm);
  1097. cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
  1098. }
  1099. }
  1100. function onPromptKeyDown(e, query, close) {
  1101. var keyName = CodeMirror.keyName(e);
  1102. if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[') {
  1103. vimGlobalState.searchHistoryController.pushInput(query);
  1104. vimGlobalState.searchHistoryController.reset();
  1105. updateSearchQuery(cm, originalQuery);
  1106. clearSearchHighlight(cm);
  1107. cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
  1108. CodeMirror.e_stop(e);
  1109. close();
  1110. cm.focus();
  1111. }
  1112. }
  1113. switch (command.searchArgs.querySrc) {
  1114. case 'prompt':
  1115. var macroModeState = vimGlobalState.macroModeState;
  1116. if (macroModeState.isPlaying) {
  1117. var query = macroModeState.replaySearchQueries.shift();
  1118. handleQuery(query, true /** ignoreCase */, false /** smartCase */);
  1119. } else {
  1120. showPrompt(cm, {
  1121. onClose: onPromptClose,
  1122. prefix: promptPrefix,
  1123. desc: searchPromptDesc,
  1124. onKeyUp: onPromptKeyUp,
  1125. onKeyDown: onPromptKeyDown
  1126. });
  1127. }
  1128. break;
  1129. case 'wordUnderCursor':
  1130. var word = expandWordUnderCursor(cm, false /** inclusive */,
  1131. true /** forward */, false /** bigWord */,
  1132. true /** noSymbol */);
  1133. var isKeyword = true;
  1134. if (!word) {
  1135. word = expandWordUnderCursor(cm, false /** inclusive */,
  1136. true /** forward */, false /** bigWord */,
  1137. false /** noSymbol */);
  1138. isKeyword = false;
  1139. }
  1140. if (!word) {
  1141. return;
  1142. }
  1143. var query = cm.getLine(word.start.line).substring(word.start.ch,
  1144. word.end.ch);
  1145. if (isKeyword && wholeWordOnly) {
  1146. query = '\\b' + query + '\\b';
  1147. } else {
  1148. query = escapeRegex(query);
  1149. }
  1150. // cachedCursor is used to save the old position of the cursor
  1151. // when * or # causes vim to seek for the nearest word and shift
  1152. // the cursor before entering the motion.
  1153. vimGlobalState.jumpList.cachedCursor = cm.getCursor();
  1154. cm.setCursor(word.start);
  1155. handleQuery(query, true /** ignoreCase */, false /** smartCase */);
  1156. break;
  1157. }
  1158. },
  1159. processEx: function(cm, vim, command) {
  1160. function onPromptClose(input) {
  1161. // Give the prompt some time to close so that if processCommand shows
  1162. // an error, the elements don't overlap.
  1163. vimGlobalState.exCommandHistoryController.pushInput(input);
  1164. vimGlobalState.exCommandHistoryController.reset();
  1165. exCommandDispatcher.processCommand(cm, input);
  1166. }
  1167. function onPromptKeyDown(e, input, close) {
  1168. var keyName = CodeMirror.keyName(e), up;
  1169. if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[') {
  1170. vimGlobalState.exCommandHistoryController.pushInput(input);
  1171. vimGlobalState.exCommandHistoryController.reset();
  1172. CodeMirror.e_stop(e);
  1173. close();
  1174. cm.focus();
  1175. }
  1176. if (keyName == 'Up' || keyName == 'Down') {
  1177. up = keyName == 'Up' ? true : false;
  1178. input = vimGlobalState.exCommandHistoryController.nextMatch(input, up) || '';
  1179. close(input);
  1180. } else {
  1181. if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')
  1182. vimGlobalState.exCommandHistoryController.reset();
  1183. }
  1184. }
  1185. if (command.type == 'keyToEx') {
  1186. // Handle user defined Ex to Ex mappings
  1187. exCommandDispatcher.processCommand(cm, command.exArgs.input);
  1188. } else {
  1189. if (vim.visualMode) {
  1190. showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>',
  1191. onKeyDown: onPromptKeyDown});
  1192. } else {
  1193. showPrompt(cm, { onClose: onPromptClose, prefix: ':',
  1194. onKeyDown: onPromptKeyDown});
  1195. }
  1196. }
  1197. },
  1198. evalInput: function(cm, vim) {
  1199. // If the motion comand is set, execute both the operator and motion.
  1200. // Otherwise return.
  1201. var inputState = vim.inputState;
  1202. var motion = inputState.motion;
  1203. var motionArgs = inputState.motionArgs || {};
  1204. var operator = inputState.operator;
  1205. var operatorArgs = inputState.operatorArgs || {};
  1206. var registerName = inputState.registerName;
  1207. var sel = vim.sel;
  1208. // TODO: Make sure cm and vim selections are identical outside visual mode.
  1209. var origHead = copyCursor(vim.visualMode ? sel.head: cm.getCursor('head'));
  1210. var origAnchor = copyCursor(vim.visualMode ? sel.anchor : cm.getCursor('anchor'));
  1211. var oldHead = copyCursor(origHead);
  1212. var oldAnchor = copyCursor(origAnchor);
  1213. var newHead, newAnchor;
  1214. var repeat;
  1215. if (operator) {
  1216. this.recordLastEdit(vim, inputState);
  1217. }
  1218. if (inputState.repeatOverride !== undefined) {
  1219. // If repeatOverride is specified, that takes precedence over the
  1220. // input state's repeat. Used by Ex mode and can be user defined.
  1221. repeat = inputState.repeatOverride;
  1222. } else {
  1223. repeat = inputState.getRepeat();
  1224. }
  1225. if (repeat > 0 && motionArgs.explicitRepeat) {
  1226. motionArgs.repeatIsExplicit = true;
  1227. } else if (motionArgs.noRepeat ||
  1228. (!motionArgs.explicitRepeat && repeat === 0)) {
  1229. repeat = 1;
  1230. motionArgs.repeatIsExplicit = false;
  1231. }
  1232. if (inputState.selectedCharacter) {
  1233. // If there is a character input, stick it in all of the arg arrays.
  1234. motionArgs.selectedCharacter = operatorArgs.selectedCharacter =
  1235. inputState.selectedCharacter;
  1236. }
  1237. motionArgs.repeat = repeat;
  1238. clearInputState(cm);
  1239. if (motion) {
  1240. var motionResult = motions[motion](cm, origHead, motionArgs, vim);
  1241. vim.lastMotion = motions[motion];
  1242. if (!motionResult) {
  1243. return;
  1244. }
  1245. if (motionArgs.toJumplist) {
  1246. var jumpList = vimGlobalState.jumpList;
  1247. // if the current motion is # or *, use cachedCursor
  1248. var cachedCursor = jumpList.cachedCursor;
  1249. if (cachedCursor) {
  1250. recordJumpPosition(cm, cachedCursor, motionResult);
  1251. delete jumpList.cachedCursor;
  1252. } else {
  1253. recordJumpPosition(cm, origHead, motionResult);
  1254. }
  1255. }
  1256. if (motionResult instanceof Array) {
  1257. newAnchor = motionResult[0];
  1258. newHead = motionResult[1];
  1259. } else {
  1260. newHead = motionResult;
  1261. }
  1262. // TODO: Handle null returns from motion commands better.
  1263. if (!newHead) {
  1264. newHead = copyCursor(origHead);
  1265. }
  1266. if (vim.visualMode) {
  1267. newHead = clipCursorToContent(cm, newHead, vim.visualBlock);
  1268. if (newAnchor) {
  1269. newAnchor = clipCursorToContent(cm, newAnchor, true);
  1270. }
  1271. newAnchor = newAnchor || oldAnchor;
  1272. sel.anchor = newAnchor;
  1273. sel.head = newHead;
  1274. updateCmSelection(cm);
  1275. updateMark(cm, vim, '<',
  1276. cursorIsBefore(newAnchor, newHead) ? newAnchor
  1277. : newHead);
  1278. updateMark(cm, vim, '>',
  1279. cursorIsBefore(newAnchor, newHead) ? newHead
  1280. : newAnchor);
  1281. } else if (!operator) {
  1282. newHead = clipCursorToContent(cm, newHead);
  1283. cm.setCursor(newHead.line, newHead.ch);
  1284. }
  1285. }
  1286. if (operator) {
  1287. if (operatorArgs.lastSel) {
  1288. // Replaying a visual mode operation
  1289. newAnchor = oldAnchor;
  1290. var lastSel = operatorArgs.lastSel;
  1291. var lineOffset = Math.abs(lastSel.head.line - lastSel.anchor.line);
  1292. var chOffset = Math.abs(lastSel.head.ch - lastSel.anchor.ch);
  1293. if (lastSel.visualLine) {
  1294. // Linewise Visual mode: The same number of lines.
  1295. newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
  1296. } else if (lastSel.visualBlock) {
  1297. // Blockwise Visual mode: The same number of lines and columns.
  1298. newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch + chOffset);
  1299. } else if (lastSel.head.line == lastSel.anchor.line) {
  1300. // Normal Visual mode within one line: The same number of characters.
  1301. newHead = Pos(oldAnchor.line, oldAnchor.ch + chOffset);
  1302. } else {
  1303. // Normal Visual mode with several lines: The same number of lines, in the
  1304. // last line the same number of characters as in the last line the last time.
  1305. newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
  1306. }
  1307. vim.visualMode = true;
  1308. vim.visualLine = lastSel.visualLine;
  1309. vim.visualBlock = lastSel.visualBlock;
  1310. sel = vim.sel = {
  1311. anchor: newAnchor,
  1312. head: newHead
  1313. };
  1314. updateCmSelection(cm);
  1315. } else if (vim.visualMode) {
  1316. operatorArgs.lastSel = {
  1317. anchor: copyCursor(sel.anchor),
  1318. head: copyCursor(sel.head),
  1319. visualBlock: vim.visualBlock,
  1320. visualLine: vim.visualLine
  1321. };
  1322. }
  1323. var curStart, curEnd, linewise, mode;
  1324. var cmSel;
  1325. if (vim.visualMode) {
  1326. // Init visual op
  1327. curStart = cursorMin(sel.head, sel.anchor);
  1328. curEnd = cursorMax(sel.head, sel.anchor);
  1329. linewise = vim.visualLine || operatorArgs.linewise;
  1330. mode = vim.visualBlock ? 'block' :
  1331. linewise ? 'line' :
  1332. 'char';
  1333. cmSel = makeCmSelection(cm, {
  1334. anchor: curStart,
  1335. head: curEnd
  1336. }, mode);
  1337. if (linewise) {
  1338. var ranges = cmSel.ranges;
  1339. if (mode == 'block') {
  1340. // Linewise operators in visual block mode extend to end of line
  1341. for (var i = 0; i < ranges.length; i++) {
  1342. ranges[i].head.ch = lineLength(cm, ranges[i].head.line);
  1343. }
  1344. } else if (mode == 'line') {
  1345. ranges[0].head = Pos(ranges[0].head.line + 1, 0);
  1346. }
  1347. }
  1348. } else {
  1349. // Init motion op
  1350. curStart = copyCursor(newAnchor || oldAnchor);
  1351. curEnd = copyCursor(newHead || oldHead);
  1352. if (cursorIsBefore(curEnd, curStart)) {
  1353. var tmp = curStart;
  1354. curStart = curEnd;
  1355. curEnd = tmp;
  1356. }
  1357. linewise = motionArgs.linewise || operatorArgs.linewise;
  1358. if (linewise) {
  1359. // Expand selection to entire line.
  1360. expandSelectionToLine(cm, curStart, curEnd);
  1361. } else if (motionArgs.forward) {
  1362. // Clip to trailing newlines only if the motion goes forward.
  1363. clipToLine(cm, curStart, curEnd);
  1364. }
  1365. mode = 'char';
  1366. var exclusive = !motionArgs.inclusive || linewise;
  1367. cmSel = makeCmSelection(cm, {
  1368. anchor: curStart,
  1369. head: curEnd
  1370. }, mode, exclusive);
  1371. }
  1372. cm.setSelections(cmSel.ranges, cmSel.primary);
  1373. vim.lastMotion = null;
  1374. operatorArgs.repeat = repeat; // For indent in visual mode.
  1375. operatorArgs.registerName = registerName;
  1376. // Keep track of linewise as it affects how paste and change behave.
  1377. operatorArgs.linewise = linewise;
  1378. var operatorMoveTo = operators[operator](
  1379. cm, operatorArgs, cmSel.ranges, oldAnchor, newHead);
  1380. if (vim.visualMode) {
  1381. exitVisualMode(cm);
  1382. }
  1383. if (operatorMoveTo) {
  1384. cm.setCursor(operatorMoveTo);
  1385. }
  1386. }
  1387. },
  1388. recordLastEdit: function(vim, inputState, actionCommand) {
  1389. var macroModeState = vimGlobalState.macroModeState;
  1390. if (macroModeState.isPlaying) { return; }
  1391. vim.lastEditInputState = inputState;
  1392. vim.lastEditActionCommand = actionCommand;
  1393. macroModeState.lastInsertModeChanges.changes = [];
  1394. macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false;
  1395. }
  1396. };
  1397. /**
  1398. * typedef {Object{line:number,ch:number}} Cursor An object containing the
  1399. * position of the cursor.
  1400. */
  1401. // All of the functions below return Cursor objects.
  1402. var motions = {
  1403. moveToTopLine: function(cm, _head, motionArgs) {
  1404. var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;
  1405. return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
  1406. },
  1407. moveToMiddleLine: function(cm) {
  1408. var range = getUserVisibleLines(cm);
  1409. var line = Math.floor((range.top + range.bottom) * 0.5);
  1410. return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
  1411. },
  1412. moveToBottomLine: function(cm, _head, motionArgs) {
  1413. var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;
  1414. return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
  1415. },
  1416. expandToLine: function(_cm, head, motionArgs) {
  1417. // Expands forward to end of line, and then to next line if repeat is
  1418. // >1. Does not handle backward motion!
  1419. var cur = head;
  1420. return Pos(cur.line + motionArgs.repeat - 1, Infinity);
  1421. },
  1422. findNext: function(cm, _head, motionArgs) {
  1423. var state = getSearchState(cm);
  1424. var query = state.getQuery();
  1425. if (!query) {
  1426. return;
  1427. }
  1428. var prev = !motionArgs.forward;
  1429. // If search is initiated with ? instead of /, negate direction.
  1430. prev = (state.isReversed()) ? !prev : prev;
  1431. highlightSearchMatches(cm, query);
  1432. return findNext(cm, prev/** prev */, query, motionArgs.repeat);
  1433. },
  1434. goToMark: function(cm, _head, motionArgs, vim) {
  1435. var mark = vim.marks[motionArgs.selectedCharacter];
  1436. if (mark) {
  1437. var pos = mark.find();
  1438. return motionArgs.linewise ? { line: pos.line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line)) } : pos;
  1439. }
  1440. return null;
  1441. },
  1442. moveToOtherHighlightedEnd: function(cm, _head, motionArgs, vim) {
  1443. if (vim.visualBlock && motionArgs.sameLine) {
  1444. var sel = vim.sel;
  1445. return [
  1446. clipCursorToContent(cm, Pos(sel.anchor.line, sel.head.ch)),
  1447. clipCursorToContent(cm, Pos(sel.head.line, sel.anchor.ch))
  1448. ];
  1449. } else {
  1450. return ([vim.sel.head, vim.sel.anchor]);
  1451. }
  1452. },
  1453. jumpToMark: function(cm, head, motionArgs, vim) {
  1454. var best = head;
  1455. for (var i = 0; i < motionArgs.repeat; i++) {
  1456. var cursor = best;
  1457. for (var key in vim.marks) {
  1458. if (!isLowerCase(key)) {
  1459. continue;
  1460. }
  1461. var mark = vim.marks[key].find();
  1462. var isWrongDirection = (motionArgs.forward) ?
  1463. cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark);
  1464. if (isWrongDirection) {
  1465. continue;
  1466. }
  1467. if (motionArgs.linewise && (mark.line == cursor.line)) {
  1468. continue;
  1469. }
  1470. var equal = cursorEqual(cursor, best);
  1471. var between = (motionArgs.forward) ?
  1472. cursorIsBetween(cursor, mark, best) :
  1473. cursorIsBetween(best, mark, cursor);
  1474. if (equal || between) {
  1475. best = mark;
  1476. }
  1477. }
  1478. }
  1479. if (motionArgs.linewise) {
  1480. // Vim places the cursor on the first non-whitespace character of
  1481. // the line if there is one, else it places the cursor at the end
  1482. // of the line, regardless of whether a mark was found.
  1483. best = Pos(best.line, findFirstNonWhiteSpaceCharacter(cm.getLine(best.line)));
  1484. }
  1485. return best;
  1486. },
  1487. moveByCharacters: function(_cm, head, motionArgs) {
  1488. var cur = head;
  1489. var repeat = motionArgs.repeat;
  1490. var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;
  1491. return Pos(cur.line, ch);
  1492. },
  1493. moveByLines: function(cm, head, motionArgs, vim) {
  1494. var cur = head;
  1495. var endCh = cur.ch;
  1496. // Depending what our last motion was, we may want to do different
  1497. // things. If our last motion was moving vertically, we want to
  1498. // preserve the HPos from our last horizontal move. If our last motion
  1499. // was going to the end of a line, moving vertically we should go to
  1500. // the end of the line, etc.
  1501. switch (vim.lastMotion) {
  1502. case this.moveByLines:
  1503. case this.moveByDisplayLines:
  1504. case this.moveByScroll:
  1505. case this.moveToColumn:
  1506. case this.moveToEol:
  1507. endCh = vim.lastHPos;
  1508. break;
  1509. default:
  1510. vim.lastHPos = endCh;
  1511. }
  1512. var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0);
  1513. var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat;
  1514. var first = cm.firstLine();
  1515. var last = cm.lastLine();
  1516. // Vim cancels linewise motions that start on an edge and move beyond
  1517. // that edge. It does not cancel motions that do not start on an edge.
  1518. if ((line < first && cur.line == first) ||
  1519. (line > last && cur.line == last)) {
  1520. return;
  1521. }
  1522. if (motionArgs.toFirstChar){
  1523. endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));
  1524. vim.lastHPos = endCh;
  1525. }
  1526. vim.lastHSPos = cm.charCoords(Pos(line, endCh),'div').left;
  1527. return Pos(line, endCh);
  1528. },
  1529. moveByDisplayLines: function(cm, head, motionArgs, vim) {
  1530. var cur = head;
  1531. switch (vim.lastMotion) {
  1532. case this.moveByDisplayLines:
  1533. case this.moveByScroll:
  1534. case this.moveByLines:
  1535. case this.moveToColumn:
  1536. case this.moveToEol:
  1537. break;
  1538. default:
  1539. vim.lastHSPos = cm.charCoords(cur,'div').left;
  1540. }
  1541. var repeat = motionArgs.repeat;
  1542. var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos);
  1543. if (res.hitSide) {
  1544. if (motionArgs.forward) {
  1545. var lastCharCoords = cm.charCoords(res, 'div');
  1546. var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos };
  1547. var res = cm.coordsChar(goalCoords, 'div');
  1548. } else {
  1549. var resCoords = cm.charCoords(Pos(cm.firstLine(), 0), 'div');
  1550. resCoords.left = vim.lastHSPos;
  1551. res = cm.coordsChar(resCoords, 'div');
  1552. }
  1553. }
  1554. vim.lastHPos = res.ch;
  1555. return res;
  1556. },
  1557. moveByPage: function(cm, head, motionArgs) {
  1558. // CodeMirror only exposes functions that move the cursor page down, so
  1559. // doing this bad hack to move the cursor and move it back. evalInput
  1560. // will move the cursor to where it should be in the end.
  1561. var curStart = head;
  1562. var repeat = motionArgs.repeat;
  1563. return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page');
  1564. },
  1565. moveByParagraph: function(cm, head, motionArgs) {
  1566. var line = head.line;
  1567. var repeat = motionArgs.repeat;
  1568. var inc = motionArgs.forward ? 1 : -1;
  1569. for (var i = 0; i < repeat; i++) {
  1570. if ((!motionArgs.forward && line === cm.firstLine() ) ||
  1571. (motionArgs.forward && line == cm.lastLine())) {
  1572. break;
  1573. }
  1574. line += inc;
  1575. while (line !== cm.firstLine() && line != cm.lastLine() && cm.getLine(line)) {
  1576. line += inc;
  1577. }
  1578. }
  1579. return Pos(line, 0);
  1580. },
  1581. moveByScroll: function(cm, head, motionArgs, vim) {
  1582. var scrollbox = cm.getScrollInfo();
  1583. var curEnd = null;
  1584. var repeat = motionArgs.repeat;
  1585. if (!repeat) {
  1586. repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
  1587. }
  1588. var orig = cm.charCoords(head, 'local');
  1589. motionArgs.repeat = repeat;
  1590. var curEnd = motions.moveByDisplayLines(cm, head, motionArgs, vim);
  1591. if (!curEnd) {
  1592. return null;
  1593. }
  1594. var dest = cm.charCoords(curEnd, 'local');
  1595. cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
  1596. return curEnd;
  1597. },
  1598. moveByWords: function(cm, head, motionArgs) {
  1599. return moveToWord(cm, head, motionArgs.repeat, !!motionArgs.forward,
  1600. !!motionArgs.wordEnd, !!motionArgs.bigWord);
  1601. },
  1602. moveTillCharacter: function(cm, _head, motionArgs) {
  1603. var repeat = motionArgs.repeat;
  1604. var curEnd = moveToCharacter(cm, repeat, motionArgs.forward,
  1605. motionArgs.selectedCharacter);
  1606. var increment = motionArgs.forward ? -1 : 1;
  1607. recordLastCharacterSearch(increment, motionArgs);
  1608. if (!curEnd) return null;
  1609. curEnd.ch += increment;
  1610. return curEnd;
  1611. },
  1612. moveToCharacter: function(cm, head, motionArgs) {
  1613. var repeat = motionArgs.repeat;
  1614. recordLastCharacterSearch(0, motionArgs);
  1615. return moveToCharacter(cm, repeat, motionArgs.forward,
  1616. motionArgs.selectedCharacter) || head;
  1617. },
  1618. moveToSymbol: function(cm, head, motionArgs) {
  1619. var repeat = motionArgs.repeat;
  1620. return findSymbol(cm, repeat, motionArgs.forward,
  1621. motionArgs.selectedCharacter) || head;
  1622. },
  1623. moveToColumn: function(cm, head, motionArgs, vim) {
  1624. var repeat = motionArgs.repeat;
  1625. // repeat is equivalent to which column we want to move to!
  1626. vim.lastHPos = repeat - 1;
  1627. vim.lastHSPos = cm.charCoords(head,'div').left;
  1628. return moveToColumn(cm, repeat);
  1629. },
  1630. moveToEol: function(cm, head, motionArgs, vim) {
  1631. var cur = head;
  1632. vim.lastHPos = Infinity;
  1633. var retval= Pos(cur.line + motionArgs.repeat - 1, Infinity);
  1634. var end=cm.clipPos(retval);
  1635. end.ch--;
  1636. vim.lastHSPos = cm.charCoords(end,'div').left;
  1637. return retval;
  1638. },
  1639. moveToFirstNonWhiteSpaceCharacter: function(cm, head) {
  1640. // Go to the start of the line where the text begins, or the end for
  1641. // whitespace-only lines
  1642. var cursor = head;
  1643. return Pos(cursor.line,
  1644. findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)));
  1645. },
  1646. moveToMatchedSymbol: function(cm, head) {
  1647. var cursor = head;
  1648. var line = cursor.line;
  1649. var ch = cursor.ch;
  1650. var lineText = cm.getLine(line);
  1651. var symbol;
  1652. do {
  1653. symbol = lineText.charAt(ch++);
  1654. if (symbol && isMatchableSymbol(symbol)) {
  1655. var style = cm.getTokenTypeAt(Pos(line, ch));
  1656. if (style !== "string" && style !== "comment") {
  1657. break;
  1658. }
  1659. }
  1660. } while (symbol);
  1661. if (symbol) {
  1662. var matched = cm.findMatchingBracket(Pos(line, ch));
  1663. return matched.to;
  1664. } else {
  1665. return cursor;
  1666. }
  1667. },
  1668. moveToStartOfLine: function(_cm, head) {
  1669. return Pos(head.line, 0);
  1670. },
  1671. moveToLineOrEdgeOfDocument: function(cm, _head, motionArgs) {
  1672. var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine();
  1673. if (motionArgs.repeatIsExplicit) {
  1674. lineNum = motionArgs.repeat - cm.getOption('firstLineNumber');
  1675. }
  1676. return Pos(lineNum,
  1677. findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)));
  1678. },
  1679. textObjectManipulation: function(cm, head, motionArgs) {
  1680. // TODO: lots of possible exceptions that can be thrown here. Try da(
  1681. // outside of a () block.
  1682. // TODO: adding <> >< to this map doesn't work, presumably because
  1683. // they're operators
  1684. var mirroredPairs = {'(': ')', ')': '(',
  1685. '{': '}', '}': '{',
  1686. '[': ']', ']': '['};
  1687. var selfPaired = {'\'': true, '"': true};
  1688. var character = motionArgs.selectedCharacter;
  1689. // 'b' refers to '()' block.
  1690. // 'B' refers to '{}' block.
  1691. if (character == 'b') {
  1692. character = '(';
  1693. } else if (character == 'B') {
  1694. character = '{';
  1695. }
  1696. // Inclusive is the difference between a and i
  1697. // TODO: Instead of using the additional text object map to perform text
  1698. // object operations, merge the map into the defaultKeyMap and use
  1699. // motionArgs to define behavior. Define separate entries for 'aw',
  1700. // 'iw', 'a[', 'i[', etc.
  1701. var inclusive = !motionArgs.textObjectInner;
  1702. var tmp;
  1703. if (mirroredPairs[character]) {
  1704. tmp = selectCompanionObject(cm, head, character, inclusive);
  1705. } else if (selfPaired[character]) {
  1706. tmp = findBeginningAndEnd(cm, head, character, inclusive);
  1707. } else if (character === 'W') {
  1708. tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
  1709. true /** bigWord */);
  1710. } else if (character === 'w') {
  1711. tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
  1712. false /** bigWord */);
  1713. } else {
  1714. // No text object defined for this, don't move.
  1715. return null;
  1716. }
  1717. if (!cm.state.vim.visualMode) {
  1718. return [tmp.start, tmp.end];
  1719. } else {
  1720. return expandSelection(cm, tmp.start, tmp.end);
  1721. }
  1722. },
  1723. repeatLastCharacterSearch: function(cm, head, motionArgs) {
  1724. var lastSearch = vimGlobalState.lastChararacterSearch;
  1725. var repeat = motionArgs.repeat;
  1726. var forward = motionArgs.forward === lastSearch.forward;
  1727. var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1);
  1728. cm.moveH(-increment, 'char');
  1729. motionArgs.inclusive = forward ? true : false;
  1730. var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);
  1731. if (!curEnd) {
  1732. cm.moveH(increment, 'char');
  1733. return head;
  1734. }
  1735. curEnd.ch += increment;
  1736. return curEnd;
  1737. }
  1738. };
  1739. function fillArray(val, times) {
  1740. var arr = [];
  1741. for (var i = 0; i < times; i++) {
  1742. arr.push(val);
  1743. }
  1744. return arr;
  1745. }
  1746. /**
  1747. * An operator acts on a text selection. It receives the list of selections
  1748. * as input. The corresponding CodeMirror selection is guaranteed to
  1749. * match the input selection.
  1750. */
  1751. var operators = {
  1752. change: function(cm, args, ranges) {
  1753. var finalHead, text;
  1754. var vim = cm.state.vim;
  1755. vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock = vim.visualBlock;
  1756. if (!vim.visualMode) {
  1757. var anchor = ranges[0].anchor,
  1758. head = ranges[0].head;
  1759. text = cm.getRange(anchor, head);
  1760. if (!isWhiteSpaceString(text)) {
  1761. // Exclude trailing whitespace if the range is not all whitespace.
  1762. var match = (/\s+$/).exec(text);
  1763. if (match) {
  1764. head = offsetCursor(head, 0, - match[0].length);
  1765. text = text.slice(0, - match[0].length);
  1766. }
  1767. }
  1768. var wasLastLine = head.line - 1 == cm.lastLine();
  1769. cm.replaceRange('', anchor, head);
  1770. if (args.linewise && !wasLastLine) {
  1771. // Push the next line back down, if there is a next line.
  1772. CodeMirror.commands.newlineAndIndent(cm);
  1773. // null ch so setCursor moves to end of line.
  1774. anchor.ch = null;
  1775. }
  1776. finalHead = anchor;
  1777. } else {
  1778. text = cm.getSelection();
  1779. var replacement = fillArray('', ranges.length);
  1780. cm.replaceSelections(replacement);
  1781. finalHead = cursorMin(ranges[0].head, ranges[0].anchor);
  1782. }
  1783. vimGlobalState.registerController.pushText(
  1784. args.registerName, 'change', text,
  1785. args.linewise, ranges.length > 1);
  1786. actions.enterInsertMode(cm, {head: finalHead}, cm.state.vim);
  1787. },
  1788. // delete is a javascript keyword.
  1789. 'delete': function(cm, args, ranges) {
  1790. var finalHead, text;
  1791. var vim = cm.state.vim;
  1792. if (!vim.visualBlock) {
  1793. var anchor = ranges[0].anchor,
  1794. head = ranges[0].head;
  1795. if (args.linewise &&
  1796. head.line != cm.firstLine() &&
  1797. anchor.line == cm.lastLine() &&
  1798. anchor.line == head.line - 1) {
  1799. // Special case for dd on last line (and first line).
  1800. if (anchor.line == cm.firstLine()) {
  1801. anchor.ch = 0;
  1802. } else {
  1803. anchor = Pos(anchor.line - 1, lineLength(cm, anchor.line - 1));
  1804. }
  1805. }
  1806. text = cm.getRange(anchor, head);
  1807. cm.replaceRange('', anchor, head);
  1808. finalHead = anchor;
  1809. if (args.linewise) {
  1810. finalHead = motions.moveToFirstNonWhiteSpaceCharacter(cm, anchor);
  1811. }
  1812. } else {
  1813. text = cm.getSelection();
  1814. var replacement = fillArray('', ranges.length);
  1815. cm.replaceSelections(replacement);
  1816. finalHead = ranges[0].anchor;
  1817. }
  1818. vimGlobalState.registerController.pushText(
  1819. args.registerName, 'delete', text,
  1820. args.linewise, vim.visualBlock);
  1821. return finalHead;
  1822. },
  1823. indent: function(cm, args, ranges) {
  1824. var vim = cm.state.vim;
  1825. var startLine = ranges[0].anchor.line;
  1826. var endLine = vim.visualBlock ?
  1827. ranges[ranges.length - 1].anchor.line :
  1828. ranges[0].head.line;
  1829. // In visual mode, n> shifts the selection right n times, instead of
  1830. // shifting n lines right once.
  1831. var repeat = (vim.visualMode) ? args.repeat : 1;
  1832. if (args.linewise) {
  1833. // The only way to delete a newline is to delete until the start of
  1834. // the next line, so in linewise mode evalInput will include the next
  1835. // line. We don't want this in indent, so we go back a line.
  1836. endLine--;
  1837. }
  1838. for (var i = startLine; i <= endLine; i++) {
  1839. for (var j = 0; j < repeat; j++) {
  1840. cm.indentLine(i, args.indentRight);
  1841. }
  1842. }
  1843. return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);
  1844. },
  1845. changeCase: function(cm, args, ranges, oldAnchor, newHead) {
  1846. var selections = cm.getSelections();
  1847. var swapped = [];
  1848. var toLower = args.toLower;
  1849. for (var j = 0; j < selections.length; j++) {
  1850. var toSwap = selections[j];
  1851. var text = '';
  1852. if (toLower === true) {
  1853. text = toSwap.toLowerCase();
  1854. } else if (toLower === false) {
  1855. text = toSwap.toUpperCase();
  1856. } else {
  1857. for (var i = 0; i < toSwap.length; i++) {
  1858. var character = toSwap.charAt(i);
  1859. text += isUpperCase(character) ? character.toLowerCase() :
  1860. character.toUpperCase();
  1861. }
  1862. }
  1863. swapped.push(text);
  1864. }
  1865. cm.replaceSelections(swapped);
  1866. if (args.shouldMoveCursor){
  1867. return newHead;
  1868. } else if (!cm.state.vim.visualMode && args.linewise && ranges[0].anchor.line + 1 == ranges[0].head.line) {
  1869. return motions.moveToFirstNonWhiteSpaceCharacter(cm, oldAnchor);
  1870. } else if (args.linewise){
  1871. return oldAnchor;
  1872. } else {
  1873. return cursorMin(ranges[0].anchor, ranges[0].head);
  1874. }
  1875. },
  1876. yank: function(cm, args, ranges, oldAnchor) {
  1877. var vim = cm.state.vim;
  1878. var text = cm.getSelection();
  1879. var endPos = vim.visualMode
  1880. ? cursorMin(vim.sel.anchor, vim.sel.head, ranges[0].head, ranges[0].anchor)
  1881. : oldAnchor;
  1882. vimGlobalState.registerController.pushText(
  1883. args.registerName, 'yank',
  1884. text, args.linewise, vim.visualBlock);
  1885. return endPos;
  1886. }
  1887. };
  1888. var actions = {
  1889. jumpListWalk: function(cm, actionArgs, vim) {
  1890. if (vim.visualMode) {
  1891. return;
  1892. }
  1893. var repeat = actionArgs.repeat;
  1894. var forward = actionArgs.forward;
  1895. var jumpList = vimGlobalState.jumpList;
  1896. var mark = jumpList.move(cm, forward ? repeat : -repeat);
  1897. var markPos = mark ? mark.find() : undefined;
  1898. markPos = markPos ? markPos : cm.getCursor();
  1899. cm.setCursor(markPos);
  1900. },
  1901. scroll: function(cm, actionArgs, vim) {
  1902. if (vim.visualMode) {
  1903. return;
  1904. }
  1905. var repeat = actionArgs.repeat || 1;
  1906. var lineHeight = cm.defaultTextHeight();
  1907. var top = cm.getScrollInfo().top;
  1908. var delta = lineHeight * repeat;
  1909. var newPos = actionArgs.forward ? top + delta : top - delta;
  1910. var cursor = copyCursor(cm.getCursor());
  1911. var cursorCoords = cm.charCoords(cursor, 'local');
  1912. if (actionArgs.forward) {
  1913. if (newPos > cursorCoords.top) {
  1914. cursor.line += (newPos - cursorCoords.top) / lineHeight;
  1915. cursor.line = Math.ceil(cursor.line);
  1916. cm.setCursor(cursor);
  1917. cursorCoords = cm.charCoords(cursor, 'local');
  1918. cm.scrollTo(null, cursorCoords.top);
  1919. } else {
  1920. // Cursor stays within bounds. Just reposition the scroll window.
  1921. cm.scrollTo(null, newPos);
  1922. }
  1923. } else {
  1924. var newBottom = newPos + cm.getScrollInfo().clientHeight;
  1925. if (newBottom < cursorCoords.bottom) {
  1926. cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight;
  1927. cursor.line = Math.floor(cursor.line);
  1928. cm.setCursor(cursor);
  1929. cursorCoords = cm.charCoords(cursor, 'local');
  1930. cm.scrollTo(
  1931. null, cursorCoords.bottom - cm.getScrollInfo().clientHeight);
  1932. } else {
  1933. // Cursor stays within bounds. Just reposition the scroll window.
  1934. cm.scrollTo(null, newPos);
  1935. }
  1936. }
  1937. },
  1938. scrollToCursor: function(cm, actionArgs) {
  1939. var lineNum = cm.getCursor().line;
  1940. var charCoords = cm.charCoords(Pos(lineNum, 0), 'local');
  1941. var height = cm.getScrollInfo().clientHeight;
  1942. var y = charCoords.top;
  1943. var lineHeight = charCoords.bottom - y;
  1944. switch (actionArgs.position) {
  1945. case 'center': y = y - (height / 2) + lineHeight;
  1946. break;
  1947. case 'bottom': y = y - height + lineHeight*1.4;
  1948. break;
  1949. case 'top': y = y + lineHeight*0.4;
  1950. break;
  1951. }
  1952. cm.scrollTo(null, y);
  1953. },
  1954. replayMacro: function(cm, actionArgs, vim) {
  1955. var registerName = actionArgs.selectedCharacter;
  1956. var repeat = actionArgs.repeat;
  1957. var macroModeState = vimGlobalState.macroModeState;
  1958. if (registerName == '@') {
  1959. registerName = macroModeState.latestRegister;
  1960. }
  1961. while(repeat--){
  1962. executeMacroRegister(cm, vim, macroModeState, registerName);
  1963. }
  1964. },
  1965. enterMacroRecordMode: function(cm, actionArgs) {
  1966. var macroModeState = vimGlobalState.macroModeState;
  1967. var registerName = actionArgs.selectedCharacter;
  1968. macroModeState.enterMacroRecordMode(cm, registerName);
  1969. },
  1970. enterInsertMode: function(cm, actionArgs, vim) {
  1971. if (cm.getOption('readOnly')) { return; }
  1972. vim.insertMode = true;
  1973. vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1;
  1974. var insertAt = (actionArgs) ? actionArgs.insertAt : null;
  1975. var sel = vim.sel;
  1976. var head = actionArgs.head || cm.getCursor('head');
  1977. var height = cm.listSelections().length;
  1978. if (insertAt == 'eol') {
  1979. head = Pos(head.line, lineLength(cm, head.line));
  1980. } else if (insertAt == 'charAfter') {
  1981. head = offsetCursor(head, 0, 1);
  1982. } else if (insertAt == 'firstNonBlank') {
  1983. head = motions.moveToFirstNonWhiteSpaceCharacter(cm, head);
  1984. } else if (insertAt == 'startOfSelectedArea') {
  1985. if (!vim.visualBlock) {
  1986. if (sel.head.line < sel.anchor.line) {
  1987. head = sel.head;
  1988. } else {
  1989. head = Pos(sel.anchor.line, 0);
  1990. }
  1991. } else {
  1992. head = Pos(
  1993. Math.min(sel.head.line, sel.anchor.line),
  1994. Math.min(sel.head.ch, sel.anchor.ch));
  1995. height = Math.abs(sel.head.line - sel.anchor.line) + 1;
  1996. }
  1997. } else if (insertAt == 'endOfSelectedArea') {
  1998. if (!vim.visualBlock) {
  1999. if (sel.head.line >= sel.anchor.line) {
  2000. head = offsetCursor(sel.head, 0, 1);
  2001. } else {
  2002. head = Pos(sel.anchor.line, 0);
  2003. }
  2004. } else {
  2005. head = Pos(
  2006. Math.min(sel.head.line, sel.anchor.line),
  2007. Math.max(sel.head.ch + 1, sel.anchor.ch));
  2008. height = Math.abs(sel.head.line - sel.anchor.line) + 1;
  2009. }
  2010. } else if (insertAt == 'inplace') {
  2011. if (vim.visualMode){
  2012. return;
  2013. }
  2014. }
  2015. cm.setOption('keyMap', 'vim-insert');
  2016. cm.setOption('disableInput', false);
  2017. if (actionArgs && actionArgs.replace) {
  2018. // Handle Replace-mode as a special case of insert mode.
  2019. cm.toggleOverwrite(true);
  2020. cm.setOption('keyMap', 'vim-replace');
  2021. CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
  2022. } else {
  2023. cm.setOption('keyMap', 'vim-insert');
  2024. CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
  2025. }
  2026. if (!vimGlobalState.macroModeState.isPlaying) {
  2027. // Only record if not replaying.
  2028. cm.on('change', onChange);
  2029. CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
  2030. }
  2031. if (vim.visualMode) {
  2032. exitVisualMode(cm);
  2033. }
  2034. selectForInsert(cm, head, height);
  2035. },
  2036. toggleVisualMode: function(cm, actionArgs, vim) {
  2037. var repeat = actionArgs.repeat;
  2038. var anchor = cm.getCursor();
  2039. var head;
  2040. // TODO: The repeat should actually select number of characters/lines
  2041. // equal to the repeat times the size of the previous visual
  2042. // operation.
  2043. if (!vim.visualMode) {
  2044. // Entering visual mode
  2045. vim.visualMode = true;
  2046. vim.visualLine = !!actionArgs.linewise;
  2047. vim.visualBlock = !!actionArgs.blockwise;
  2048. head = clipCursorToContent(
  2049. cm, Pos(anchor.line, anchor.ch + repeat - 1),
  2050. true /** includeLineBreak */);
  2051. vim.sel = {
  2052. anchor: anchor,
  2053. head: head
  2054. };
  2055. CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
  2056. updateCmSelection(cm);
  2057. updateMark(cm, vim, '<', cursorMin(anchor, head));
  2058. updateMark(cm, vim, '>', cursorMax(anchor, head));
  2059. } else if (vim.visualLine ^ actionArgs.linewise ||
  2060. vim.visualBlock ^ actionArgs.blockwise) {
  2061. // Toggling between modes
  2062. vim.visualLine = !!actionArgs.linewise;
  2063. vim.visualBlock = !!actionArgs.blockwise;
  2064. CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
  2065. updateCmSelection(cm);
  2066. } else {
  2067. exitVisualMode(cm);
  2068. }
  2069. },
  2070. reselectLastSelection: function(cm, _actionArgs, vim) {
  2071. var lastSelection = vim.lastSelection;
  2072. if (vim.visualMode) {
  2073. updateLastSelection(cm, vim);
  2074. }
  2075. if (lastSelection) {
  2076. var anchor = lastSelection.anchorMark.find();
  2077. var head = lastSelection.headMark.find();
  2078. if (!anchor || !head) {
  2079. // If the marks have been destroyed due to edits, do nothing.
  2080. return;
  2081. }
  2082. vim.sel = {
  2083. anchor: anchor,
  2084. head: head
  2085. };
  2086. vim.visualMode = true;
  2087. vim.visualLine = lastSelection.visualLine;
  2088. vim.visualBlock = lastSelection.visualBlock;
  2089. updateCmSelection(cm);
  2090. updateMark(cm, vim, '<', cursorMin(anchor, head));
  2091. updateMark(cm, vim, '>', cursorMax(anchor, head));
  2092. CodeMirror.signal(cm, 'vim-mode-change', {
  2093. mode: 'visual',
  2094. subMode: vim.visualLine ? 'linewise' :
  2095. vim.visualBlock ? 'blockwise' : ''});
  2096. }
  2097. },
  2098. joinLines: function(cm, actionArgs, vim) {
  2099. var curStart, curEnd;
  2100. if (vim.visualMode) {
  2101. curStart = cm.getCursor('anchor');
  2102. curEnd = cm.getCursor('head');
  2103. curEnd.ch = lineLength(cm, curEnd.line) - 1;
  2104. } else {
  2105. // Repeat is the number of lines to join. Minimum 2 lines.
  2106. var repeat = Math.max(actionArgs.repeat, 2);
  2107. curStart = cm.getCursor();
  2108. curEnd = clipCursorToContent(cm, Pos(curStart.line + repeat - 1,
  2109. Infinity));
  2110. }
  2111. var finalCh = 0;
  2112. for (var i = curStart.line; i < curEnd.line; i++) {
  2113. finalCh = lineLength(cm, curStart.line);
  2114. var tmp = Pos(curStart.line + 1,
  2115. lineLength(cm, curStart.line + 1));
  2116. var text = cm.getRange(curStart, tmp);
  2117. text = text.replace(/\n\s*/g, ' ');
  2118. cm.replaceRange(text, curStart, tmp);
  2119. }
  2120. var curFinalPos = Pos(curStart.line, finalCh);
  2121. cm.setCursor(curFinalPos);
  2122. if (vim.visualMode) {
  2123. exitVisualMode(cm);
  2124. }
  2125. },
  2126. newLineAndEnterInsertMode: function(cm, actionArgs, vim) {
  2127. vim.insertMode = true;
  2128. var insertAt = copyCursor(cm.getCursor());
  2129. if (insertAt.line === cm.firstLine() && !actionArgs.after) {
  2130. // Special case for inserting newline before start of document.
  2131. cm.replaceRange('\n', Pos(cm.firstLine(), 0));
  2132. cm.setCursor(cm.firstLine(), 0);
  2133. } else {
  2134. insertAt.line = (actionArgs.after) ? insertAt.line :
  2135. insertAt.line - 1;
  2136. insertAt.ch = lineLength(cm, insertAt.line);
  2137. cm.setCursor(insertAt);
  2138. var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||
  2139. CodeMirror.commands.newlineAndIndent;
  2140. newlineFn(cm);
  2141. }
  2142. this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim);
  2143. },
  2144. paste: function(cm, actionArgs, vim) {
  2145. var cur = copyCursor(cm.getCursor());
  2146. var register = vimGlobalState.registerController.getRegister(
  2147. actionArgs.registerName);
  2148. var text = register.toString();
  2149. if (!text) {
  2150. return;
  2151. }
  2152. if (actionArgs.matchIndent) {
  2153. var tabSize = cm.getOption("tabSize");
  2154. // length that considers tabs and tabSize
  2155. var whitespaceLength = function(str) {
  2156. var tabs = (str.split("\t").length - 1);
  2157. var spaces = (str.split(" ").length - 1);
  2158. return tabs * tabSize + spaces * 1;
  2159. };
  2160. var currentLine = cm.getLine(cm.getCursor().line);
  2161. var indent = whitespaceLength(currentLine.match(/^\s*/)[0]);
  2162. // chomp last newline b/c don't want it to match /^\s*/gm
  2163. var chompedText = text.replace(/\n$/, '');
  2164. var wasChomped = text !== chompedText;
  2165. var firstIndent = whitespaceLength(text.match(/^\s*/)[0]);
  2166. var text = chompedText.replace(/^\s*/gm, function(wspace) {
  2167. var newIndent = indent + (whitespaceLength(wspace) - firstIndent);
  2168. if (newIndent < 0) {
  2169. return "";
  2170. }
  2171. else if (cm.getOption("indentWithTabs")) {
  2172. var quotient = Math.floor(newIndent / tabSize);
  2173. return Array(quotient + 1).join('\t');
  2174. }
  2175. else {
  2176. return Array(newIndent + 1).join(' ');
  2177. }
  2178. });
  2179. text += wasChomped ? "\n" : "";
  2180. }
  2181. if (actionArgs.repeat > 1) {
  2182. var text = Array(actionArgs.repeat + 1).join(text);
  2183. }
  2184. var linewise = register.linewise;
  2185. var blockwise = register.blockwise;
  2186. if (linewise) {
  2187. if(vim.visualMode) {
  2188. text = vim.visualLine ? text.slice(0, -1) : '\n' + text.slice(0, text.length - 1) + '\n';
  2189. } else if (actionArgs.after) {
  2190. // Move the newline at the end to the start instead, and paste just
  2191. // before the newline character of the line we are on right now.
  2192. text = '\n' + text.slice(0, text.length - 1);
  2193. cur.ch = lineLength(cm, cur.line);
  2194. } else {
  2195. cur.ch = 0;
  2196. }
  2197. } else {
  2198. if (blockwise) {
  2199. text = text.split('\n');
  2200. for (var i = 0; i < text.length; i++) {
  2201. text[i] = (text[i] == '') ? ' ' : text[i];
  2202. }
  2203. }
  2204. cur.ch += actionArgs.after ? 1 : 0;
  2205. }
  2206. var curPosFinal;
  2207. var idx;
  2208. if (vim.visualMode) {
  2209. // save the pasted text for reselection if the need arises
  2210. vim.lastPastedText = text;
  2211. var lastSelectionCurEnd;
  2212. var selectedArea = getSelectedAreaRange(cm, vim);
  2213. var selectionStart = selectedArea[0];
  2214. var selectionEnd = selectedArea[1];
  2215. var selectedText = cm.getSelection();
  2216. var selections = cm.listSelections();
  2217. var emptyStrings = new Array(selections.length).join('1').split('1');
  2218. // save the curEnd marker before it get cleared due to cm.replaceRange.
  2219. if (vim.lastSelection) {
  2220. lastSelectionCurEnd = vim.lastSelection.headMark.find();
  2221. }
  2222. // push the previously selected text to unnamed register
  2223. vimGlobalState.registerController.unnamedRegister.setText(selectedText);
  2224. if (blockwise) {
  2225. // first delete the selected text
  2226. cm.replaceSelections(emptyStrings);
  2227. // Set new selections as per the block length of the yanked text
  2228. selectionEnd = Pos(selectionStart.line + text.length-1, selectionStart.ch);
  2229. cm.setCursor(selectionStart);
  2230. selectBlock(cm, selectionEnd);
  2231. cm.replaceSelections(text);
  2232. curPosFinal = selectionStart;
  2233. } else if (vim.visualBlock) {
  2234. cm.replaceSelections(emptyStrings);
  2235. cm.setCursor(selectionStart);
  2236. cm.replaceRange(text, selectionStart, selectionStart);
  2237. curPosFinal = selectionStart;
  2238. } else {
  2239. cm.replaceRange(text, selectionStart, selectionEnd);
  2240. curPosFinal = cm.posFromIndex(cm.indexFromPos(selectionStart) + text.length - 1);
  2241. }
  2242. // restore the the curEnd marker
  2243. if(lastSelectionCurEnd) {
  2244. vim.lastSelection.headMark = cm.setBookmark(lastSelectionCurEnd);
  2245. }
  2246. if (linewise) {
  2247. curPosFinal.ch=0;
  2248. }
  2249. } else {
  2250. if (blockwise) {
  2251. cm.setCursor(cur);
  2252. for (var i = 0; i < text.length; i++) {
  2253. var line = cur.line+i;
  2254. if (line > cm.lastLine()) {
  2255. cm.replaceRange('\n', Pos(line, 0));
  2256. }
  2257. var lastCh = lineLength(cm, line);
  2258. if (lastCh < cur.ch) {
  2259. extendLineToColumn(cm, line, cur.ch);
  2260. }
  2261. }
  2262. cm.setCursor(cur);
  2263. selectBlock(cm, Pos(cur.line + text.length-1, cur.ch));
  2264. cm.replaceSelections(text);
  2265. curPosFinal = cur;
  2266. } else {
  2267. cm.replaceRange(text, cur);
  2268. // Now fine tune the cursor to where we want it.
  2269. if (linewise && actionArgs.after) {
  2270. curPosFinal = Pos(
  2271. cur.line + 1,
  2272. findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1)));
  2273. } else if (linewise && !actionArgs.after) {
  2274. curPosFinal = Pos(
  2275. cur.line,
  2276. findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line)));
  2277. } else if (!linewise && actionArgs.after) {
  2278. idx = cm.indexFromPos(cur);
  2279. curPosFinal = cm.posFromIndex(idx + text.length - 1);
  2280. } else {
  2281. idx = cm.indexFromPos(cur);
  2282. curPosFinal = cm.posFromIndex(idx + text.length);
  2283. }
  2284. }
  2285. }
  2286. if (vim.visualMode) {
  2287. exitVisualMode(cm);
  2288. }
  2289. cm.setCursor(curPosFinal);
  2290. },
  2291. undo: function(cm, actionArgs) {
  2292. cm.operation(function() {
  2293. repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();
  2294. cm.setCursor(cm.getCursor('anchor'));
  2295. });
  2296. },
  2297. redo: function(cm, actionArgs) {
  2298. repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();
  2299. },
  2300. setRegister: function(_cm, actionArgs, vim) {
  2301. vim.inputState.registerName = actionArgs.selectedCharacter;
  2302. },
  2303. setMark: function(cm, actionArgs, vim) {
  2304. var markName = actionArgs.selectedCharacter;
  2305. updateMark(cm, vim, markName, cm.getCursor());
  2306. },
  2307. replace: function(cm, actionArgs, vim) {
  2308. var replaceWith = actionArgs.selectedCharacter;
  2309. var curStart = cm.getCursor();
  2310. var replaceTo;
  2311. var curEnd;
  2312. var selections = cm.listSelections();
  2313. if (vim.visualMode) {
  2314. curStart = cm.getCursor('start');
  2315. curEnd = cm.getCursor('end');
  2316. } else {
  2317. var line = cm.getLine(curStart.line);
  2318. replaceTo = curStart.ch + actionArgs.repeat;
  2319. if (replaceTo > line.length) {
  2320. replaceTo=line.length;
  2321. }
  2322. curEnd = Pos(curStart.line, replaceTo);
  2323. }
  2324. if (replaceWith=='\n') {
  2325. if (!vim.visualMode) cm.replaceRange('', curStart, curEnd);
  2326. // special case, where vim help says to replace by just one line-break
  2327. (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm);
  2328. } else {
  2329. var replaceWithStr = cm.getRange(curStart, curEnd);
  2330. //replace all characters in range by selected, but keep linebreaks
  2331. replaceWithStr = replaceWithStr.replace(/[^\n]/g, replaceWith);
  2332. if (vim.visualBlock) {
  2333. // Tabs are split in visua block before replacing
  2334. var spaces = new Array(cm.getOption("tabSize")+1).join(' ');
  2335. replaceWithStr = cm.getSelection();
  2336. replaceWithStr = replaceWithStr.replace(/\t/g, spaces).replace(/[^\n]/g, replaceWith).split('\n');
  2337. cm.replaceSelections(replaceWithStr);
  2338. } else {
  2339. cm.replaceRange(replaceWithStr, curStart, curEnd);
  2340. }
  2341. if (vim.visualMode) {
  2342. curStart = cursorIsBefore(selections[0].anchor, selections[0].head) ?
  2343. selections[0].anchor : selections[0].head;
  2344. cm.setCursor(curStart);
  2345. exitVisualMode(cm);
  2346. } else {
  2347. cm.setCursor(offsetCursor(curEnd, 0, -1));
  2348. }
  2349. }
  2350. },
  2351. incrementNumberToken: function(cm, actionArgs) {
  2352. var cur = cm.getCursor();
  2353. var lineStr = cm.getLine(cur.line);
  2354. var re = /-?\d+/g;
  2355. var match;
  2356. var start;
  2357. var end;
  2358. var numberStr;
  2359. var token;
  2360. while ((match = re.exec(lineStr)) !== null) {
  2361. token = match[0];
  2362. start = match.index;
  2363. end = start + token.length;
  2364. if (cur.ch < end)break;
  2365. }
  2366. if (!actionArgs.backtrack && (end <= cur.ch))return;
  2367. if (token) {
  2368. var increment = actionArgs.increase ? 1 : -1;
  2369. var number = parseInt(token) + (increment * actionArgs.repeat);
  2370. var from = Pos(cur.line, start);
  2371. var to = Pos(cur.line, end);
  2372. numberStr = number.toString();
  2373. cm.replaceRange(numberStr, from, to);
  2374. } else {
  2375. return;
  2376. }
  2377. cm.setCursor(Pos(cur.line, start + numberStr.length - 1));
  2378. },
  2379. repeatLastEdit: function(cm, actionArgs, vim) {
  2380. var lastEditInputState = vim.lastEditInputState;
  2381. if (!lastEditInputState) { return; }
  2382. var repeat = actionArgs.repeat;
  2383. if (repeat && actionArgs.repeatIsExplicit) {
  2384. vim.lastEditInputState.repeatOverride = repeat;
  2385. } else {
  2386. repeat = vim.lastEditInputState.repeatOverride || repeat;
  2387. }
  2388. repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);
  2389. },
  2390. exitInsertMode: exitInsertMode
  2391. };
  2392. /*
  2393. * Below are miscellaneous utility functions used by vim.js
  2394. */
  2395. /**
  2396. * Clips cursor to ensure that line is within the buffer's range
  2397. * If includeLineBreak is true, then allow cur.ch == lineLength.
  2398. */
  2399. function clipCursorToContent(cm, cur, includeLineBreak) {
  2400. var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() );
  2401. var maxCh = lineLength(cm, line) - 1;
  2402. maxCh = (includeLineBreak) ? maxCh + 1 : maxCh;
  2403. var ch = Math.min(Math.max(0, cur.ch), maxCh);
  2404. return Pos(line, ch);
  2405. }
  2406. function copyArgs(args) {
  2407. var ret = {};
  2408. for (var prop in args) {
  2409. if (args.hasOwnProperty(prop)) {
  2410. ret[prop] = args[prop];
  2411. }
  2412. }
  2413. return ret;
  2414. }
  2415. function offsetCursor(cur, offsetLine, offsetCh) {
  2416. if (typeof offsetLine === 'object') {
  2417. offsetCh = offsetLine.ch;
  2418. offsetLine = offsetLine.line;
  2419. }
  2420. return Pos(cur.line + offsetLine, cur.ch + offsetCh);
  2421. }
  2422. function getOffset(anchor, head) {
  2423. return {
  2424. line: head.line - anchor.line,
  2425. ch: head.line - anchor.line
  2426. };
  2427. }
  2428. function commandMatches(keys, keyMap, context, inputState) {
  2429. // Partial matches are not applied. They inform the key handler
  2430. // that the current key sequence is a subsequence of a valid key
  2431. // sequence, so that the key buffer is not cleared.
  2432. var match, partial = [], full = [];
  2433. for (var i = 0; i < keyMap.length; i++) {
  2434. var command = keyMap[i];
  2435. if (context == 'insert' && command.context != 'insert' ||
  2436. command.context && command.context != context ||
  2437. inputState.operator && command.type == 'action' ||
  2438. !(match = commandMatch(keys, command.keys))) { continue; }
  2439. if (match == 'partial') { partial.push(command); }
  2440. if (match == 'full') { full.push(command); }
  2441. }
  2442. return {
  2443. partial: partial.length && partial,
  2444. full: full.length && full
  2445. };
  2446. }
  2447. function commandMatch(pressed, mapped) {
  2448. if (mapped.slice(-11) == '<character>') {
  2449. // Last character matches anything.
  2450. var prefixLen = mapped.length - 11;
  2451. var pressedPrefix = pressed.slice(0, prefixLen);
  2452. var mappedPrefix = mapped.slice(0, prefixLen);
  2453. return pressedPrefix == mappedPrefix && pressed.length > prefixLen ? 'full' :
  2454. mappedPrefix.indexOf(pressedPrefix) == 0 ? 'partial' : false;
  2455. } else {
  2456. return pressed == mapped ? 'full' :
  2457. mapped.indexOf(pressed) == 0 ? 'partial' : false;
  2458. }
  2459. }
  2460. function lastChar(keys) {
  2461. var match = /^.*(<[\w\-]+>)$/.exec(keys);
  2462. var selectedCharacter = match ? match[1] : keys.slice(-1);
  2463. if (selectedCharacter.length > 1){
  2464. switch(selectedCharacter){
  2465. case '<CR>':
  2466. selectedCharacter='\n';
  2467. break;
  2468. case '<Space>':
  2469. selectedCharacter=' ';
  2470. break;
  2471. default:
  2472. break;
  2473. }
  2474. }
  2475. return selectedCharacter;
  2476. }
  2477. function repeatFn(cm, fn, repeat) {
  2478. return function() {
  2479. for (var i = 0; i < repeat; i++) {
  2480. fn(cm);
  2481. }
  2482. };
  2483. }
  2484. function copyCursor(cur) {
  2485. return Pos(cur.line, cur.ch);
  2486. }
  2487. function cursorEqual(cur1, cur2) {
  2488. return cur1.ch == cur2.ch && cur1.line == cur2.line;
  2489. }
  2490. function cursorIsBefore(cur1, cur2) {
  2491. if (cur1.line < cur2.line) {
  2492. return true;
  2493. }
  2494. if (cur1.line == cur2.line && cur1.ch < cur2.ch) {
  2495. return true;
  2496. }
  2497. return false;
  2498. }
  2499. function cursorMin(cur1, cur2) {
  2500. if (arguments.length > 2) {
  2501. cur2 = cursorMin.apply(undefined, Array.prototype.slice.call(arguments, 1));
  2502. }
  2503. return cursorIsBefore(cur1, cur2) ? cur1 : cur2;
  2504. }
  2505. function cursorMax(cur1, cur2) {
  2506. if (arguments.length > 2) {
  2507. cur2 = cursorMax.apply(undefined, Array.prototype.slice.call(arguments, 1));
  2508. }
  2509. return cursorIsBefore(cur1, cur2) ? cur2 : cur1;
  2510. }
  2511. function cursorIsBetween(cur1, cur2, cur3) {
  2512. // returns true if cur2 is between cur1 and cur3.
  2513. var cur1before2 = cursorIsBefore(cur1, cur2);
  2514. var cur2before3 = cursorIsBefore(cur2, cur3);
  2515. return cur1before2 && cur2before3;
  2516. }
  2517. function lineLength(cm, lineNum) {
  2518. return cm.getLine(lineNum).length;
  2519. }
  2520. function reverse(s){
  2521. return s.split('').reverse().join('');
  2522. }
  2523. function trim(s) {
  2524. if (s.trim) {
  2525. return s.trim();
  2526. }
  2527. return s.replace(/^\s+|\s+$/g, '');
  2528. }
  2529. function escapeRegex(s) {
  2530. return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1');
  2531. }
  2532. function extendLineToColumn(cm, lineNum, column) {
  2533. var endCh = lineLength(cm, lineNum);
  2534. var spaces = new Array(column-endCh+1).join(' ');
  2535. cm.setCursor(Pos(lineNum, endCh));
  2536. cm.replaceRange(spaces, cm.getCursor());
  2537. }
  2538. // This functions selects a rectangular block
  2539. // of text with selectionEnd as any of its corner
  2540. // Height of block:
  2541. // Difference in selectionEnd.line and first/last selection.line
  2542. // Width of the block:
  2543. // Distance between selectionEnd.ch and any(first considered here) selection.ch
  2544. function selectBlock(cm, selectionEnd) {
  2545. var selections = [], ranges = cm.listSelections();
  2546. var head = copyCursor(cm.clipPos(selectionEnd));
  2547. var isClipped = !cursorEqual(selectionEnd, head);
  2548. var curHead = cm.getCursor('head');
  2549. var primIndex = getIndex(ranges, curHead);
  2550. var wasClipped = cursorEqual(ranges[primIndex].head, ranges[primIndex].anchor);
  2551. var max = ranges.length - 1;
  2552. var index = max - primIndex > primIndex ? max : 0;
  2553. var base = ranges[index].anchor;
  2554. var firstLine = Math.min(base.line, head.line);
  2555. var lastLine = Math.max(base.line, head.line);
  2556. var baseCh = base.ch, headCh = head.ch;
  2557. var dir = ranges[index].head.ch - baseCh;
  2558. var newDir = headCh - baseCh;
  2559. if (dir > 0 && newDir <= 0) {
  2560. baseCh++;
  2561. if (!isClipped) { headCh--; }
  2562. } else if (dir < 0 && newDir >= 0) {
  2563. baseCh--;
  2564. if (!wasClipped) { headCh++; }
  2565. } else if (dir < 0 && newDir == -1) {
  2566. baseCh--;
  2567. headCh++;
  2568. }
  2569. for (var line = firstLine; line <= lastLine; line++) {
  2570. var range = {anchor: new Pos(line, baseCh), head: new Pos(line, headCh)};
  2571. selections.push(range);
  2572. }
  2573. primIndex = head.line == lastLine ? selections.length - 1 : 0;
  2574. cm.setSelections(selections);
  2575. selectionEnd.ch = headCh;
  2576. base.ch = baseCh;
  2577. return base;
  2578. }
  2579. function selectForInsert(cm, head, height) {
  2580. var sel = [];
  2581. for (var i = 0; i < height; i++) {
  2582. var lineHead = offsetCursor(head, i, 0);
  2583. sel.push({anchor: lineHead, head: lineHead});
  2584. }
  2585. cm.setSelections(sel, 0);
  2586. }
  2587. // getIndex returns the index of the cursor in the selections.
  2588. function getIndex(ranges, cursor, end) {
  2589. for (var i = 0; i < ranges.length; i++) {
  2590. var atAnchor = end != 'head' && cursorEqual(ranges[i].anchor, cursor);
  2591. var atHead = end != 'anchor' && cursorEqual(ranges[i].head, cursor);
  2592. if (atAnchor || atHead) {
  2593. return i;
  2594. }
  2595. }
  2596. return -1;
  2597. }
  2598. function getSelectedAreaRange(cm, vim) {
  2599. var lastSelection = vim.lastSelection;
  2600. var getCurrentSelectedAreaRange = function() {
  2601. var selections = cm.listSelections();
  2602. var start = selections[0];
  2603. var end = selections[selections.length-1];
  2604. var selectionStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head;
  2605. var selectionEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor;
  2606. return [selectionStart, selectionEnd];
  2607. };
  2608. var getLastSelectedAreaRange = function() {
  2609. var selectionStart = cm.getCursor();
  2610. var selectionEnd = cm.getCursor();
  2611. var block = lastSelection.visualBlock;
  2612. if (block) {
  2613. var width = block.width;
  2614. var height = block.height;
  2615. selectionEnd = Pos(selectionStart.line + height, selectionStart.ch + width);
  2616. var selections = [];
  2617. // selectBlock creates a 'proper' rectangular block.
  2618. // We do not want that in all cases, so we manually set selections.
  2619. for (var i = selectionStart.line; i < selectionEnd.line; i++) {
  2620. var anchor = Pos(i, selectionStart.ch);
  2621. var head = Pos(i, selectionEnd.ch);
  2622. var range = {anchor: anchor, head: head};
  2623. selections.push(range);
  2624. }
  2625. cm.setSelections(selections);
  2626. } else {
  2627. var start = lastSelection.anchorMark.find();
  2628. var end = lastSelection.headMark.find();
  2629. var line = end.line - start.line;
  2630. var ch = end.ch - start.ch;
  2631. selectionEnd = {line: selectionEnd.line + line, ch: line ? selectionEnd.ch : ch + selectionEnd.ch};
  2632. if (lastSelection.visualLine) {
  2633. selectionStart = Pos(selectionStart.line, 0);
  2634. selectionEnd = Pos(selectionEnd.line, lineLength(cm, selectionEnd.line));
  2635. }
  2636. cm.setSelection(selectionStart, selectionEnd);
  2637. }
  2638. return [selectionStart, selectionEnd];
  2639. };
  2640. if (!vim.visualMode) {
  2641. // In case of replaying the action.
  2642. return getLastSelectedAreaRange();
  2643. } else {
  2644. return getCurrentSelectedAreaRange();
  2645. }
  2646. }
  2647. // Updates the previous selection with the current selection's values. This
  2648. // should only be called in visual mode.
  2649. function updateLastSelection(cm, vim) {
  2650. var anchor = vim.sel.anchor;
  2651. var head = vim.sel.head;
  2652. // To accommodate the effect of lastPastedText in the last selection
  2653. if (vim.lastPastedText) {
  2654. head = cm.posFromIndex(cm.indexFromPos(anchor) + vim.lastPastedText.length);
  2655. vim.lastPastedText = null;
  2656. }
  2657. vim.lastSelection = {'anchorMark': cm.setBookmark(anchor),
  2658. 'headMark': cm.setBookmark(head),
  2659. 'anchor': copyCursor(anchor),
  2660. 'head': copyCursor(head),
  2661. 'visualMode': vim.visualMode,
  2662. 'visualLine': vim.visualLine,
  2663. 'visualBlock': vim.visualBlock};
  2664. }
  2665. function expandSelection(cm, start, end) {
  2666. var sel = cm.state.vim.sel;
  2667. var head = sel.head;
  2668. var anchor = sel.anchor;
  2669. var tmp;
  2670. if (cursorIsBefore(end, start)) {
  2671. tmp = end;
  2672. end = start;
  2673. start = tmp;
  2674. }
  2675. if (cursorIsBefore(head, anchor)) {
  2676. head = cursorMin(start, head);
  2677. anchor = cursorMax(anchor, end);
  2678. } else {
  2679. anchor = cursorMin(start, anchor);
  2680. head = cursorMax(head, end);
  2681. head = offsetCursor(head, 0, -1);
  2682. if (head.ch == -1 && head.line != cm.firstLine()) {
  2683. head = Pos(head.line - 1, lineLength(cm, head.line - 1));
  2684. }
  2685. }
  2686. return [anchor, head];
  2687. }
  2688. /**
  2689. * Updates the CodeMirror selection to match the provided vim selection.
  2690. * If no arguments are given, it uses the current vim selection state.
  2691. */
  2692. function updateCmSelection(cm, sel, mode) {
  2693. var vim = cm.state.vim;
  2694. sel = sel || vim.sel;
  2695. var mode = mode ||
  2696. vim.visualLine ? 'line' : vim.visualBlock ? 'block' : 'char';
  2697. var cmSel = makeCmSelection(cm, sel, mode);
  2698. cm.setSelections(cmSel.ranges, cmSel.primary);
  2699. updateFakeCursor(cm);
  2700. }
  2701. function makeCmSelection(cm, sel, mode, exclusive) {
  2702. var head = copyCursor(sel.head);
  2703. var anchor = copyCursor(sel.anchor);
  2704. if (mode == 'char') {
  2705. var headOffset = !exclusive && !cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
  2706. var anchorOffset = cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
  2707. head = offsetCursor(sel.head, 0, headOffset);
  2708. anchor = offsetCursor(sel.anchor, 0, anchorOffset);
  2709. return {
  2710. ranges: [{anchor: anchor, head: head}],
  2711. primary: 0
  2712. };
  2713. } else if (mode == 'line') {
  2714. if (!cursorIsBefore(sel.head, sel.anchor)) {
  2715. anchor.ch = 0;
  2716. var lastLine = cm.lastLine();
  2717. if (head.line > lastLine) {
  2718. head.line = lastLine;
  2719. }
  2720. head.ch = lineLength(cm, head.line);
  2721. } else {
  2722. head.ch = 0;
  2723. anchor.ch = lineLength(cm, anchor.line);
  2724. }
  2725. return {
  2726. ranges: [{anchor: anchor, head: head}],
  2727. primary: 0
  2728. };
  2729. } else if (mode == 'block') {
  2730. var top = Math.min(anchor.line, head.line),
  2731. left = Math.min(anchor.ch, head.ch),
  2732. bottom = Math.max(anchor.line, head.line),
  2733. right = Math.max(anchor.ch, head.ch) + 1;
  2734. var height = bottom - top + 1;
  2735. var primary = head.line == top ? 0 : height - 1;
  2736. var ranges = [];
  2737. for (var i = 0; i < height; i++) {
  2738. ranges.push({
  2739. anchor: Pos(top + i, left),
  2740. head: Pos(top + i, right)
  2741. });
  2742. }
  2743. return {
  2744. ranges: ranges,
  2745. primary: primary
  2746. };
  2747. }
  2748. }
  2749. function getHead(cm) {
  2750. var cur = cm.getCursor('head');
  2751. if (cm.getSelection().length == 1) {
  2752. // Small corner case when only 1 character is selected. The "real"
  2753. // head is the left of head and anchor.
  2754. cur = cursorMin(cur, cm.getCursor('anchor'));
  2755. }
  2756. return cur;
  2757. }
  2758. /**
  2759. * If moveHead is set to false, the CodeMirror selection will not be
  2760. * touched. The caller assumes the responsibility of putting the cursor
  2761. * in the right place.
  2762. */
  2763. function exitVisualMode(cm, moveHead) {
  2764. var vim = cm.state.vim;
  2765. if (moveHead !== false) {
  2766. cm.setCursor(clipCursorToContent(cm, vim.sel.head));
  2767. }
  2768. updateLastSelection(cm, vim);
  2769. vim.visualMode = false;
  2770. vim.visualLine = false;
  2771. vim.visualBlock = false;
  2772. CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
  2773. if (vim.fakeCursor) {
  2774. vim.fakeCursor.clear();
  2775. }
  2776. }
  2777. // Remove any trailing newlines from the selection. For
  2778. // example, with the caret at the start of the last word on the line,
  2779. // 'dw' should word, but not the newline, while 'w' should advance the
  2780. // caret to the first character of the next line.
  2781. function clipToLine(cm, curStart, curEnd) {
  2782. var selection = cm.getRange(curStart, curEnd);
  2783. // Only clip if the selection ends with trailing newline + whitespace
  2784. if (/\n\s*$/.test(selection)) {
  2785. var lines = selection.split('\n');
  2786. // We know this is all whitepsace.
  2787. lines.pop();
  2788. // Cases:
  2789. // 1. Last word is an empty line - do not clip the trailing '\n'
  2790. // 2. Last word is not an empty line - clip the trailing '\n'
  2791. var line;
  2792. // Find the line containing the last word, and clip all whitespace up
  2793. // to it.
  2794. for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {
  2795. curEnd.line--;
  2796. curEnd.ch = 0;
  2797. }
  2798. // If the last word is not an empty line, clip an additional newline
  2799. if (line) {
  2800. curEnd.line--;
  2801. curEnd.ch = lineLength(cm, curEnd.line);
  2802. } else {
  2803. curEnd.ch = 0;
  2804. }
  2805. }
  2806. }
  2807. // Expand the selection to line ends.
  2808. function expandSelectionToLine(_cm, curStart, curEnd) {
  2809. curStart.ch = 0;
  2810. curEnd.ch = 0;
  2811. curEnd.line++;
  2812. }
  2813. function findFirstNonWhiteSpaceCharacter(text) {
  2814. if (!text) {
  2815. return 0;
  2816. }
  2817. var firstNonWS = text.search(/\S/);
  2818. return firstNonWS == -1 ? text.length : firstNonWS;
  2819. }
  2820. function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) {
  2821. var cur = getHead(cm);
  2822. var line = cm.getLine(cur.line);
  2823. var idx = cur.ch;
  2824. // Seek to first word or non-whitespace character, depending on if
  2825. // noSymbol is true.
  2826. var textAfterIdx = line.substring(idx);
  2827. var firstMatchedChar;
  2828. if (noSymbol) {
  2829. firstMatchedChar = textAfterIdx.search(/\w/);
  2830. } else {
  2831. firstMatchedChar = textAfterIdx.search(/\S/);
  2832. }
  2833. if (firstMatchedChar == -1) {
  2834. return null;
  2835. }
  2836. idx += firstMatchedChar;
  2837. textAfterIdx = line.substring(idx);
  2838. var textBeforeIdx = line.substring(0, idx);
  2839. var matchRegex;
  2840. // Greedy matchers for the "word" we are trying to expand.
  2841. if (bigWord) {
  2842. matchRegex = /^\S+/;
  2843. } else {
  2844. if ((/\w/).test(line.charAt(idx))) {
  2845. matchRegex = /^\w+/;
  2846. } else {
  2847. matchRegex = /^[^\w\s]+/;
  2848. }
  2849. }
  2850. var wordAfterRegex = matchRegex.exec(textAfterIdx);
  2851. var wordStart = idx;
  2852. var wordEnd = idx + wordAfterRegex[0].length;
  2853. // TODO: Find a better way to do this. It will be slow on very long lines.
  2854. var revTextBeforeIdx = reverse(textBeforeIdx);
  2855. var wordBeforeRegex = matchRegex.exec(revTextBeforeIdx);
  2856. if (wordBeforeRegex) {
  2857. wordStart -= wordBeforeRegex[0].length;
  2858. }
  2859. if (inclusive) {
  2860. // If present, trim all whitespace after word.
  2861. // Otherwise, trim all whitespace before word.
  2862. var textAfterWordEnd = line.substring(wordEnd);
  2863. var whitespacesAfterWord = textAfterWordEnd.match(/^\s*/)[0].length;
  2864. if (whitespacesAfterWord > 0) {
  2865. wordEnd += whitespacesAfterWord;
  2866. } else {
  2867. var revTrim = revTextBeforeIdx.length - wordStart;
  2868. var textBeforeWordStart = revTextBeforeIdx.substring(revTrim);
  2869. var whitespacesBeforeWord = textBeforeWordStart.match(/^\s*/)[0].length;
  2870. wordStart -= whitespacesBeforeWord;
  2871. }
  2872. }
  2873. return { start: Pos(cur.line, wordStart),
  2874. end: Pos(cur.line, wordEnd) };
  2875. }
  2876. function recordJumpPosition(cm, oldCur, newCur) {
  2877. if (!cursorEqual(oldCur, newCur)) {
  2878. vimGlobalState.jumpList.add(cm, oldCur, newCur);
  2879. }
  2880. }
  2881. function recordLastCharacterSearch(increment, args) {
  2882. vimGlobalState.lastChararacterSearch.increment = increment;
  2883. vimGlobalState.lastChararacterSearch.forward = args.forward;
  2884. vimGlobalState.lastChararacterSearch.selectedCharacter = args.selectedCharacter;
  2885. }
  2886. var symbolToMode = {
  2887. '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',
  2888. '[': 'section', ']': 'section',
  2889. '*': 'comment', '/': 'comment',
  2890. 'm': 'method', 'M': 'method',
  2891. '#': 'preprocess'
  2892. };
  2893. var findSymbolModes = {
  2894. bracket: {
  2895. isComplete: function(state) {
  2896. if (state.nextCh === state.symb) {
  2897. state.depth++;
  2898. if (state.depth >= 1)return true;
  2899. } else if (state.nextCh === state.reverseSymb) {
  2900. state.depth--;
  2901. }
  2902. return false;
  2903. }
  2904. },
  2905. section: {
  2906. init: function(state) {
  2907. state.curMoveThrough = true;
  2908. state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';
  2909. },
  2910. isComplete: function(state) {
  2911. return state.index === 0 && state.nextCh === state.symb;
  2912. }
  2913. },
  2914. comment: {
  2915. isComplete: function(state) {
  2916. var found = state.lastCh === '*' && state.nextCh === '/';
  2917. state.lastCh = state.nextCh;
  2918. return found;
  2919. }
  2920. },
  2921. // TODO: The original Vim implementation only operates on level 1 and 2.
  2922. // The current implementation doesn't check for code block level and
  2923. // therefore it operates on any levels.
  2924. method: {
  2925. init: function(state) {
  2926. state.symb = (state.symb === 'm' ? '{' : '}');
  2927. state.reverseSymb = state.symb === '{' ? '}' : '{';
  2928. },
  2929. isComplete: function(state) {
  2930. if (state.nextCh === state.symb)return true;
  2931. return false;
  2932. }
  2933. },
  2934. preprocess: {
  2935. init: function(state) {
  2936. state.index = 0;
  2937. },
  2938. isComplete: function(state) {
  2939. if (state.nextCh === '#') {
  2940. var token = state.lineText.match(/#(\w+)/)[1];
  2941. if (token === 'endif') {
  2942. if (state.forward && state.depth === 0) {
  2943. return true;
  2944. }
  2945. state.depth++;
  2946. } else if (token === 'if') {
  2947. if (!state.forward && state.depth === 0) {
  2948. return true;
  2949. }
  2950. state.depth--;
  2951. }
  2952. if (token === 'else' && state.depth === 0)return true;
  2953. }
  2954. return false;
  2955. }
  2956. }
  2957. };
  2958. function findSymbol(cm, repeat, forward, symb) {
  2959. var cur = copyCursor(cm.getCursor());
  2960. var increment = forward ? 1 : -1;
  2961. var endLine = forward ? cm.lineCount() : -1;
  2962. var curCh = cur.ch;
  2963. var line = cur.line;
  2964. var lineText = cm.getLine(line);
  2965. var state = {
  2966. lineText: lineText,
  2967. nextCh: lineText.charAt(curCh),
  2968. lastCh: null,
  2969. index: curCh,
  2970. symb: symb,
  2971. reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],
  2972. forward: forward,
  2973. depth: 0,
  2974. curMoveThrough: false
  2975. };
  2976. var mode = symbolToMode[symb];
  2977. if (!mode)return cur;
  2978. var init = findSymbolModes[mode].init;
  2979. var isComplete = findSymbolModes[mode].isComplete;
  2980. if (init) { init(state); }
  2981. while (line !== endLine && repeat) {
  2982. state.index += increment;
  2983. state.nextCh = state.lineText.charAt(state.index);
  2984. if (!state.nextCh) {
  2985. line += increment;
  2986. state.lineText = cm.getLine(line) || '';
  2987. if (increment > 0) {
  2988. state.index = 0;
  2989. } else {
  2990. var lineLen = state.lineText.length;
  2991. state.index = (lineLen > 0) ? (lineLen-1) : 0;
  2992. }
  2993. state.nextCh = state.lineText.charAt(state.index);
  2994. }
  2995. if (isComplete(state)) {
  2996. cur.line = line;
  2997. cur.ch = state.index;
  2998. repeat--;
  2999. }
  3000. }
  3001. if (state.nextCh || state.curMoveThrough) {
  3002. return Pos(line, state.index);
  3003. }
  3004. return cur;
  3005. }
  3006. /*
  3007. * Returns the boundaries of the next word. If the cursor in the middle of
  3008. * the word, then returns the boundaries of the current word, starting at
  3009. * the cursor. If the cursor is at the start/end of a word, and we are going
  3010. * forward/backward, respectively, find the boundaries of the next word.
  3011. *
  3012. * @param {CodeMirror} cm CodeMirror object.
  3013. * @param {Cursor} cur The cursor position.
  3014. * @param {boolean} forward True to search forward. False to search
  3015. * backward.
  3016. * @param {boolean} bigWord True if punctuation count as part of the word.
  3017. * False if only [a-zA-Z0-9] characters count as part of the word.
  3018. * @param {boolean} emptyLineIsWord True if empty lines should be treated
  3019. * as words.
  3020. * @return {Object{from:number, to:number, line: number}} The boundaries of
  3021. * the word, or null if there are no more words.
  3022. */
  3023. function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {
  3024. var lineNum = cur.line;
  3025. var pos = cur.ch;
  3026. var line = cm.getLine(lineNum);
  3027. var dir = forward ? 1 : -1;
  3028. var regexps = bigWord ? bigWordRegexp : wordRegexp;
  3029. if (emptyLineIsWord && line == '') {
  3030. lineNum += dir;
  3031. line = cm.getLine(lineNum);
  3032. if (!isLine(cm, lineNum)) {
  3033. return null;
  3034. }
  3035. pos = (forward) ? 0 : line.length;
  3036. }
  3037. while (true) {
  3038. if (emptyLineIsWord && line == '') {
  3039. return { from: 0, to: 0, line: lineNum };
  3040. }
  3041. var stop = (dir > 0) ? line.length : -1;
  3042. var wordStart = stop, wordEnd = stop;
  3043. // Find bounds of next word.
  3044. while (pos != stop) {
  3045. var foundWord = false;
  3046. for (var i = 0; i < regexps.length && !foundWord; ++i) {
  3047. if (regexps[i].test(line.charAt(pos))) {
  3048. wordStart = pos;
  3049. // Advance to end of word.
  3050. while (pos != stop && regexps[i].test(line.charAt(pos))) {
  3051. pos += dir;
  3052. }
  3053. wordEnd = pos;
  3054. foundWord = wordStart != wordEnd;
  3055. if (wordStart == cur.ch && lineNum == cur.line &&
  3056. wordEnd == wordStart + dir) {
  3057. // We started at the end of a word. Find the next one.
  3058. continue;
  3059. } else {
  3060. return {
  3061. from: Math.min(wordStart, wordEnd + 1),
  3062. to: Math.max(wordStart, wordEnd),
  3063. line: lineNum };
  3064. }
  3065. }
  3066. }
  3067. if (!foundWord) {
  3068. pos += dir;
  3069. }
  3070. }
  3071. // Advance to next/prev line.
  3072. lineNum += dir;
  3073. if (!isLine(cm, lineNum)) {
  3074. return null;
  3075. }
  3076. line = cm.getLine(lineNum);
  3077. pos = (dir > 0) ? 0 : line.length;
  3078. }
  3079. // Should never get here.
  3080. throw new Error('The impossible happened.');
  3081. }
  3082. /**
  3083. * @param {CodeMirror} cm CodeMirror object.
  3084. * @param {Pos} cur The position to start from.
  3085. * @param {int} repeat Number of words to move past.
  3086. * @param {boolean} forward True to search forward. False to search
  3087. * backward.
  3088. * @param {boolean} wordEnd True to move to end of word. False to move to
  3089. * beginning of word.
  3090. * @param {boolean} bigWord True if punctuation count as part of the word.
  3091. * False if only alphabet characters count as part of the word.
  3092. * @return {Cursor} The position the cursor should move to.
  3093. */
  3094. function moveToWord(cm, cur, repeat, forward, wordEnd, bigWord) {
  3095. var curStart = copyCursor(cur);
  3096. var words = [];
  3097. if (forward && !wordEnd || !forward && wordEnd) {
  3098. repeat++;
  3099. }
  3100. // For 'e', empty lines are not considered words, go figure.
  3101. var emptyLineIsWord = !(forward && wordEnd);
  3102. for (var i = 0; i < repeat; i++) {
  3103. var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord);
  3104. if (!word) {
  3105. var eodCh = lineLength(cm, cm.lastLine());
  3106. words.push(forward
  3107. ? {line: cm.lastLine(), from: eodCh, to: eodCh}
  3108. : {line: 0, from: 0, to: 0});
  3109. break;
  3110. }
  3111. words.push(word);
  3112. cur = Pos(word.line, forward ? (word.to - 1) : word.from);
  3113. }
  3114. var shortCircuit = words.length != repeat;
  3115. var firstWord = words[0];
  3116. var lastWord = words.pop();
  3117. if (forward && !wordEnd) {
  3118. // w
  3119. if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) {
  3120. // We did not start in the middle of a word. Discard the extra word at the end.
  3121. lastWord = words.pop();
  3122. }
  3123. return Pos(lastWord.line, lastWord.from);
  3124. } else if (forward && wordEnd) {
  3125. return Pos(lastWord.line, lastWord.to - 1);
  3126. } else if (!forward && wordEnd) {
  3127. // ge
  3128. if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) {
  3129. // We did not start in the middle of a word. Discard the extra word at the end.
  3130. lastWord = words.pop();
  3131. }
  3132. return Pos(lastWord.line, lastWord.to);
  3133. } else {
  3134. // b
  3135. return Pos(lastWord.line, lastWord.from);
  3136. }
  3137. }
  3138. function moveToCharacter(cm, repeat, forward, character) {
  3139. var cur = cm.getCursor();
  3140. var start = cur.ch;
  3141. var idx;
  3142. for (var i = 0; i < repeat; i ++) {
  3143. var line = cm.getLine(cur.line);
  3144. idx = charIdxInLine(start, line, character, forward, true);
  3145. if (idx == -1) {
  3146. return null;
  3147. }
  3148. start = idx;
  3149. }
  3150. return Pos(cm.getCursor().line, idx);
  3151. }
  3152. function moveToColumn(cm, repeat) {
  3153. // repeat is always >= 1, so repeat - 1 always corresponds
  3154. // to the column we want to go to.
  3155. var line = cm.getCursor().line;
  3156. return clipCursorToContent(cm, Pos(line, repeat - 1));
  3157. }
  3158. function updateMark(cm, vim, markName, pos) {
  3159. if (!inArray(markName, validMarks)) {
  3160. return;
  3161. }
  3162. if (vim.marks[markName]) {
  3163. vim.marks[markName].clear();
  3164. }
  3165. vim.marks[markName] = cm.setBookmark(pos);
  3166. }
  3167. function charIdxInLine(start, line, character, forward, includeChar) {
  3168. // Search for char in line.
  3169. // motion_options: {forward, includeChar}
  3170. // If includeChar = true, include it too.
  3171. // If forward = true, search forward, else search backwards.
  3172. // If char is not found on this line, do nothing
  3173. var idx;
  3174. if (forward) {
  3175. idx = line.indexOf(character, start + 1);
  3176. if (idx != -1 && !includeChar) {
  3177. idx -= 1;
  3178. }
  3179. } else {
  3180. idx = line.lastIndexOf(character, start - 1);
  3181. if (idx != -1 && !includeChar) {
  3182. idx += 1;
  3183. }
  3184. }
  3185. return idx;
  3186. }
  3187. // TODO: perhaps this finagling of start and end positions belonds
  3188. // in codmirror/replaceRange?
  3189. function selectCompanionObject(cm, head, symb, inclusive) {
  3190. var cur = head, start, end;
  3191. var bracketRegexp = ({
  3192. '(': /[()]/, ')': /[()]/,
  3193. '[': /[[\]]/, ']': /[[\]]/,
  3194. '{': /[{}]/, '}': /[{}]/})[symb];
  3195. var openSym = ({
  3196. '(': '(', ')': '(',
  3197. '[': '[', ']': '[',
  3198. '{': '{', '}': '{'})[symb];
  3199. var curChar = cm.getLine(cur.line).charAt(cur.ch);
  3200. // Due to the behavior of scanForBracket, we need to add an offset if the
  3201. // cursor is on a matching open bracket.
  3202. var offset = curChar === openSym ? 1 : 0;
  3203. start = cm.scanForBracket(Pos(cur.line, cur.ch + offset), -1, null, {'bracketRegex': bracketRegexp});
  3204. end = cm.scanForBracket(Pos(cur.line, cur.ch + offset), 1, null, {'bracketRegex': bracketRegexp});
  3205. if (!start || !end) {
  3206. return { start: cur, end: cur };
  3207. }
  3208. start = start.pos;
  3209. end = end.pos;
  3210. if ((start.line == end.line && start.ch > end.ch)
  3211. || (start.line > end.line)) {
  3212. var tmp = start;
  3213. start = end;
  3214. end = tmp;
  3215. }
  3216. if (inclusive) {
  3217. end.ch += 1;
  3218. } else {
  3219. start.ch += 1;
  3220. }
  3221. return { start: start, end: end };
  3222. }
  3223. // Takes in a symbol and a cursor and tries to simulate text objects that
  3224. // have identical opening and closing symbols
  3225. // TODO support across multiple lines
  3226. function findBeginningAndEnd(cm, head, symb, inclusive) {
  3227. var cur = copyCursor(head);
  3228. var line = cm.getLine(cur.line);
  3229. var chars = line.split('');
  3230. var start, end, i, len;
  3231. var firstIndex = chars.indexOf(symb);
  3232. // the decision tree is to always look backwards for the beginning first,
  3233. // but if the cursor is in front of the first instance of the symb,
  3234. // then move the cursor forward
  3235. if (cur.ch < firstIndex) {
  3236. cur.ch = firstIndex;
  3237. // Why is this line even here???
  3238. // cm.setCursor(cur.line, firstIndex+1);
  3239. }
  3240. // otherwise if the cursor is currently on the closing symbol
  3241. else if (firstIndex < cur.ch && chars[cur.ch] == symb) {
  3242. end = cur.ch; // assign end to the current cursor
  3243. --cur.ch; // make sure to look backwards
  3244. }
  3245. // if we're currently on the symbol, we've got a start
  3246. if (chars[cur.ch] == symb && !end) {
  3247. start = cur.ch + 1; // assign start to ahead of the cursor
  3248. } else {
  3249. // go backwards to find the start
  3250. for (i = cur.ch; i > -1 && !start; i--) {
  3251. if (chars[i] == symb) {
  3252. start = i + 1;
  3253. }
  3254. }
  3255. }
  3256. // look forwards for the end symbol
  3257. if (start && !end) {
  3258. for (i = start, len = chars.length; i < len && !end; i++) {
  3259. if (chars[i] == symb) {
  3260. end = i;
  3261. }
  3262. }
  3263. }
  3264. // nothing found
  3265. if (!start || !end) {
  3266. return { start: cur, end: cur };
  3267. }
  3268. // include the symbols
  3269. if (inclusive) {
  3270. --start; ++end;
  3271. }
  3272. return {
  3273. start: Pos(cur.line, start),
  3274. end: Pos(cur.line, end)
  3275. };
  3276. }
  3277. // Search functions
  3278. defineOption('pcre', true, 'boolean');
  3279. function SearchState() {}
  3280. SearchState.prototype = {
  3281. getQuery: function() {
  3282. return vimGlobalState.query;
  3283. },
  3284. setQuery: function(query) {
  3285. vimGlobalState.query = query;
  3286. },
  3287. getOverlay: function() {
  3288. return this.searchOverlay;
  3289. },
  3290. setOverlay: function(overlay) {
  3291. this.searchOverlay = overlay;
  3292. },
  3293. isReversed: function() {
  3294. return vimGlobalState.isReversed;
  3295. },
  3296. setReversed: function(reversed) {
  3297. vimGlobalState.isReversed = reversed;
  3298. }
  3299. };
  3300. function getSearchState(cm) {
  3301. var vim = cm.state.vim;
  3302. return vim.searchState_ || (vim.searchState_ = new SearchState());
  3303. }
  3304. function dialog(cm, template, shortText, onClose, options) {
  3305. if (cm.openDialog) {
  3306. cm.openDialog(template, onClose, { bottom: true, value: options.value,
  3307. onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp });
  3308. }
  3309. else {
  3310. onClose(prompt(shortText, ''));
  3311. }
  3312. }
  3313. function splitBySlash(argString) {
  3314. var slashes = findUnescapedSlashes(argString) || [];
  3315. if (!slashes.length) return [];
  3316. var tokens = [];
  3317. // in case of strings like foo/bar
  3318. if (slashes[0] !== 0) return;
  3319. for (var i = 0; i < slashes.length; i++) {
  3320. if (typeof slashes[i] == 'number')
  3321. tokens.push(argString.substring(slashes[i] + 1, slashes[i+1]));
  3322. }
  3323. return tokens;
  3324. }
  3325. function findUnescapedSlashes(str) {
  3326. var escapeNextChar = false;
  3327. var slashes = [];
  3328. for (var i = 0; i < str.length; i++) {
  3329. var c = str.charAt(i);
  3330. if (!escapeNextChar && c == '/') {
  3331. slashes.push(i);
  3332. }
  3333. escapeNextChar = !escapeNextChar && (c == '\\');
  3334. }
  3335. return slashes;
  3336. }
  3337. // Translates a search string from ex (vim) syntax into javascript form.
  3338. function translateRegex(str) {
  3339. // When these match, add a '\' if unescaped or remove one if escaped.
  3340. var specials = '|(){';
  3341. // Remove, but never add, a '\' for these.
  3342. var unescape = '}';
  3343. var escapeNextChar = false;
  3344. var out = [];
  3345. for (var i = -1; i < str.length; i++) {
  3346. var c = str.charAt(i) || '';
  3347. var n = str.charAt(i+1) || '';
  3348. var specialComesNext = (n && specials.indexOf(n) != -1);
  3349. if (escapeNextChar) {
  3350. if (c !== '\\' || !specialComesNext) {
  3351. out.push(c);
  3352. }
  3353. escapeNextChar = false;
  3354. } else {
  3355. if (c === '\\') {
  3356. escapeNextChar = true;
  3357. // Treat the unescape list as special for removing, but not adding '\'.
  3358. if (n && unescape.indexOf(n) != -1) {
  3359. specialComesNext = true;
  3360. }
  3361. // Not passing this test means removing a '\'.
  3362. if (!specialComesNext || n === '\\') {
  3363. out.push(c);
  3364. }
  3365. } else {
  3366. out.push(c);
  3367. if (specialComesNext && n !== '\\') {
  3368. out.push('\\');
  3369. }
  3370. }
  3371. }
  3372. }
  3373. return out.join('');
  3374. }
  3375. // Translates the replace part of a search and replace from ex (vim) syntax into
  3376. // javascript form. Similar to translateRegex, but additionally fixes back references
  3377. // (translates '\[0..9]' to '$[0..9]') and follows different rules for escaping '$'.
  3378. function translateRegexReplace(str) {
  3379. var escapeNextChar = false;
  3380. var out = [];
  3381. for (var i = -1; i < str.length; i++) {
  3382. var c = str.charAt(i) || '';
  3383. var n = str.charAt(i+1) || '';
  3384. if (escapeNextChar) {
  3385. // At any point in the loop, escapeNextChar is true if the previous
  3386. // character was a '\' and was not escaped.
  3387. out.push(c);
  3388. escapeNextChar = false;
  3389. } else {
  3390. if (c === '\\') {
  3391. escapeNextChar = true;
  3392. if ((isNumber(n) || n === '$')) {
  3393. out.push('$');
  3394. } else if (n !== '/' && n !== '\\') {
  3395. out.push('\\');
  3396. }
  3397. } else {
  3398. if (c === '$') {
  3399. out.push('$');
  3400. }
  3401. out.push(c);
  3402. if (n === '/') {
  3403. out.push('\\');
  3404. }
  3405. }
  3406. }
  3407. }
  3408. return out.join('');
  3409. }
  3410. // Unescape \ and / in the replace part, for PCRE mode.
  3411. function unescapeRegexReplace(str) {
  3412. var stream = new CodeMirror.StringStream(str);
  3413. var output = [];
  3414. while (!stream.eol()) {
  3415. // Search for \.
  3416. while (stream.peek() && stream.peek() != '\\') {
  3417. output.push(stream.next());
  3418. }
  3419. if (stream.match('\\/', true)) {
  3420. // \/ => /
  3421. output.push('/');
  3422. } else if (stream.match('\\\\', true)) {
  3423. // \\ => \
  3424. output.push('\\');
  3425. } else {
  3426. // Don't change anything
  3427. output.push(stream.next());
  3428. }
  3429. }
  3430. return output.join('');
  3431. }
  3432. /**
  3433. * Extract the regular expression from the query and return a Regexp object.
  3434. * Returns null if the query is blank.
  3435. * If ignoreCase is passed in, the Regexp object will have the 'i' flag set.
  3436. * If smartCase is passed in, and the query contains upper case letters,
  3437. * then ignoreCase is overridden, and the 'i' flag will not be set.
  3438. * If the query contains the /i in the flag part of the regular expression,
  3439. * then both ignoreCase and smartCase are ignored, and 'i' will be passed
  3440. * through to the Regex object.
  3441. */
  3442. function parseQuery(query, ignoreCase, smartCase) {
  3443. // First update the last search register
  3444. var lastSearchRegister = vimGlobalState.registerController.getRegister('/');
  3445. lastSearchRegister.setText(query);
  3446. // Check if the query is already a regex.
  3447. if (query instanceof RegExp) { return query; }
  3448. // First try to extract regex + flags from the input. If no flags found,
  3449. // extract just the regex. IE does not accept flags directly defined in
  3450. // the regex string in the form /regex/flags
  3451. var slashes = findUnescapedSlashes(query);
  3452. var regexPart;
  3453. var forceIgnoreCase;
  3454. if (!slashes.length) {
  3455. // Query looks like 'regexp'
  3456. regexPart = query;
  3457. } else {
  3458. // Query looks like 'regexp/...'
  3459. regexPart = query.substring(0, slashes[0]);
  3460. var flagsPart = query.substring(slashes[0]);
  3461. forceIgnoreCase = (flagsPart.indexOf('i') != -1);
  3462. }
  3463. if (!regexPart) {
  3464. return null;
  3465. }
  3466. if (!getOption('pcre')) {
  3467. regexPart = translateRegex(regexPart);
  3468. }
  3469. if (smartCase) {
  3470. ignoreCase = (/^[^A-Z]*$/).test(regexPart);
  3471. }
  3472. var regexp = new RegExp(regexPart,
  3473. (ignoreCase || forceIgnoreCase) ? 'i' : undefined);
  3474. return regexp;
  3475. }
  3476. function showConfirm(cm, text) {
  3477. if (cm.openNotification) {
  3478. cm.openNotification('<span style="color: red">' + text + '</span>',
  3479. {bottom: true, duration: 5000});
  3480. } else {
  3481. alert(text);
  3482. }
  3483. }
  3484. function makePrompt(prefix, desc) {
  3485. var raw = '';
  3486. if (prefix) {
  3487. raw += '<span style="font-family: monospace">' + prefix + '</span>';
  3488. }
  3489. raw += '<input type="text"/> ' +
  3490. '<span style="color: #888">';
  3491. if (desc) {
  3492. raw += '<span style="color: #888">';
  3493. raw += desc;
  3494. raw += '</span>';
  3495. }
  3496. return raw;
  3497. }
  3498. var searchPromptDesc = '(Javascript regexp)';
  3499. function showPrompt(cm, options) {
  3500. var shortText = (options.prefix || '') + ' ' + (options.desc || '');
  3501. var prompt = makePrompt(options.prefix, options.desc);
  3502. dialog(cm, prompt, shortText, options.onClose, options);
  3503. }
  3504. function regexEqual(r1, r2) {
  3505. if (r1 instanceof RegExp && r2 instanceof RegExp) {
  3506. var props = ['global', 'multiline', 'ignoreCase', 'source'];
  3507. for (var i = 0; i < props.length; i++) {
  3508. var prop = props[i];
  3509. if (r1[prop] !== r2[prop]) {
  3510. return false;
  3511. }
  3512. }
  3513. return true;
  3514. }
  3515. return false;
  3516. }
  3517. // Returns true if the query is valid.
  3518. function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {
  3519. if (!rawQuery) {
  3520. return;
  3521. }
  3522. var state = getSearchState(cm);
  3523. var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase);
  3524. if (!query) {
  3525. return;
  3526. }
  3527. highlightSearchMatches(cm, query);
  3528. if (regexEqual(query, state.getQuery())) {
  3529. return query;
  3530. }
  3531. state.setQuery(query);
  3532. return query;
  3533. }
  3534. function searchOverlay(query) {
  3535. if (query.source.charAt(0) == '^') {
  3536. var matchSol = true;
  3537. }
  3538. return {
  3539. token: function(stream) {
  3540. if (matchSol && !stream.sol()) {
  3541. stream.skipToEnd();
  3542. return;
  3543. }
  3544. var match = stream.match(query, false);
  3545. if (match) {
  3546. if (match[0].length == 0) {
  3547. // Matched empty string, skip to next.
  3548. stream.next();
  3549. return 'searching';
  3550. }
  3551. if (!stream.sol()) {
  3552. // Backtrack 1 to match \b
  3553. stream.backUp(1);
  3554. if (!query.exec(stream.next() + match[0])) {
  3555. stream.next();
  3556. return null;
  3557. }
  3558. }
  3559. stream.match(query);
  3560. return 'searching';
  3561. }
  3562. while (!stream.eol()) {
  3563. stream.next();
  3564. if (stream.match(query, false)) break;
  3565. }
  3566. },
  3567. query: query
  3568. };
  3569. }
  3570. function highlightSearchMatches(cm, query) {
  3571. var overlay = getSearchState(cm).getOverlay();
  3572. if (!overlay || query != overlay.query) {
  3573. if (overlay) {
  3574. cm.removeOverlay(overlay);
  3575. }
  3576. overlay = searchOverlay(query);
  3577. cm.addOverlay(overlay);
  3578. getSearchState(cm).setOverlay(overlay);
  3579. }
  3580. }
  3581. function findNext(cm, prev, query, repeat) {
  3582. if (repeat === undefined) { repeat = 1; }
  3583. return cm.operation(function() {
  3584. var pos = cm.getCursor();
  3585. var cursor = cm.getSearchCursor(query, pos);
  3586. for (var i = 0; i < repeat; i++) {
  3587. var found = cursor.find(prev);
  3588. if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); }
  3589. if (!found) {
  3590. // SearchCursor may have returned null because it hit EOF, wrap
  3591. // around and try again.
  3592. cursor = cm.getSearchCursor(query,
  3593. (prev) ? Pos(cm.lastLine()) : Pos(cm.firstLine(), 0) );
  3594. if (!cursor.find(prev)) {
  3595. return;
  3596. }
  3597. }
  3598. }
  3599. return cursor.from();
  3600. });
  3601. }
  3602. function clearSearchHighlight(cm) {
  3603. cm.removeOverlay(getSearchState(cm).getOverlay());
  3604. getSearchState(cm).setOverlay(null);
  3605. }
  3606. /**
  3607. * Check if pos is in the specified range, INCLUSIVE.
  3608. * Range can be specified with 1 or 2 arguments.
  3609. * If the first range argument is an array, treat it as an array of line
  3610. * numbers. Match pos against any of the lines.
  3611. * If the first range argument is a number,
  3612. * if there is only 1 range argument, check if pos has the same line
  3613. * number
  3614. * if there are 2 range arguments, then check if pos is in between the two
  3615. * range arguments.
  3616. */
  3617. function isInRange(pos, start, end) {
  3618. if (typeof pos != 'number') {
  3619. // Assume it is a cursor position. Get the line number.
  3620. pos = pos.line;
  3621. }
  3622. if (start instanceof Array) {
  3623. return inArray(pos, start);
  3624. } else {
  3625. if (end) {
  3626. return (pos >= start && pos <= end);
  3627. } else {
  3628. return pos == start;
  3629. }
  3630. }
  3631. }
  3632. function getUserVisibleLines(cm) {
  3633. var scrollInfo = cm.getScrollInfo();
  3634. var occludeToleranceTop = 6;
  3635. var occludeToleranceBottom = 10;
  3636. var from = cm.coordsChar({left:0, top: occludeToleranceTop + scrollInfo.top}, 'local');
  3637. var bottomY = scrollInfo.clientHeight - occludeToleranceBottom + scrollInfo.top;
  3638. var to = cm.coordsChar({left:0, top: bottomY}, 'local');
  3639. return {top: from.line, bottom: to.line};
  3640. }
  3641. // Ex command handling
  3642. // Care must be taken when adding to the default Ex command map. For any
  3643. // pair of commands that have a shared prefix, at least one of their
  3644. // shortNames must not match the prefix of the other command.
  3645. var defaultExCommandMap = [
  3646. { name: 'map' },
  3647. { name: 'imap', shortName: 'im' },
  3648. { name: 'nmap', shortName: 'nm' },
  3649. { name: 'vmap', shortName: 'vm' },
  3650. { name: 'unmap' },
  3651. { name: 'write', shortName: 'w' },
  3652. { name: 'undo', shortName: 'u' },
  3653. { name: 'redo', shortName: 'red' },
  3654. { name: 'set', shortName: 'set' },
  3655. { name: 'sort', shortName: 'sor' },
  3656. { name: 'substitute', shortName: 's', possiblyAsync: true },
  3657. { name: 'nohlsearch', shortName: 'noh' },
  3658. { name: 'delmarks', shortName: 'delm' },
  3659. { name: 'registers', shortName: 'reg', excludeFromCommandHistory: true },
  3660. { name: 'global', shortName: 'g' }
  3661. ];
  3662. var ExCommandDispatcher = function() {
  3663. this.buildCommandMap_();
  3664. };
  3665. ExCommandDispatcher.prototype = {
  3666. processCommand: function(cm, input, opt_params) {
  3667. var vim = cm.state.vim;
  3668. var commandHistoryRegister = vimGlobalState.registerController.getRegister(':');
  3669. var previousCommand = commandHistoryRegister.toString();
  3670. if (vim.visualMode) {
  3671. exitVisualMode(cm);
  3672. }
  3673. var inputStream = new CodeMirror.StringStream(input);
  3674. // update ": with the latest command whether valid or invalid
  3675. commandHistoryRegister.setText(input);
  3676. var params = opt_params || {};
  3677. params.input = input;
  3678. try {
  3679. this.parseInput_(cm, inputStream, params);
  3680. } catch(e) {
  3681. showConfirm(cm, e);
  3682. throw e;
  3683. }
  3684. var command;
  3685. var commandName;
  3686. if (!params.commandName) {
  3687. // If only a line range is defined, move to the line.
  3688. if (params.line !== undefined) {
  3689. commandName = 'move';
  3690. }
  3691. } else {
  3692. command = this.matchCommand_(params.commandName);
  3693. if (command) {
  3694. commandName = command.name;
  3695. if (command.excludeFromCommandHistory) {
  3696. commandHistoryRegister.setText(previousCommand);
  3697. }
  3698. this.parseCommandArgs_(inputStream, params, command);
  3699. if (command.type == 'exToKey') {
  3700. // Handle Ex to Key mapping.
  3701. for (var i = 0; i < command.toKeys.length; i++) {
  3702. CodeMirror.Vim.handleKey(cm, command.toKeys[i], 'mapping');
  3703. }
  3704. return;
  3705. } else if (command.type == 'exToEx') {
  3706. // Handle Ex to Ex mapping.
  3707. this.processCommand(cm, command.toInput);
  3708. return;
  3709. }
  3710. }
  3711. }
  3712. if (!commandName) {
  3713. showConfirm(cm, 'Not an editor command ":' + input + '"');
  3714. return;
  3715. }
  3716. try {
  3717. exCommands[commandName](cm, params);
  3718. // Possibly asynchronous commands (e.g. substitute, which might have a
  3719. // user confirmation), are responsible for calling the callback when
  3720. // done. All others have it taken care of for them here.
  3721. if ((!command || !command.possiblyAsync) && params.callback) {
  3722. params.callback();
  3723. }
  3724. } catch(e) {
  3725. showConfirm(cm, e);
  3726. throw e;
  3727. }
  3728. },
  3729. parseInput_: function(cm, inputStream, result) {
  3730. inputStream.eatWhile(':');
  3731. // Parse range.
  3732. if (inputStream.eat('%')) {
  3733. result.line = cm.firstLine();
  3734. result.lineEnd = cm.lastLine();
  3735. } else {
  3736. result.line = this.parseLineSpec_(cm, inputStream);
  3737. if (result.line !== undefined && inputStream.eat(',')) {
  3738. result.lineEnd = this.parseLineSpec_(cm, inputStream);
  3739. }
  3740. }
  3741. // Parse command name.
  3742. var commandMatch = inputStream.match(/^(\w+)/);
  3743. if (commandMatch) {
  3744. result.commandName = commandMatch[1];
  3745. } else {
  3746. result.commandName = inputStream.match(/.*/)[0];
  3747. }
  3748. return result;
  3749. },
  3750. parseLineSpec_: function(cm, inputStream) {
  3751. var numberMatch = inputStream.match(/^(\d+)/);
  3752. if (numberMatch) {
  3753. return parseInt(numberMatch[1], 10) - 1;
  3754. }
  3755. switch (inputStream.next()) {
  3756. case '.':
  3757. return cm.getCursor().line;
  3758. case '$':
  3759. return cm.lastLine();
  3760. case '\'':
  3761. var mark = cm.state.vim.marks[inputStream.next()];
  3762. if (mark && mark.find()) {
  3763. return mark.find().line;
  3764. }
  3765. throw new Error('Mark not set');
  3766. default:
  3767. inputStream.backUp(1);
  3768. return undefined;
  3769. }
  3770. },
  3771. parseCommandArgs_: function(inputStream, params, command) {
  3772. if (inputStream.eol()) {
  3773. return;
  3774. }
  3775. params.argString = inputStream.match(/.*/)[0];
  3776. // Parse command-line arguments
  3777. var delim = command.argDelimiter || /\s+/;
  3778. var args = trim(params.argString).split(delim);
  3779. if (args.length && args[0]) {
  3780. params.args = args;
  3781. }
  3782. },
  3783. matchCommand_: function(commandName) {
  3784. // Return the command in the command map that matches the shortest
  3785. // prefix of the passed in command name. The match is guaranteed to be
  3786. // unambiguous if the defaultExCommandMap's shortNames are set up
  3787. // correctly. (see @code{defaultExCommandMap}).
  3788. for (var i = commandName.length; i > 0; i--) {
  3789. var prefix = commandName.substring(0, i);
  3790. if (this.commandMap_[prefix]) {
  3791. var command = this.commandMap_[prefix];
  3792. if (command.name.indexOf(commandName) === 0) {
  3793. return command;
  3794. }
  3795. }
  3796. }
  3797. return null;
  3798. },
  3799. buildCommandMap_: function() {
  3800. this.commandMap_ = {};
  3801. for (var i = 0; i < defaultExCommandMap.length; i++) {
  3802. var command = defaultExCommandMap[i];
  3803. var key = command.shortName || command.name;
  3804. this.commandMap_[key] = command;
  3805. }
  3806. },
  3807. map: function(lhs, rhs, ctx) {
  3808. if (lhs != ':' && lhs.charAt(0) == ':') {
  3809. if (ctx) { throw Error('Mode not supported for ex mappings'); }
  3810. var commandName = lhs.substring(1);
  3811. if (rhs != ':' && rhs.charAt(0) == ':') {
  3812. // Ex to Ex mapping
  3813. this.commandMap_[commandName] = {
  3814. name: commandName,
  3815. type: 'exToEx',
  3816. toInput: rhs.substring(1),
  3817. user: true
  3818. };
  3819. } else {
  3820. // Ex to key mapping
  3821. this.commandMap_[commandName] = {
  3822. name: commandName,
  3823. type: 'exToKey',
  3824. toKeys: rhs,
  3825. user: true
  3826. };
  3827. }
  3828. } else {
  3829. if (rhs != ':' && rhs.charAt(0) == ':') {
  3830. // Key to Ex mapping.
  3831. var mapping = {
  3832. keys: lhs,
  3833. type: 'keyToEx',
  3834. exArgs: { input: rhs.substring(1) },
  3835. user: true};
  3836. if (ctx) { mapping.context = ctx; }
  3837. defaultKeymap.unshift(mapping);
  3838. } else {
  3839. // Key to key mapping
  3840. var mapping = {
  3841. keys: lhs,
  3842. type: 'keyToKey',
  3843. toKeys: rhs,
  3844. user: true
  3845. };
  3846. if (ctx) { mapping.context = ctx; }
  3847. defaultKeymap.unshift(mapping);
  3848. }
  3849. }
  3850. },
  3851. unmap: function(lhs, ctx) {
  3852. if (lhs != ':' && lhs.charAt(0) == ':') {
  3853. // Ex to Ex or Ex to key mapping
  3854. if (ctx) { throw Error('Mode not supported for ex mappings'); }
  3855. var commandName = lhs.substring(1);
  3856. if (this.commandMap_[commandName] && this.commandMap_[commandName].user) {
  3857. delete this.commandMap_[commandName];
  3858. return;
  3859. }
  3860. } else {
  3861. // Key to Ex or key to key mapping
  3862. var keys = lhs;
  3863. for (var i = 0; i < defaultKeymap.length; i++) {
  3864. if (keys == defaultKeymap[i].keys
  3865. && defaultKeymap[i].context === ctx
  3866. && defaultKeymap[i].user) {
  3867. defaultKeymap.splice(i, 1);
  3868. return;
  3869. }
  3870. }
  3871. }
  3872. throw Error('No such mapping.');
  3873. }
  3874. };
  3875. var exCommands = {
  3876. map: function(cm, params, ctx) {
  3877. var mapArgs = params.args;
  3878. if (!mapArgs || mapArgs.length < 2) {
  3879. if (cm) {
  3880. showConfirm(cm, 'Invalid mapping: ' + params.input);
  3881. }
  3882. return;
  3883. }
  3884. exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx);
  3885. },
  3886. imap: function(cm, params) { this.map(cm, params, 'insert'); },
  3887. nmap: function(cm, params) { this.map(cm, params, 'normal'); },
  3888. vmap: function(cm, params) { this.map(cm, params, 'visual'); },
  3889. unmap: function(cm, params, ctx) {
  3890. var mapArgs = params.args;
  3891. if (!mapArgs || mapArgs.length < 1) {
  3892. if (cm) {
  3893. showConfirm(cm, 'No such mapping: ' + params.input);
  3894. }
  3895. return;
  3896. }
  3897. exCommandDispatcher.unmap(mapArgs[0], ctx);
  3898. },
  3899. move: function(cm, params) {
  3900. commandDispatcher.processCommand(cm, cm.state.vim, {
  3901. type: 'motion',
  3902. motion: 'moveToLineOrEdgeOfDocument',
  3903. motionArgs: { forward: false, explicitRepeat: true,
  3904. linewise: true },
  3905. repeatOverride: params.line+1});
  3906. },
  3907. set: function(cm, params) {
  3908. var setArgs = params.args;
  3909. if (!setArgs || setArgs.length < 1) {
  3910. if (cm) {
  3911. showConfirm(cm, 'Invalid mapping: ' + params.input);
  3912. }
  3913. return;
  3914. }
  3915. var expr = setArgs[0].split('=');
  3916. var optionName = expr[0];
  3917. var value = expr[1];
  3918. var forceGet = false;
  3919. if (optionName.charAt(optionName.length - 1) == '?') {
  3920. // If post-fixed with ?, then the set is actually a get.
  3921. if (value) { throw Error('Trailing characters: ' + params.argString); }
  3922. optionName = optionName.substring(0, optionName.length - 1);
  3923. forceGet = true;
  3924. }
  3925. if (value === undefined && optionName.substring(0, 2) == 'no') {
  3926. // To set boolean options to false, the option name is prefixed with
  3927. // 'no'.
  3928. optionName = optionName.substring(2);
  3929. value = false;
  3930. }
  3931. var optionIsBoolean = options[optionName] && options[optionName].type == 'boolean';
  3932. if (optionIsBoolean && value == undefined) {
  3933. // Calling set with a boolean option sets it to true.
  3934. value = true;
  3935. }
  3936. if (!optionIsBoolean && !value || forceGet) {
  3937. var oldValue = getOption(optionName);
  3938. // If no value is provided, then we assume this is a get.
  3939. if (oldValue === true || oldValue === false) {
  3940. showConfirm(cm, ' ' + (oldValue ? '' : 'no') + optionName);
  3941. } else {
  3942. showConfirm(cm, ' ' + optionName + '=' + oldValue);
  3943. }
  3944. } else {
  3945. setOption(optionName, value);
  3946. }
  3947. },
  3948. registers: function(cm,params) {
  3949. var regArgs = params.args;
  3950. var registers = vimGlobalState.registerController.registers;
  3951. var regInfo = '----------Registers----------<br><br>';
  3952. if (!regArgs) {
  3953. for (var registerName in registers) {
  3954. var text = registers[registerName].toString();
  3955. if (text.length) {
  3956. regInfo += '"' + registerName + ' ' + text + '<br>';
  3957. }
  3958. }
  3959. } else {
  3960. var registerName;
  3961. regArgs = regArgs.join('');
  3962. for (var i = 0; i < regArgs.length; i++) {
  3963. registerName = regArgs.charAt(i);
  3964. if (!vimGlobalState.registerController.isValidRegister(registerName)) {
  3965. continue;
  3966. }
  3967. var register = registers[registerName] || new Register();
  3968. regInfo += '"' + registerName + ' ' + register.toString() + '<br>';
  3969. }
  3970. }
  3971. showConfirm(cm, regInfo);
  3972. },
  3973. sort: function(cm, params) {
  3974. var reverse, ignoreCase, unique, number;
  3975. function parseArgs() {
  3976. if (params.argString) {
  3977. var args = new CodeMirror.StringStream(params.argString);
  3978. if (args.eat('!')) { reverse = true; }
  3979. if (args.eol()) { return; }
  3980. if (!args.eatSpace()) { return 'Invalid arguments'; }
  3981. var opts = args.match(/[a-z]+/);
  3982. if (opts) {
  3983. opts = opts[0];
  3984. ignoreCase = opts.indexOf('i') != -1;
  3985. unique = opts.indexOf('u') != -1;
  3986. var decimal = opts.indexOf('d') != -1 && 1;
  3987. var hex = opts.indexOf('x') != -1 && 1;
  3988. var octal = opts.indexOf('o') != -1 && 1;
  3989. if (decimal + hex + octal > 1) { return 'Invalid arguments'; }
  3990. number = decimal && 'decimal' || hex && 'hex' || octal && 'octal';
  3991. }
  3992. if (args.eatSpace() && args.match(/\/.*\//)) { 'patterns not supported'; }
  3993. }
  3994. }
  3995. var err = parseArgs();
  3996. if (err) {
  3997. showConfirm(cm, err + ': ' + params.argString);
  3998. return;
  3999. }
  4000. var lineStart = params.line || cm.firstLine();
  4001. var lineEnd = params.lineEnd || params.line || cm.lastLine();
  4002. if (lineStart == lineEnd) { return; }
  4003. var curStart = Pos(lineStart, 0);
  4004. var curEnd = Pos(lineEnd, lineLength(cm, lineEnd));
  4005. var text = cm.getRange(curStart, curEnd).split('\n');
  4006. var numberRegex = (number == 'decimal') ? /(-?)([\d]+)/ :
  4007. (number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i :
  4008. (number == 'octal') ? /([0-7]+)/ : null;
  4009. var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null;
  4010. var numPart = [], textPart = [];
  4011. if (number) {
  4012. for (var i = 0; i < text.length; i++) {
  4013. if (numberRegex.exec(text[i])) {
  4014. numPart.push(text[i]);
  4015. } else {
  4016. textPart.push(text[i]);
  4017. }
  4018. }
  4019. } else {
  4020. textPart = text;
  4021. }
  4022. function compareFn(a, b) {
  4023. if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
  4024. if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); }
  4025. var anum = number && numberRegex.exec(a);
  4026. var bnum = number && numberRegex.exec(b);
  4027. if (!anum) { return a < b ? -1 : 1; }
  4028. anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix);
  4029. bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix);
  4030. return anum - bnum;
  4031. }
  4032. numPart.sort(compareFn);
  4033. textPart.sort(compareFn);
  4034. text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart);
  4035. if (unique) { // Remove duplicate lines
  4036. var textOld = text;
  4037. var lastLine;
  4038. text = [];
  4039. for (var i = 0; i < textOld.length; i++) {
  4040. if (textOld[i] != lastLine) {
  4041. text.push(textOld[i]);
  4042. }
  4043. lastLine = textOld[i];
  4044. }
  4045. }
  4046. cm.replaceRange(text.join('\n'), curStart, curEnd);
  4047. },
  4048. global: function(cm, params) {
  4049. // a global command is of the form
  4050. // :[range]g/pattern/[cmd]
  4051. // argString holds the string /pattern/[cmd]
  4052. var argString = params.argString;
  4053. if (!argString) {
  4054. showConfirm(cm, 'Regular Expression missing from global');
  4055. return;
  4056. }
  4057. // range is specified here
  4058. var lineStart = (params.line !== undefined) ? params.line : cm.firstLine();
  4059. var lineEnd = params.lineEnd || params.line || cm.lastLine();
  4060. // get the tokens from argString
  4061. var tokens = splitBySlash(argString);
  4062. var regexPart = argString, cmd;
  4063. if (tokens.length) {
  4064. regexPart = tokens[0];
  4065. cmd = tokens.slice(1, tokens.length).join('/');
  4066. }
  4067. if (regexPart) {
  4068. // If regex part is empty, then use the previous query. Otherwise
  4069. // use the regex part as the new query.
  4070. try {
  4071. updateSearchQuery(cm, regexPart, true /** ignoreCase */,
  4072. true /** smartCase */);
  4073. } catch (e) {
  4074. showConfirm(cm, 'Invalid regex: ' + regexPart);
  4075. return;
  4076. }
  4077. }
  4078. // now that we have the regexPart, search for regex matches in the
  4079. // specified range of lines
  4080. var query = getSearchState(cm).getQuery();
  4081. var matchedLines = [], content = '';
  4082. for (var i = lineStart; i <= lineEnd; i++) {
  4083. var matched = query.test(cm.getLine(i));
  4084. if (matched) {
  4085. matchedLines.push(i+1);
  4086. content+= cm.getLine(i) + '<br>';
  4087. }
  4088. }
  4089. // if there is no [cmd], just display the list of matched lines
  4090. if (!cmd) {
  4091. showConfirm(cm, content);
  4092. return;
  4093. }
  4094. var index = 0;
  4095. var nextCommand = function() {
  4096. if (index < matchedLines.length) {
  4097. var command = matchedLines[index] + cmd;
  4098. exCommandDispatcher.processCommand(cm, command, {
  4099. callback: nextCommand
  4100. });
  4101. }
  4102. index++;
  4103. };
  4104. nextCommand();
  4105. },
  4106. substitute: function(cm, params) {
  4107. if (!cm.getSearchCursor) {
  4108. throw new Error('Search feature not available. Requires searchcursor.js or ' +
  4109. 'any other getSearchCursor implementation.');
  4110. }
  4111. var argString = params.argString;
  4112. var tokens = argString ? splitBySlash(argString) : [];
  4113. var regexPart, replacePart = '', trailing, flagsPart, count;
  4114. var confirm = false; // Whether to confirm each replace.
  4115. var global = false; // True to replace all instances on a line, false to replace only 1.
  4116. if (tokens.length) {
  4117. regexPart = tokens[0];
  4118. replacePart = tokens[1];
  4119. if (replacePart !== undefined) {
  4120. if (getOption('pcre')) {
  4121. replacePart = unescapeRegexReplace(replacePart);
  4122. } else {
  4123. replacePart = translateRegexReplace(replacePart);
  4124. }
  4125. vimGlobalState.lastSubstituteReplacePart = replacePart;
  4126. }
  4127. trailing = tokens[2] ? tokens[2].split(' ') : [];
  4128. } else {
  4129. // either the argString is empty or its of the form ' hello/world'
  4130. // actually splitBySlash returns a list of tokens
  4131. // only if the string starts with a '/'
  4132. if (argString && argString.length) {
  4133. showConfirm(cm, 'Substitutions should be of the form ' +
  4134. ':s/pattern/replace/');
  4135. return;
  4136. }
  4137. }
  4138. // After the 3rd slash, we can have flags followed by a space followed
  4139. // by count.
  4140. if (trailing) {
  4141. flagsPart = trailing[0];
  4142. count = parseInt(trailing[1]);
  4143. if (flagsPart) {
  4144. if (flagsPart.indexOf('c') != -1) {
  4145. confirm = true;
  4146. flagsPart.replace('c', '');
  4147. }
  4148. if (flagsPart.indexOf('g') != -1) {
  4149. global = true;
  4150. flagsPart.replace('g', '');
  4151. }
  4152. regexPart = regexPart + '/' + flagsPart;
  4153. }
  4154. }
  4155. if (regexPart) {
  4156. // If regex part is empty, then use the previous query. Otherwise use
  4157. // the regex part as the new query.
  4158. try {
  4159. updateSearchQuery(cm, regexPart, true /** ignoreCase */,
  4160. true /** smartCase */);
  4161. } catch (e) {
  4162. showConfirm(cm, 'Invalid regex: ' + regexPart);
  4163. return;
  4164. }
  4165. }
  4166. replacePart = replacePart || vimGlobalState.lastSubstituteReplacePart;
  4167. if (replacePart === undefined) {
  4168. showConfirm(cm, 'No previous substitute regular expression');
  4169. return;
  4170. }
  4171. var state = getSearchState(cm);
  4172. var query = state.getQuery();
  4173. var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line;
  4174. var lineEnd = params.lineEnd || lineStart;
  4175. if (count) {
  4176. lineStart = lineEnd;
  4177. lineEnd = lineStart + count - 1;
  4178. }
  4179. var startPos = clipCursorToContent(cm, Pos(lineStart, 0));
  4180. var cursor = cm.getSearchCursor(query, startPos);
  4181. doReplace(cm, confirm, global, lineStart, lineEnd, cursor, query, replacePart, params.callback);
  4182. },
  4183. redo: CodeMirror.commands.redo,
  4184. undo: CodeMirror.commands.undo,
  4185. write: function(cm) {
  4186. if (CodeMirror.commands.save) {
  4187. // If a save command is defined, call it.
  4188. CodeMirror.commands.save(cm);
  4189. } else {
  4190. // Saves to text area if no save command is defined.
  4191. cm.save();
  4192. }
  4193. },
  4194. nohlsearch: function(cm) {
  4195. clearSearchHighlight(cm);
  4196. },
  4197. delmarks: function(cm, params) {
  4198. if (!params.argString || !trim(params.argString)) {
  4199. showConfirm(cm, 'Argument required');
  4200. return;
  4201. }
  4202. var state = cm.state.vim;
  4203. var stream = new CodeMirror.StringStream(trim(params.argString));
  4204. while (!stream.eol()) {
  4205. stream.eatSpace();
  4206. // Record the streams position at the beginning of the loop for use
  4207. // in error messages.
  4208. var count = stream.pos;
  4209. if (!stream.match(/[a-zA-Z]/, false)) {
  4210. showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
  4211. return;
  4212. }
  4213. var sym = stream.next();
  4214. // Check if this symbol is part of a range
  4215. if (stream.match('-', true)) {
  4216. // This symbol is part of a range.
  4217. // The range must terminate at an alphabetic character.
  4218. if (!stream.match(/[a-zA-Z]/, false)) {
  4219. showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
  4220. return;
  4221. }
  4222. var startMark = sym;
  4223. var finishMark = stream.next();
  4224. // The range must terminate at an alphabetic character which
  4225. // shares the same case as the start of the range.
  4226. if (isLowerCase(startMark) && isLowerCase(finishMark) ||
  4227. isUpperCase(startMark) && isUpperCase(finishMark)) {
  4228. var start = startMark.charCodeAt(0);
  4229. var finish = finishMark.charCodeAt(0);
  4230. if (start >= finish) {
  4231. showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
  4232. return;
  4233. }
  4234. // Because marks are always ASCII values, and we have
  4235. // determined that they are the same case, we can use
  4236. // their char codes to iterate through the defined range.
  4237. for (var j = 0; j <= finish - start; j++) {
  4238. var mark = String.fromCharCode(start + j);
  4239. delete state.marks[mark];
  4240. }
  4241. } else {
  4242. showConfirm(cm, 'Invalid argument: ' + startMark + '-');
  4243. return;
  4244. }
  4245. } else {
  4246. // This symbol is a valid mark, and is not part of a range.
  4247. delete state.marks[sym];
  4248. }
  4249. }
  4250. }
  4251. };
  4252. var exCommandDispatcher = new ExCommandDispatcher();
  4253. /**
  4254. * @param {CodeMirror} cm CodeMirror instance we are in.
  4255. * @param {boolean} confirm Whether to confirm each replace.
  4256. * @param {Cursor} lineStart Line to start replacing from.
  4257. * @param {Cursor} lineEnd Line to stop replacing at.
  4258. * @param {RegExp} query Query for performing matches with.
  4259. * @param {string} replaceWith Text to replace matches with. May contain $1,
  4260. * $2, etc for replacing captured groups using Javascript replace.
  4261. * @param {function()} callback A callback for when the replace is done.
  4262. */
  4263. function doReplace(cm, confirm, global, lineStart, lineEnd, searchCursor, query,
  4264. replaceWith, callback) {
  4265. // Set up all the functions.
  4266. cm.state.vim.exMode = true;
  4267. var done = false;
  4268. var lastPos = searchCursor.from();
  4269. function replaceAll() {
  4270. cm.operation(function() {
  4271. while (!done) {
  4272. replace();
  4273. next();
  4274. }
  4275. stop();
  4276. });
  4277. }
  4278. function replace() {
  4279. var text = cm.getRange(searchCursor.from(), searchCursor.to());
  4280. var newText = text.replace(query, replaceWith);
  4281. searchCursor.replace(newText);
  4282. }
  4283. function next() {
  4284. var found;
  4285. // The below only loops to skip over multiple occurrences on the same
  4286. // line when 'global' is not true.
  4287. while(found = searchCursor.findNext() &&
  4288. isInRange(searchCursor.from(), lineStart, lineEnd)) {
  4289. if (!global && lastPos && searchCursor.from().line == lastPos.line) {
  4290. continue;
  4291. }
  4292. cm.scrollIntoView(searchCursor.from(), 30);
  4293. cm.setSelection(searchCursor.from(), searchCursor.to());
  4294. lastPos = searchCursor.from();
  4295. done = false;
  4296. return;
  4297. }
  4298. done = true;
  4299. }
  4300. function stop(close) {
  4301. if (close) { close(); }
  4302. cm.focus();
  4303. if (lastPos) {
  4304. cm.setCursor(lastPos);
  4305. var vim = cm.state.vim;
  4306. vim.exMode = false;
  4307. vim.lastHPos = vim.lastHSPos = lastPos.ch;
  4308. }
  4309. if (callback) { callback(); }
  4310. }
  4311. function onPromptKeyDown(e, _value, close) {
  4312. // Swallow all keys.
  4313. CodeMirror.e_stop(e);
  4314. var keyName = CodeMirror.keyName(e);
  4315. switch (keyName) {
  4316. case 'Y':
  4317. replace(); next(); break;
  4318. case 'N':
  4319. next(); break;
  4320. case 'A':
  4321. // replaceAll contains a call to close of its own. We don't want it
  4322. // to fire too early or multiple times.
  4323. var savedCallback = callback;
  4324. callback = undefined;
  4325. cm.operation(replaceAll);
  4326. callback = savedCallback;
  4327. break;
  4328. case 'L':
  4329. replace();
  4330. // fall through and exit.
  4331. case 'Q':
  4332. case 'Esc':
  4333. case 'Ctrl-C':
  4334. case 'Ctrl-[':
  4335. stop(close);
  4336. break;
  4337. }
  4338. if (done) { stop(close); }
  4339. return true;
  4340. }
  4341. // Actually do replace.
  4342. next();
  4343. if (done) {
  4344. showConfirm(cm, 'No matches for ' + query.source);
  4345. return;
  4346. }
  4347. if (!confirm) {
  4348. replaceAll();
  4349. if (callback) { callback(); };
  4350. return;
  4351. }
  4352. showPrompt(cm, {
  4353. prefix: 'replace with <strong>' + replaceWith + '</strong> (y/n/a/q/l)',
  4354. onKeyDown: onPromptKeyDown
  4355. });
  4356. }
  4357. CodeMirror.keyMap.vim = {
  4358. attach: attachVimMap,
  4359. detach: detachVimMap
  4360. };
  4361. function exitInsertMode(cm) {
  4362. var vim = cm.state.vim;
  4363. var macroModeState = vimGlobalState.macroModeState;
  4364. var insertModeChangeRegister = vimGlobalState.registerController.getRegister('.');
  4365. var isPlaying = macroModeState.isPlaying;
  4366. var lastChange = macroModeState.lastInsertModeChanges;
  4367. // In case of visual block, the insertModeChanges are not saved as a
  4368. // single word, so we convert them to a single word
  4369. // so as to update the ". register as expected in real vim.
  4370. var text = [];
  4371. if (!isPlaying) {
  4372. var selLength = lastChange.inVisualBlock ? vim.lastSelection.visualBlock.height : 1;
  4373. var changes = lastChange.changes;
  4374. var text = [];
  4375. var i = 0;
  4376. // In case of multiple selections in blockwise visual,
  4377. // the inserted text, for example: 'f<Backspace>oo', is stored as
  4378. // 'f', 'f', InsertModeKey 'o', 'o', 'o', 'o'. (if you have a block with 2 lines).
  4379. // We push the contents of the changes array as per the following:
  4380. // 1. In case of InsertModeKey, just increment by 1.
  4381. // 2. In case of a character, jump by selLength (2 in the example).
  4382. while (i < changes.length) {
  4383. // This loop will convert 'ff<bs>oooo' to 'f<bs>oo'.
  4384. text.push(changes[i]);
  4385. if (changes[i] instanceof InsertModeKey) {
  4386. i++;
  4387. } else {
  4388. i+= selLength;
  4389. }
  4390. }
  4391. lastChange.changes = text;
  4392. cm.off('change', onChange);
  4393. CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
  4394. }
  4395. if (!isPlaying && vim.insertModeRepeat > 1) {
  4396. // Perform insert mode repeat for commands like 3,a and 3,o.
  4397. repeatLastEdit(cm, vim, vim.insertModeRepeat - 1,
  4398. true /** repeatForInsert */);
  4399. vim.lastEditInputState.repeatOverride = vim.insertModeRepeat;
  4400. }
  4401. delete vim.insertModeRepeat;
  4402. vim.insertMode = false;
  4403. cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1);
  4404. cm.setOption('keyMap', 'vim');
  4405. cm.setOption('disableInput', true);
  4406. cm.toggleOverwrite(false); // exit replace mode if we were in it.
  4407. // update the ". register before exiting insert mode
  4408. insertModeChangeRegister.setText(lastChange.changes.join(''));
  4409. CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
  4410. if (macroModeState.isRecording) {
  4411. logInsertModeChange(macroModeState);
  4412. }
  4413. }
  4414. // The timeout in milliseconds for the two-character ESC keymap should be
  4415. // adjusted according to your typing speed to prevent false positives.
  4416. defineOption('insertModeEscKeysTimeout', 200, 'number');
  4417. CodeMirror.keyMap['vim-insert'] = {
  4418. // TODO: override navigation keys so that Esc will cancel automatic
  4419. // indentation from o, O, i_<CR>
  4420. 'Ctrl-N': 'autocomplete',
  4421. 'Ctrl-P': 'autocomplete',
  4422. 'Enter': function(cm) {
  4423. var fn = CodeMirror.commands.newlineAndIndentContinueComment ||
  4424. CodeMirror.commands.newlineAndIndent;
  4425. fn(cm);
  4426. },
  4427. fallthrough: ['default'],
  4428. attach: attachVimMap,
  4429. detach: detachVimMap
  4430. };
  4431. CodeMirror.keyMap['await-second'] = {
  4432. fallthrough: ['vim-insert'],
  4433. attach: attachVimMap,
  4434. detach: detachVimMap
  4435. };
  4436. CodeMirror.keyMap['vim-replace'] = {
  4437. 'Backspace': 'goCharLeft',
  4438. fallthrough: ['vim-insert'],
  4439. attach: attachVimMap,
  4440. detach: detachVimMap
  4441. };
  4442. function executeMacroRegister(cm, vim, macroModeState, registerName) {
  4443. var register = vimGlobalState.registerController.getRegister(registerName);
  4444. var keyBuffer = register.keyBuffer;
  4445. var imc = 0;
  4446. macroModeState.isPlaying = true;
  4447. macroModeState.replaySearchQueries = register.searchQueries.slice(0);
  4448. for (var i = 0; i < keyBuffer.length; i++) {
  4449. var text = keyBuffer[i];
  4450. var match, key;
  4451. while (text) {
  4452. // Pull off one command key, which is either a single character
  4453. // or a special sequence wrapped in '<' and '>', e.g. '<Space>'.
  4454. match = (/<\w+-.+?>|<\w+>|./).exec(text);
  4455. key = match[0];
  4456. text = text.substring(match.index + key.length);
  4457. CodeMirror.Vim.handleKey(cm, key, 'macro');
  4458. if (vim.insertMode) {
  4459. var changes = register.insertModeChanges[imc++].changes;
  4460. vimGlobalState.macroModeState.lastInsertModeChanges.changes =
  4461. changes;
  4462. repeatInsertModeChanges(cm, changes, 1);
  4463. exitInsertMode(cm);
  4464. }
  4465. }
  4466. };
  4467. macroModeState.isPlaying = false;
  4468. }
  4469. function logKey(macroModeState, key) {
  4470. if (macroModeState.isPlaying) { return; }
  4471. var registerName = macroModeState.latestRegister;
  4472. var register = vimGlobalState.registerController.getRegister(registerName);
  4473. if (register) {
  4474. register.pushText(key);
  4475. }
  4476. }
  4477. function logInsertModeChange(macroModeState) {
  4478. if (macroModeState.isPlaying) { return; }
  4479. var registerName = macroModeState.latestRegister;
  4480. var register = vimGlobalState.registerController.getRegister(registerName);
  4481. if (register) {
  4482. register.pushInsertModeChanges(macroModeState.lastInsertModeChanges);
  4483. }
  4484. }
  4485. function logSearchQuery(macroModeState, query) {
  4486. if (macroModeState.isPlaying) { return; }
  4487. var registerName = macroModeState.latestRegister;
  4488. var register = vimGlobalState.registerController.getRegister(registerName);
  4489. if (register) {
  4490. register.pushSearchQuery(query);
  4491. }
  4492. }
  4493. /**
  4494. * Listens for changes made in insert mode.
  4495. * Should only be active in insert mode.
  4496. */
  4497. function onChange(_cm, changeObj) {
  4498. var macroModeState = vimGlobalState.macroModeState;
  4499. var lastChange = macroModeState.lastInsertModeChanges;
  4500. if (!macroModeState.isPlaying) {
  4501. while(changeObj) {
  4502. lastChange.expectCursorActivityForChange = true;
  4503. if (changeObj.origin == '+input' || changeObj.origin == 'paste'
  4504. || changeObj.origin === undefined /* only in testing */) {
  4505. var text = changeObj.text.join('\n');
  4506. lastChange.changes.push(text);
  4507. }
  4508. // Change objects may be chained with next.
  4509. changeObj = changeObj.next;
  4510. }
  4511. }
  4512. }
  4513. /**
  4514. * Listens for any kind of cursor activity on CodeMirror.
  4515. */
  4516. function onCursorActivity(cm) {
  4517. var vim = cm.state.vim;
  4518. if (vim.insertMode) {
  4519. // Tracking cursor activity in insert mode (for macro support).
  4520. var macroModeState = vimGlobalState.macroModeState;
  4521. if (macroModeState.isPlaying) { return; }
  4522. var lastChange = macroModeState.lastInsertModeChanges;
  4523. if (lastChange.expectCursorActivityForChange) {
  4524. lastChange.expectCursorActivityForChange = false;
  4525. } else {
  4526. // Cursor moved outside the context of an edit. Reset the change.
  4527. lastChange.changes = [];
  4528. }
  4529. } else if (!cm.curOp.isVimOp) {
  4530. handleExternalSelection(cm, vim);
  4531. }
  4532. if (vim.visualMode) {
  4533. updateFakeCursor(cm);
  4534. }
  4535. }
  4536. function updateFakeCursor(cm) {
  4537. var vim = cm.state.vim;
  4538. var from = copyCursor(vim.sel.head);
  4539. var to = offsetCursor(from, 0, 1);
  4540. if (vim.fakeCursor) {
  4541. vim.fakeCursor.clear();
  4542. }
  4543. vim.fakeCursor = cm.markText(from, to, {className: 'cm-animate-fat-cursor'});
  4544. }
  4545. function handleExternalSelection(cm, vim) {
  4546. var anchor = cm.getCursor('anchor');
  4547. var head = cm.getCursor('head');
  4548. // Enter or exit visual mode to match mouse selection.
  4549. if (vim.visualMode && cursorEqual(head, anchor) && lineLength(cm, head.line) > head.ch) {
  4550. exitVisualMode(cm, false);
  4551. } else if (!vim.visualMode && !vim.insertMode && cm.somethingSelected()) {
  4552. vim.visualMode = true;
  4553. vim.visualLine = false;
  4554. CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
  4555. }
  4556. if (vim.visualMode) {
  4557. // Bind CodeMirror selection model to vim selection model.
  4558. // Mouse selections are considered visual characterwise.
  4559. var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0;
  4560. var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0;
  4561. head = offsetCursor(head, 0, headOffset);
  4562. anchor = offsetCursor(anchor, 0, anchorOffset);
  4563. vim.sel = {
  4564. anchor: anchor,
  4565. head: head
  4566. };
  4567. updateMark(cm, vim, '<', cursorMin(head, anchor));
  4568. updateMark(cm, vim, '>', cursorMax(head, anchor));
  4569. } else if (!vim.insertMode) {
  4570. // Reset lastHPos if selection was modified by something outside of vim mode e.g. by mouse.
  4571. vim.lastHPos = cm.getCursor().ch;
  4572. }
  4573. }
  4574. /** Wrapper for special keys pressed in insert mode */
  4575. function InsertModeKey(keyName) {
  4576. this.keyName = keyName;
  4577. }
  4578. /**
  4579. * Handles raw key down events from the text area.
  4580. * - Should only be active in insert mode.
  4581. * - For recording deletes in insert mode.
  4582. */
  4583. function onKeyEventTargetKeyDown(e) {
  4584. var macroModeState = vimGlobalState.macroModeState;
  4585. var lastChange = macroModeState.lastInsertModeChanges;
  4586. var keyName = CodeMirror.keyName(e);
  4587. function onKeyFound() {
  4588. lastChange.changes.push(new InsertModeKey(keyName));
  4589. return true;
  4590. }
  4591. if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
  4592. CodeMirror.lookupKey(keyName, 'vim-insert', onKeyFound);
  4593. }
  4594. }
  4595. /**
  4596. * Repeats the last edit, which includes exactly 1 command and at most 1
  4597. * insert. Operator and motion commands are read from lastEditInputState,
  4598. * while action commands are read from lastEditActionCommand.
  4599. *
  4600. * If repeatForInsert is true, then the function was called by
  4601. * exitInsertMode to repeat the insert mode changes the user just made. The
  4602. * corresponding enterInsertMode call was made with a count.
  4603. */
  4604. function repeatLastEdit(cm, vim, repeat, repeatForInsert) {
  4605. var macroModeState = vimGlobalState.macroModeState;
  4606. macroModeState.isPlaying = true;
  4607. var isAction = !!vim.lastEditActionCommand;
  4608. var cachedInputState = vim.inputState;
  4609. function repeatCommand() {
  4610. if (isAction) {
  4611. commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand);
  4612. } else {
  4613. commandDispatcher.evalInput(cm, vim);
  4614. }
  4615. }
  4616. function repeatInsert(repeat) {
  4617. if (macroModeState.lastInsertModeChanges.changes.length > 0) {
  4618. // For some reason, repeat cw in desktop VIM does not repeat
  4619. // insert mode changes. Will conform to that behavior.
  4620. repeat = !vim.lastEditActionCommand ? 1 : repeat;
  4621. var changeObject = macroModeState.lastInsertModeChanges;
  4622. repeatInsertModeChanges(cm, changeObject.changes, repeat);
  4623. }
  4624. }
  4625. vim.inputState = vim.lastEditInputState;
  4626. if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) {
  4627. // o and O repeat have to be interlaced with insert repeats so that the
  4628. // insertions appear on separate lines instead of the last line.
  4629. for (var i = 0; i < repeat; i++) {
  4630. repeatCommand();
  4631. repeatInsert(1);
  4632. }
  4633. } else {
  4634. if (!repeatForInsert) {
  4635. // Hack to get the cursor to end up at the right place. If I is
  4636. // repeated in insert mode repeat, cursor will be 1 insert
  4637. // change set left of where it should be.
  4638. repeatCommand();
  4639. }
  4640. repeatInsert(repeat);
  4641. }
  4642. vim.inputState = cachedInputState;
  4643. if (vim.insertMode && !repeatForInsert) {
  4644. // Don't exit insert mode twice. If repeatForInsert is set, then we
  4645. // were called by an exitInsertMode call lower on the stack.
  4646. exitInsertMode(cm);
  4647. }
  4648. macroModeState.isPlaying = false;
  4649. };
  4650. function repeatInsertModeChanges(cm, changes, repeat) {
  4651. function keyHandler(binding) {
  4652. if (typeof binding == 'string') {
  4653. CodeMirror.commands[binding](cm);
  4654. } else {
  4655. binding(cm);
  4656. }
  4657. return true;
  4658. }
  4659. var head = cm.getCursor('head');
  4660. var inVisualBlock = vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock;
  4661. if (inVisualBlock) {
  4662. // Set up block selection again for repeating the changes.
  4663. var vim = cm.state.vim;
  4664. var lastSel = vim.lastSelection;
  4665. var offset = getOffset(lastSel.anchor, lastSel.head);
  4666. selectForInsert(cm, head, offset.line + 1);
  4667. repeat = cm.listSelections().length;
  4668. cm.setCursor(head);
  4669. }
  4670. for (var i = 0; i < repeat; i++) {
  4671. if (inVisualBlock) {
  4672. cm.setCursor(offsetCursor(head, i, 0));
  4673. }
  4674. for (var j = 0; j < changes.length; j++) {
  4675. var change = changes[j];
  4676. if (change instanceof InsertModeKey) {
  4677. CodeMirror.lookupKey(change.keyName, 'vim-insert', keyHandler);
  4678. } else {
  4679. var cur = cm.getCursor();
  4680. cm.replaceRange(change, cur, cur);
  4681. }
  4682. }
  4683. }
  4684. if (inVisualBlock) {
  4685. cm.setCursor(offsetCursor(head, 0, 1));
  4686. }
  4687. }
  4688. resetVimGlobalState();
  4689. return vimApi;
  4690. };
  4691. // Initialize Vim and make it available as an API.
  4692. CodeMirror.Vim = Vim();
  4693. });