vim.js 187 KB

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