vim.js 200 KB

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