22b3d72765b6ec7c787f375e68324531.js 237 KB

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