keybinding-vim.js 201 KB

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