You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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