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

keybinding-vim.js 192KB

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