Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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