vim.js 196 KB

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