vim.js 232 KB

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