vim.js 151 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123
  1. /**
  2. * Supported keybindings:
  3. *
  4. * Motion:
  5. * h, j, k, l
  6. * gj, gk
  7. * e, E, w, W, b, B, ge, gE
  8. * f<character>, F<character>, t<character>, T<character>
  9. * $, ^, 0, -, +, _
  10. * gg, G
  11. * %
  12. * '<character>, `<character>
  13. *
  14. * Operator:
  15. * d, y, c
  16. * dd, yy, cc
  17. * g~, g~g~
  18. * >, <, >>, <<
  19. *
  20. * Operator-Motion:
  21. * x, X, D, Y, C, ~
  22. *
  23. * Action:
  24. * a, i, s, A, I, S, o, O
  25. * zz, z., z<CR>, zt, zb, z-
  26. * J
  27. * u, Ctrl-r
  28. * m<character>
  29. * r<character>
  30. *
  31. * Modes:
  32. * ESC - leave insert mode, visual mode, and clear input state.
  33. * Ctrl-[, Ctrl-c - same as ESC.
  34. *
  35. * Registers: unnamed, -, a-z, A-Z, 0-9
  36. * (Does not respect the special case for number registers when delete
  37. * operator is made with these commands: %, (, ), , /, ?, n, N, {, } )
  38. * TODO: Implement the remaining registers.
  39. * Marks: a-z, A-Z, and 0-9
  40. * TODO: Implement the remaining special marks. They have more complex
  41. * behavior.
  42. *
  43. * Events:
  44. * 'vim-mode-change' - raised on the editor anytime the current mode changes,
  45. * Event object: {mode: "visual", subMode: "linewise"}
  46. *
  47. * Code structure:
  48. * 1. Default keymap
  49. * 2. Variable declarations and short basic helpers
  50. * 3. Instance (External API) implementation
  51. * 4. Internal state tracking objects (input state, counter) implementation
  52. * and instanstiation
  53. * 5. Key handler (the main command dispatcher) implementation
  54. * 6. Motion, operator, and action implementations
  55. * 7. Helper functions for the key handler, motions, operators, and actions
  56. * 8. Set up Vim to work as a keymap for CodeMirror.
  57. */
  58. (function(mod) {
  59. if (typeof exports == "object" && typeof module == "object") // CommonJS
  60. mod(require("../lib/codemirror"), require("../addon/search/searchcursor"), require("../addon/dialog/dialog"));
  61. else if (typeof define == "function" && define.amd) // AMD
  62. define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/dialog/dialog"], mod);
  63. else // Plain browser env
  64. mod(CodeMirror);
  65. })(function(CodeMirror) {
  66. 'use strict';
  67. var defaultKeymap = [
  68. // Key to key mapping. This goes first to make it possible to override
  69. // existing mappings.
  70. { keys: ['<Left>'], type: 'keyToKey', toKeys: ['h'] },
  71. { keys: ['<Right>'], type: 'keyToKey', toKeys: ['l'] },
  72. { keys: ['<Up>'], type: 'keyToKey', toKeys: ['k'] },
  73. { keys: ['<Down>'], type: 'keyToKey', toKeys: ['j'] },
  74. { keys: ['<Space>'], type: 'keyToKey', toKeys: ['l'] },
  75. { keys: ['<BS>'], type: 'keyToKey', toKeys: ['h'] },
  76. { keys: ['<C-Space>'], type: 'keyToKey', toKeys: ['W'] },
  77. { keys: ['<C-BS>'], type: 'keyToKey', toKeys: ['B'] },
  78. { keys: ['<S-Space>'], type: 'keyToKey', toKeys: ['w'] },
  79. { keys: ['<S-BS>'], type: 'keyToKey', toKeys: ['b'] },
  80. { keys: ['<C-n>'], type: 'keyToKey', toKeys: ['j'] },
  81. { keys: ['<C-p>'], type: 'keyToKey', toKeys: ['k'] },
  82. { keys: ['<C-[>'], type: 'keyToKey', toKeys: ['<Esc>'] },
  83. { keys: ['<C-c>'], type: 'keyToKey', toKeys: ['<Esc>'] },
  84. { keys: ['s'], type: 'keyToKey', toKeys: ['c', 'l'], context: 'normal' },
  85. { keys: ['s'], type: 'keyToKey', toKeys: ['x', 'i'], context: 'visual'},
  86. { keys: ['S'], type: 'keyToKey', toKeys: ['c', 'c'], context: 'normal' },
  87. { keys: ['S'], type: 'keyToKey', toKeys: ['d', 'c', 'c'], context: 'visual' },
  88. { keys: ['<Home>'], type: 'keyToKey', toKeys: ['0'] },
  89. { keys: ['<End>'], type: 'keyToKey', toKeys: ['$'] },
  90. { keys: ['<PageUp>'], type: 'keyToKey', toKeys: ['<C-b>'] },
  91. { keys: ['<PageDown>'], type: 'keyToKey', toKeys: ['<C-f>'] },
  92. { keys: ['<CR>'], type: 'keyToKey', toKeys: ['j', '^'], context: 'normal' },
  93. // Motions
  94. { keys: ['H'], type: 'motion',
  95. motion: 'moveToTopLine',
  96. motionArgs: { linewise: true, toJumplist: true }},
  97. { keys: ['M'], type: 'motion',
  98. motion: 'moveToMiddleLine',
  99. motionArgs: { linewise: true, toJumplist: true }},
  100. { keys: ['L'], type: 'motion',
  101. motion: 'moveToBottomLine',
  102. motionArgs: { linewise: true, toJumplist: true }},
  103. { keys: ['h'], type: 'motion',
  104. motion: 'moveByCharacters',
  105. motionArgs: { forward: false }},
  106. { keys: ['l'], type: 'motion',
  107. motion: 'moveByCharacters',
  108. motionArgs: { forward: true }},
  109. { keys: ['j'], type: 'motion',
  110. motion: 'moveByLines',
  111. motionArgs: { forward: true, linewise: true }},
  112. { keys: ['k'], type: 'motion',
  113. motion: 'moveByLines',
  114. motionArgs: { forward: false, linewise: true }},
  115. { keys: ['g','j'], type: 'motion',
  116. motion: 'moveByDisplayLines',
  117. motionArgs: { forward: true }},
  118. { keys: ['g','k'], type: 'motion',
  119. motion: 'moveByDisplayLines',
  120. motionArgs: { forward: false }},
  121. { keys: ['w'], type: 'motion',
  122. motion: 'moveByWords',
  123. motionArgs: { forward: true, wordEnd: false }},
  124. { keys: ['W'], type: 'motion',
  125. motion: 'moveByWords',
  126. motionArgs: { forward: true, wordEnd: false, bigWord: true }},
  127. { keys: ['e'], type: 'motion',
  128. motion: 'moveByWords',
  129. motionArgs: { forward: true, wordEnd: true, inclusive: true }},
  130. { keys: ['E'], type: 'motion',
  131. motion: 'moveByWords',
  132. motionArgs: { forward: true, wordEnd: true, bigWord: true,
  133. inclusive: true }},
  134. { keys: ['b'], type: 'motion',
  135. motion: 'moveByWords',
  136. motionArgs: { forward: false, wordEnd: false }},
  137. { keys: ['B'], type: 'motion',
  138. motion: 'moveByWords',
  139. motionArgs: { forward: false, wordEnd: false, bigWord: true }},
  140. { keys: ['g', 'e'], type: 'motion',
  141. motion: 'moveByWords',
  142. motionArgs: { forward: false, wordEnd: true, inclusive: true }},
  143. { keys: ['g', 'E'], type: 'motion',
  144. motion: 'moveByWords',
  145. motionArgs: { forward: false, wordEnd: true, bigWord: true,
  146. inclusive: true }},
  147. { keys: ['{'], type: 'motion', motion: 'moveByParagraph',
  148. motionArgs: { forward: false, toJumplist: true }},
  149. { keys: ['}'], type: 'motion', motion: 'moveByParagraph',
  150. motionArgs: { forward: true, toJumplist: true }},
  151. { keys: ['<C-f>'], type: 'motion',
  152. motion: 'moveByPage', motionArgs: { forward: true }},
  153. { keys: ['<C-b>'], type: 'motion',
  154. motion: 'moveByPage', motionArgs: { forward: false }},
  155. { keys: ['<C-d>'], type: 'motion',
  156. motion: 'moveByScroll',
  157. motionArgs: { forward: true, explicitRepeat: true }},
  158. { keys: ['<C-u>'], type: 'motion',
  159. motion: 'moveByScroll',
  160. motionArgs: { forward: false, explicitRepeat: true }},
  161. { keys: ['g', 'g'], type: 'motion',
  162. motion: 'moveToLineOrEdgeOfDocument',
  163. motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},
  164. { keys: ['G'], type: 'motion',
  165. motion: 'moveToLineOrEdgeOfDocument',
  166. motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},
  167. { keys: ['0'], type: 'motion', motion: 'moveToStartOfLine' },
  168. { keys: ['^'], type: 'motion',
  169. motion: 'moveToFirstNonWhiteSpaceCharacter' },
  170. { keys: ['+'], type: 'motion',
  171. motion: 'moveByLines',
  172. motionArgs: { forward: true, toFirstChar:true }},
  173. { keys: ['-'], type: 'motion',
  174. motion: 'moveByLines',
  175. motionArgs: { forward: false, toFirstChar:true }},
  176. { keys: ['_'], type: 'motion',
  177. motion: 'moveByLines',
  178. motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},
  179. { keys: ['$'], type: 'motion',
  180. motion: 'moveToEol',
  181. motionArgs: { inclusive: true }},
  182. { keys: ['%'], type: 'motion',
  183. motion: 'moveToMatchedSymbol',
  184. motionArgs: { inclusive: true, toJumplist: true }},
  185. { keys: ['f', 'character'], type: 'motion',
  186. motion: 'moveToCharacter',
  187. motionArgs: { forward: true , inclusive: true }},
  188. { keys: ['F', 'character'], type: 'motion',
  189. motion: 'moveToCharacter',
  190. motionArgs: { forward: false }},
  191. { keys: ['t', 'character'], type: 'motion',
  192. motion: 'moveTillCharacter',
  193. motionArgs: { forward: true, inclusive: true }},
  194. { keys: ['T', 'character'], type: 'motion',
  195. motion: 'moveTillCharacter',
  196. motionArgs: { forward: false }},
  197. { keys: [';'], type: 'motion', motion: 'repeatLastCharacterSearch',
  198. motionArgs: { forward: true }},
  199. { keys: [','], type: 'motion', motion: 'repeatLastCharacterSearch',
  200. motionArgs: { forward: false }},
  201. { keys: ['\'', 'character'], type: 'motion', motion: 'goToMark',
  202. motionArgs: {toJumplist: true}},
  203. { keys: ['`', 'character'], type: 'motion', motion: 'goToMark',
  204. motionArgs: {toJumplist: true}},
  205. { keys: [']', '`'], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
  206. { keys: ['[', '`'], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
  207. { keys: [']', '\''], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
  208. { keys: ['[', '\''], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
  209. { keys: [']', 'character'], type: 'motion',
  210. motion: 'moveToSymbol',
  211. motionArgs: { forward: true, toJumplist: true}},
  212. { keys: ['[', 'character'], type: 'motion',
  213. motion: 'moveToSymbol',
  214. motionArgs: { forward: false, toJumplist: true}},
  215. { keys: ['|'], type: 'motion',
  216. motion: 'moveToColumn',
  217. motionArgs: { }},
  218. { keys: ['o'], type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: { },context:'visual'},
  219. // Operators
  220. { keys: ['d'], type: 'operator', operator: 'delete' },
  221. { keys: ['y'], type: 'operator', operator: 'yank' },
  222. { keys: ['c'], type: 'operator', operator: 'change' },
  223. { keys: ['>'], type: 'operator', operator: 'indent',
  224. operatorArgs: { indentRight: true }},
  225. { keys: ['<'], type: 'operator', operator: 'indent',
  226. operatorArgs: { indentRight: false }},
  227. { keys: ['g', '~'], type: 'operator', operator: 'swapcase' },
  228. { keys: ['n'], type: 'motion', motion: 'findNext',
  229. motionArgs: { forward: true, toJumplist: true }},
  230. { keys: ['N'], type: 'motion', motion: 'findNext',
  231. motionArgs: { forward: false, toJumplist: true }},
  232. // Operator-Motion dual commands
  233. { keys: ['x'], type: 'operatorMotion', operator: 'delete',
  234. motion: 'moveByCharacters', motionArgs: { forward: true },
  235. operatorMotionArgs: { visualLine: false }},
  236. { keys: ['X'], type: 'operatorMotion', operator: 'delete',
  237. motion: 'moveByCharacters', motionArgs: { forward: false },
  238. operatorMotionArgs: { visualLine: true }},
  239. { keys: ['D'], type: 'operatorMotion', operator: 'delete',
  240. motion: 'moveToEol', motionArgs: { inclusive: true },
  241. operatorMotionArgs: { visualLine: true }},
  242. { keys: ['Y'], type: 'operatorMotion', operator: 'yank',
  243. motion: 'moveToEol', motionArgs: { inclusive: true },
  244. operatorMotionArgs: { visualLine: true }},
  245. { keys: ['C'], type: 'operatorMotion',
  246. operator: 'change',
  247. motion: 'moveToEol', motionArgs: { inclusive: true },
  248. operatorMotionArgs: { visualLine: true }},
  249. { keys: ['~'], type: 'operatorMotion',
  250. operator: 'swapcase', operatorArgs: { shouldMoveCursor: true },
  251. motion: 'moveByCharacters', motionArgs: { forward: true }},
  252. // Actions
  253. { keys: ['<C-i>'], type: 'action', action: 'jumpListWalk',
  254. actionArgs: { forward: true }},
  255. { keys: ['<C-o>'], type: 'action', action: 'jumpListWalk',
  256. actionArgs: { forward: false }},
  257. { keys: ['<C-e>'], type: 'action',
  258. action: 'scroll',
  259. actionArgs: { forward: true, linewise: true }},
  260. { keys: ['<C-y>'], type: 'action',
  261. action: 'scroll',
  262. actionArgs: { forward: false, linewise: true }},
  263. { keys: ['a'], type: 'action', action: 'enterInsertMode', isEdit: true,
  264. actionArgs: { insertAt: 'charAfter' }},
  265. { keys: ['A'], type: 'action', action: 'enterInsertMode', isEdit: true,
  266. actionArgs: { insertAt: 'eol' }},
  267. { keys: ['i'], type: 'action', action: 'enterInsertMode', isEdit: true,
  268. actionArgs: { insertAt: 'inplace' }},
  269. { keys: ['I'], type: 'action', action: 'enterInsertMode', isEdit: true,
  270. actionArgs: { insertAt: 'firstNonBlank' }},
  271. { keys: ['o'], type: 'action', action: 'newLineAndEnterInsertMode',
  272. isEdit: true, interlaceInsertRepeat: true,
  273. actionArgs: { after: true }},
  274. { keys: ['O'], type: 'action', action: 'newLineAndEnterInsertMode',
  275. isEdit: true, interlaceInsertRepeat: true,
  276. actionArgs: { after: false }},
  277. { keys: ['v'], type: 'action', action: 'toggleVisualMode' },
  278. { keys: ['V'], type: 'action', action: 'toggleVisualMode',
  279. actionArgs: { linewise: true }},
  280. { keys: ['g', 'v'], type: 'action', action: 'reselectLastSelection' },
  281. { keys: ['J'], type: 'action', action: 'joinLines', isEdit: true },
  282. { keys: ['p'], type: 'action', action: 'paste', isEdit: true,
  283. actionArgs: { after: true, isEdit: true }},
  284. { keys: ['P'], type: 'action', action: 'paste', isEdit: true,
  285. actionArgs: { after: false, isEdit: true }},
  286. { keys: ['r', 'character'], type: 'action', action: 'replace', isEdit: true },
  287. { keys: ['@', 'character'], type: 'action', action: 'replayMacro' },
  288. { keys: ['q', 'character'], type: 'action', action: 'enterMacroRecordMode' },
  289. // Handle Replace-mode as a special case of insert mode.
  290. { keys: ['R'], type: 'action', action: 'enterInsertMode', isEdit: true,
  291. actionArgs: { replace: true }},
  292. { keys: ['u'], type: 'action', action: 'undo' },
  293. { keys: ['<C-r>'], type: 'action', action: 'redo' },
  294. { keys: ['m', 'character'], type: 'action', action: 'setMark' },
  295. { keys: ['"', 'character'], type: 'action', action: 'setRegister' },
  296. { keys: ['z', 'z'], type: 'action', action: 'scrollToCursor',
  297. actionArgs: { position: 'center' }},
  298. { keys: ['z', '.'], type: 'action', action: 'scrollToCursor',
  299. actionArgs: { position: 'center' },
  300. motion: 'moveToFirstNonWhiteSpaceCharacter' },
  301. { keys: ['z', 't'], type: 'action', action: 'scrollToCursor',
  302. actionArgs: { position: 'top' }},
  303. { keys: ['z', '<CR>'], type: 'action', action: 'scrollToCursor',
  304. actionArgs: { position: 'top' },
  305. motion: 'moveToFirstNonWhiteSpaceCharacter' },
  306. { keys: ['z', '-'], type: 'action', action: 'scrollToCursor',
  307. actionArgs: { position: 'bottom' }},
  308. { keys: ['z', 'b'], type: 'action', action: 'scrollToCursor',
  309. actionArgs: { position: 'bottom' },
  310. motion: 'moveToFirstNonWhiteSpaceCharacter' },
  311. { keys: ['.'], type: 'action', action: 'repeatLastEdit' },
  312. { keys: ['<C-a>'], type: 'action', action: 'incrementNumberToken',
  313. isEdit: true,
  314. actionArgs: {increase: true, backtrack: false}},
  315. { keys: ['<C-x>'], type: 'action', action: 'incrementNumberToken',
  316. isEdit: true,
  317. actionArgs: {increase: false, backtrack: false}},
  318. // Text object motions
  319. { keys: ['a', 'character'], type: 'motion',
  320. motion: 'textObjectManipulation' },
  321. { keys: ['i', 'character'], type: 'motion',
  322. motion: 'textObjectManipulation',
  323. motionArgs: { textObjectInner: true }},
  324. // Search
  325. { keys: ['/'], type: 'search',
  326. searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},
  327. { keys: ['?'], type: 'search',
  328. searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},
  329. { keys: ['*'], type: 'search',
  330. searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},
  331. { keys: ['#'], type: 'search',
  332. searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},
  333. // Ex command
  334. { keys: [':'], type: 'ex' }
  335. ];
  336. var Pos = CodeMirror.Pos;
  337. var Vim = function() {
  338. CodeMirror.defineOption('vimMode', false, function(cm, val) {
  339. if (val) {
  340. cm.setOption('keyMap', 'vim');
  341. cm.setOption('disableInput', true);
  342. CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
  343. cm.on('beforeSelectionChange', beforeSelectionChange);
  344. maybeInitVimState(cm);
  345. CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm));
  346. } else if (cm.state.vim) {
  347. cm.setOption('keyMap', 'default');
  348. cm.setOption('disableInput', false);
  349. cm.off('beforeSelectionChange', beforeSelectionChange);
  350. CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm));
  351. cm.state.vim = null;
  352. }
  353. });
  354. function beforeSelectionChange(cm, obj) {
  355. var vim = cm.state.vim;
  356. if (vim.insertMode || vim.exMode) return;
  357. var head = obj.ranges[0].head;
  358. var anchor = obj.ranges[0].anchor;
  359. if (head.ch && head.ch == cm.doc.getLine(head.line).length) {
  360. var pos = Pos(head.line, head.ch - 1);
  361. obj.update([{anchor: cursorEqual(head, anchor) ? pos : anchor,
  362. head: pos}]);
  363. }
  364. }
  365. function getOnPasteFn(cm) {
  366. var vim = cm.state.vim;
  367. if (!vim.onPasteFn) {
  368. vim.onPasteFn = function() {
  369. if (!vim.insertMode) {
  370. cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
  371. actions.enterInsertMode(cm, {}, vim);
  372. }
  373. };
  374. }
  375. return vim.onPasteFn;
  376. }
  377. var numberRegex = /[\d]/;
  378. var wordRegexp = [(/\w/), (/[^\w\s]/)], bigWordRegexp = [(/\S/)];
  379. function makeKeyRange(start, size) {
  380. var keys = [];
  381. for (var i = start; i < start + size; i++) {
  382. keys.push(String.fromCharCode(i));
  383. }
  384. return keys;
  385. }
  386. var upperCaseAlphabet = makeKeyRange(65, 26);
  387. var lowerCaseAlphabet = makeKeyRange(97, 26);
  388. var numbers = makeKeyRange(48, 10);
  389. var specialSymbols = '~`!@#$%^&*()_-+=[{}]\\|/?.,<>:;"\''.split('');
  390. var specialKeys = ['Left', 'Right', 'Up', 'Down', 'Space', 'Backspace',
  391. 'Esc', 'Home', 'End', 'PageUp', 'PageDown', 'Enter'];
  392. var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']);
  393. var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"']);
  394. function isLine(cm, line) {
  395. return line >= cm.firstLine() && line <= cm.lastLine();
  396. }
  397. function isLowerCase(k) {
  398. return (/^[a-z]$/).test(k);
  399. }
  400. function isMatchableSymbol(k) {
  401. return '()[]{}'.indexOf(k) != -1;
  402. }
  403. function isNumber(k) {
  404. return numberRegex.test(k);
  405. }
  406. function isUpperCase(k) {
  407. return (/^[A-Z]$/).test(k);
  408. }
  409. function isWhiteSpaceString(k) {
  410. return (/^\s*$/).test(k);
  411. }
  412. function inArray(val, arr) {
  413. for (var i = 0; i < arr.length; i++) {
  414. if (arr[i] == val) {
  415. return true;
  416. }
  417. }
  418. return false;
  419. }
  420. var options = {};
  421. function defineOption(name, defaultValue, type) {
  422. if (defaultValue === undefined) { throw Error('defaultValue is required'); }
  423. if (!type) { type = 'string'; }
  424. options[name] = {
  425. type: type,
  426. defaultValue: defaultValue
  427. };
  428. setOption(name, defaultValue);
  429. }
  430. function setOption(name, value) {
  431. var option = options[name];
  432. if (!option) {
  433. throw Error('Unknown option: ' + name);
  434. }
  435. if (option.type == 'boolean') {
  436. if (value && value !== true) {
  437. throw Error('Invalid argument: ' + name + '=' + value);
  438. } else if (value !== false) {
  439. // Boolean options are set to true if value is not defined.
  440. value = true;
  441. }
  442. }
  443. option.value = option.type == 'boolean' ? !!value : value;
  444. }
  445. function getOption(name) {
  446. var option = options[name];
  447. if (!option) {
  448. throw Error('Unknown option: ' + name);
  449. }
  450. return option.value;
  451. }
  452. var createCircularJumpList = function() {
  453. var size = 100;
  454. var pointer = -1;
  455. var head = 0;
  456. var tail = 0;
  457. var buffer = new Array(size);
  458. function add(cm, oldCur, newCur) {
  459. var current = pointer % size;
  460. var curMark = buffer[current];
  461. function useNextSlot(cursor) {
  462. var next = ++pointer % size;
  463. var trashMark = buffer[next];
  464. if (trashMark) {
  465. trashMark.clear();
  466. }
  467. buffer[next] = cm.setBookmark(cursor);
  468. }
  469. if (curMark) {
  470. var markPos = curMark.find();
  471. // avoid recording redundant cursor position
  472. if (markPos && !cursorEqual(markPos, oldCur)) {
  473. useNextSlot(oldCur);
  474. }
  475. } else {
  476. useNextSlot(oldCur);
  477. }
  478. useNextSlot(newCur);
  479. head = pointer;
  480. tail = pointer - size + 1;
  481. if (tail < 0) {
  482. tail = 0;
  483. }
  484. }
  485. function move(cm, offset) {
  486. pointer += offset;
  487. if (pointer > head) {
  488. pointer = head;
  489. } else if (pointer < tail) {
  490. pointer = tail;
  491. }
  492. var mark = buffer[(size + pointer) % size];
  493. // skip marks that are temporarily removed from text buffer
  494. if (mark && !mark.find()) {
  495. var inc = offset > 0 ? 1 : -1;
  496. var newCur;
  497. var oldCur = cm.getCursor();
  498. do {
  499. pointer += inc;
  500. mark = buffer[(size + pointer) % size];
  501. // skip marks that are the same as current position
  502. if (mark &&
  503. (newCur = mark.find()) &&
  504. !cursorEqual(oldCur, newCur)) {
  505. break;
  506. }
  507. } while (pointer < head && pointer > tail);
  508. }
  509. return mark;
  510. }
  511. return {
  512. cachedCursor: undefined, //used for # and * jumps
  513. add: add,
  514. move: move
  515. };
  516. };
  517. // Returns an object to track the changes associated insert mode. It
  518. // clones the object that is passed in, or creates an empty object one if
  519. // none is provided.
  520. var createInsertModeChanges = function(c) {
  521. if (c) {
  522. // Copy construction
  523. return {
  524. changes: c.changes,
  525. expectCursorActivityForChange: c.expectCursorActivityForChange
  526. };
  527. }
  528. return {
  529. // Change list
  530. changes: [],
  531. // Set to true on change, false on cursorActivity.
  532. expectCursorActivityForChange: false
  533. };
  534. };
  535. function MacroModeState() {
  536. this.latestRegister = undefined;
  537. this.isPlaying = false;
  538. this.isRecording = false;
  539. this.onRecordingDone = undefined;
  540. this.lastInsertModeChanges = createInsertModeChanges();
  541. }
  542. MacroModeState.prototype = {
  543. exitMacroRecordMode: function() {
  544. var macroModeState = vimGlobalState.macroModeState;
  545. macroModeState.onRecordingDone(); // close dialog
  546. macroModeState.onRecordingDone = undefined;
  547. macroModeState.isRecording = false;
  548. },
  549. enterMacroRecordMode: function(cm, registerName) {
  550. var register =
  551. vimGlobalState.registerController.getRegister(registerName);
  552. if (register) {
  553. register.clear();
  554. this.latestRegister = registerName;
  555. this.onRecordingDone = cm.openDialog(
  556. '(recording)['+registerName+']', null, {bottom:true});
  557. this.isRecording = true;
  558. }
  559. }
  560. };
  561. function maybeInitVimState(cm) {
  562. if (!cm.state.vim) {
  563. // Store instance state in the CodeMirror object.
  564. cm.state.vim = {
  565. inputState: new InputState(),
  566. // Vim's input state that triggered the last edit, used to repeat
  567. // motions and operators with '.'.
  568. lastEditInputState: undefined,
  569. // Vim's action command before the last edit, used to repeat actions
  570. // with '.' and insert mode repeat.
  571. lastEditActionCommand: undefined,
  572. // When using jk for navigation, if you move from a longer line to a
  573. // shorter line, the cursor may clip to the end of the shorter line.
  574. // If j is pressed again and cursor goes to the next line, the
  575. // cursor should go back to its horizontal position on the longer
  576. // line if it can. This is to keep track of the horizontal position.
  577. lastHPos: -1,
  578. // Doing the same with screen-position for gj/gk
  579. lastHSPos: -1,
  580. // The last motion command run. Cleared if a non-motion command gets
  581. // executed in between.
  582. lastMotion: null,
  583. marks: {},
  584. insertMode: false,
  585. // Repeat count for changes made in insert mode, triggered by key
  586. // sequences like 3,i. Only exists when insertMode is true.
  587. insertModeRepeat: undefined,
  588. visualMode: false,
  589. // If we are in visual line mode. No effect if visualMode is false.
  590. visualLine: false,
  591. lastSelection: null
  592. };
  593. }
  594. return cm.state.vim;
  595. }
  596. var vimGlobalState;
  597. function resetVimGlobalState() {
  598. vimGlobalState = {
  599. // The current search query.
  600. searchQuery: null,
  601. // Whether we are searching backwards.
  602. searchIsReversed: false,
  603. jumpList: createCircularJumpList(),
  604. macroModeState: new MacroModeState,
  605. // Recording latest f, t, F or T motion command.
  606. lastChararacterSearch: {increment:0, forward:true, selectedCharacter:''},
  607. registerController: new RegisterController({})
  608. };
  609. for (var optionName in options) {
  610. var option = options[optionName];
  611. option.value = option.defaultValue;
  612. }
  613. }
  614. var vimApi= {
  615. buildKeyMap: function() {
  616. // TODO: Convert keymap into dictionary format for fast lookup.
  617. },
  618. // Testing hook, though it might be useful to expose the register
  619. // controller anyways.
  620. getRegisterController: function() {
  621. return vimGlobalState.registerController;
  622. },
  623. // Testing hook.
  624. resetVimGlobalState_: resetVimGlobalState,
  625. // Testing hook.
  626. getVimGlobalState_: function() {
  627. return vimGlobalState;
  628. },
  629. // Testing hook.
  630. maybeInitVimState_: maybeInitVimState,
  631. InsertModeKey: InsertModeKey,
  632. map: function(lhs, rhs, ctx) {
  633. // Add user defined key bindings.
  634. exCommandDispatcher.map(lhs, rhs, ctx);
  635. },
  636. setOption: setOption,
  637. getOption: getOption,
  638. defineOption: defineOption,
  639. defineEx: function(name, prefix, func){
  640. if (name.indexOf(prefix) !== 0) {
  641. throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered');
  642. }
  643. exCommands[name]=func;
  644. exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'};
  645. },
  646. // This is the outermost function called by CodeMirror, after keys have
  647. // been mapped to their Vim equivalents.
  648. handleKey: function(cm, key) {
  649. var command;
  650. var vim = maybeInitVimState(cm);
  651. var macroModeState = vimGlobalState.macroModeState;
  652. if (macroModeState.isRecording) {
  653. if (key == 'q') {
  654. macroModeState.exitMacroRecordMode();
  655. vim.inputState = new InputState();
  656. return;
  657. }
  658. }
  659. if (key == '<Esc>') {
  660. // Clear input state and get back to normal mode.
  661. vim.inputState = new InputState();
  662. if (vim.visualMode) {
  663. exitVisualMode(cm);
  664. }
  665. return;
  666. }
  667. // Enter visual mode when the mouse selects text.
  668. if (!vim.visualMode &&
  669. !cursorEqual(cm.getCursor('head'), cm.getCursor('anchor'))) {
  670. vim.visualMode = true;
  671. vim.visualLine = false;
  672. CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
  673. cm.on('mousedown', exitVisualMode);
  674. }
  675. if (key != '0' || (key == '0' && vim.inputState.getRepeat() === 0)) {
  676. // Have to special case 0 since it's both a motion and a number.
  677. command = commandDispatcher.matchCommand(key, defaultKeymap, vim);
  678. }
  679. if (!command) {
  680. if (isNumber(key)) {
  681. // Increment count unless count is 0 and key is 0.
  682. vim.inputState.pushRepeatDigit(key);
  683. }
  684. if (macroModeState.isRecording) {
  685. logKey(macroModeState, key);
  686. }
  687. return;
  688. }
  689. if (command.type == 'keyToKey') {
  690. // TODO: prevent infinite recursion.
  691. for (var i = 0; i < command.toKeys.length; i++) {
  692. this.handleKey(cm, command.toKeys[i]);
  693. }
  694. } else {
  695. if (macroModeState.isRecording) {
  696. logKey(macroModeState, key);
  697. }
  698. commandDispatcher.processCommand(cm, vim, command);
  699. }
  700. },
  701. handleEx: function(cm, input) {
  702. exCommandDispatcher.processCommand(cm, input);
  703. }
  704. };
  705. // Represents the current input state.
  706. function InputState() {
  707. this.prefixRepeat = [];
  708. this.motionRepeat = [];
  709. this.operator = null;
  710. this.operatorArgs = null;
  711. this.motion = null;
  712. this.motionArgs = null;
  713. this.keyBuffer = []; // For matching multi-key commands.
  714. this.registerName = null; // Defaults to the unnamed register.
  715. }
  716. InputState.prototype.pushRepeatDigit = function(n) {
  717. if (!this.operator) {
  718. this.prefixRepeat = this.prefixRepeat.concat(n);
  719. } else {
  720. this.motionRepeat = this.motionRepeat.concat(n);
  721. }
  722. };
  723. InputState.prototype.getRepeat = function() {
  724. var repeat = 0;
  725. if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) {
  726. repeat = 1;
  727. if (this.prefixRepeat.length > 0) {
  728. repeat *= parseInt(this.prefixRepeat.join(''), 10);
  729. }
  730. if (this.motionRepeat.length > 0) {
  731. repeat *= parseInt(this.motionRepeat.join(''), 10);
  732. }
  733. }
  734. return repeat;
  735. };
  736. /*
  737. * Register stores information about copy and paste registers. Besides
  738. * text, a register must store whether it is linewise (i.e., when it is
  739. * pasted, should it insert itself into a new line, or should the text be
  740. * inserted at the cursor position.)
  741. */
  742. function Register(text, linewise) {
  743. this.clear();
  744. this.keyBuffer = [text || ''];
  745. this.insertModeChanges = [];
  746. this.linewise = !!linewise;
  747. }
  748. Register.prototype = {
  749. setText: function(text, linewise) {
  750. this.keyBuffer = [text || ''];
  751. this.linewise = !!linewise;
  752. },
  753. pushText: function(text, linewise) {
  754. // if this register has ever been set to linewise, use linewise.
  755. if (linewise || this.linewise) {
  756. this.keyBuffer.push('\n');
  757. this.linewise = true;
  758. }
  759. this.keyBuffer.push(text);
  760. },
  761. pushInsertModeChanges: function(changes) {
  762. this.insertModeChanges.push(createInsertModeChanges(changes));
  763. },
  764. clear: function() {
  765. this.keyBuffer = [];
  766. this.insertModeChanges = [];
  767. this.linewise = false;
  768. },
  769. toString: function() {
  770. return this.keyBuffer.join('');
  771. }
  772. };
  773. /*
  774. * vim registers allow you to keep many independent copy and paste buffers.
  775. * See http://usevim.com/2012/04/13/registers/ for an introduction.
  776. *
  777. * RegisterController keeps the state of all the registers. An initial
  778. * state may be passed in. The unnamed register '"' will always be
  779. * overridden.
  780. */
  781. function RegisterController(registers) {
  782. this.registers = registers;
  783. this.unnamedRegister = registers['"'] = new Register();
  784. }
  785. RegisterController.prototype = {
  786. pushText: function(registerName, operator, text, linewise) {
  787. if (linewise && text.charAt(0) == '\n') {
  788. text = text.slice(1) + '\n';
  789. }
  790. if (linewise && text.charAt(text.length - 1) !== '\n'){
  791. text += '\n';
  792. }
  793. // Lowercase and uppercase registers refer to the same register.
  794. // Uppercase just means append.
  795. var register = this.isValidRegister(registerName) ?
  796. this.getRegister(registerName) : null;
  797. // if no register/an invalid register was specified, things go to the
  798. // default registers
  799. if (!register) {
  800. switch (operator) {
  801. case 'yank':
  802. // The 0 register contains the text from the most recent yank.
  803. this.registers['0'] = new Register(text, linewise);
  804. break;
  805. case 'delete':
  806. case 'change':
  807. if (text.indexOf('\n') == -1) {
  808. // Delete less than 1 line. Update the small delete register.
  809. this.registers['-'] = new Register(text, linewise);
  810. } else {
  811. // Shift down the contents of the numbered registers and put the
  812. // deleted text into register 1.
  813. this.shiftNumericRegisters_();
  814. this.registers['1'] = new Register(text, linewise);
  815. }
  816. break;
  817. }
  818. // Make sure the unnamed register is set to what just happened
  819. this.unnamedRegister.setText(text, linewise);
  820. return;
  821. }
  822. // If we've gotten to this point, we've actually specified a register
  823. var append = isUpperCase(registerName);
  824. if (append) {
  825. register.append(text, linewise);
  826. // The unnamed register always has the same value as the last used
  827. // register.
  828. this.unnamedRegister.append(text, linewise);
  829. } else {
  830. register.setText(text, linewise);
  831. this.unnamedRegister.setText(text, linewise);
  832. }
  833. },
  834. // Gets the register named @name. If one of @name doesn't already exist,
  835. // create it. If @name is invalid, return the unnamedRegister.
  836. getRegister: function(name) {
  837. if (!this.isValidRegister(name)) {
  838. return this.unnamedRegister;
  839. }
  840. name = name.toLowerCase();
  841. if (!this.registers[name]) {
  842. this.registers[name] = new Register();
  843. }
  844. return this.registers[name];
  845. },
  846. isValidRegister: function(name) {
  847. return name && inArray(name, validRegisters);
  848. },
  849. shiftNumericRegisters_: function() {
  850. for (var i = 9; i >= 2; i--) {
  851. this.registers[i] = this.getRegister('' + (i - 1));
  852. }
  853. }
  854. };
  855. var commandDispatcher = {
  856. matchCommand: function(key, keyMap, vim) {
  857. var inputState = vim.inputState;
  858. var keys = inputState.keyBuffer.concat(key);
  859. var matchedCommands = [];
  860. var selectedCharacter;
  861. for (var i = 0; i < keyMap.length; i++) {
  862. var command = keyMap[i];
  863. if (matchKeysPartial(keys, command.keys)) {
  864. if (inputState.operator && command.type == 'action') {
  865. // Ignore matched action commands after an operator. Operators
  866. // only operate on motions. This check is really for text
  867. // objects since aW, a[ etcs conflicts with a.
  868. continue;
  869. }
  870. // Match commands that take <character> as an argument.
  871. if (command.keys[keys.length - 1] == 'character') {
  872. selectedCharacter = keys[keys.length - 1];
  873. if (selectedCharacter.length>1){
  874. switch(selectedCharacter){
  875. case '<CR>':
  876. selectedCharacter='\n';
  877. break;
  878. case '<Space>':
  879. selectedCharacter=' ';
  880. break;
  881. default:
  882. continue;
  883. }
  884. }
  885. }
  886. // Add the command to the list of matched commands. Choose the best
  887. // command later.
  888. matchedCommands.push(command);
  889. }
  890. }
  891. // Returns the command if it is a full match, or null if not.
  892. function getFullyMatchedCommandOrNull(command) {
  893. if (keys.length < command.keys.length) {
  894. // Matches part of a multi-key command. Buffer and wait for next
  895. // stroke.
  896. inputState.keyBuffer.push(key);
  897. return null;
  898. } else {
  899. if (command.keys[keys.length - 1] == 'character') {
  900. inputState.selectedCharacter = selectedCharacter;
  901. }
  902. // Clear the buffer since a full match was found.
  903. inputState.keyBuffer = [];
  904. return command;
  905. }
  906. }
  907. if (!matchedCommands.length) {
  908. // Clear the buffer since there were no matches.
  909. inputState.keyBuffer = [];
  910. return null;
  911. } else if (matchedCommands.length == 1) {
  912. return getFullyMatchedCommandOrNull(matchedCommands[0]);
  913. } else {
  914. // Find the best match in the list of matchedCommands.
  915. var context = vim.visualMode ? 'visual' : 'normal';
  916. var bestMatch; // Default to first in the list.
  917. for (var i = 0; i < matchedCommands.length; i++) {
  918. var current = matchedCommands[i];
  919. if (current.context == context) {
  920. bestMatch = current;
  921. break;
  922. } else if (!bestMatch && !current.context) {
  923. // Only set an imperfect match to best match if no best match is
  924. // set and the imperfect match is not restricted to another
  925. // context.
  926. bestMatch = current;
  927. }
  928. }
  929. return getFullyMatchedCommandOrNull(bestMatch);
  930. }
  931. },
  932. processCommand: function(cm, vim, command) {
  933. vim.inputState.repeatOverride = command.repeatOverride;
  934. switch (command.type) {
  935. case 'motion':
  936. this.processMotion(cm, vim, command);
  937. break;
  938. case 'operator':
  939. this.processOperator(cm, vim, command);
  940. break;
  941. case 'operatorMotion':
  942. this.processOperatorMotion(cm, vim, command);
  943. break;
  944. case 'action':
  945. this.processAction(cm, vim, command);
  946. break;
  947. case 'search':
  948. this.processSearch(cm, vim, command);
  949. break;
  950. case 'ex':
  951. case 'keyToEx':
  952. this.processEx(cm, vim, command);
  953. break;
  954. default:
  955. break;
  956. }
  957. },
  958. processMotion: function(cm, vim, command) {
  959. vim.inputState.motion = command.motion;
  960. vim.inputState.motionArgs = copyArgs(command.motionArgs);
  961. this.evalInput(cm, vim);
  962. },
  963. processOperator: function(cm, vim, command) {
  964. var inputState = vim.inputState;
  965. if (inputState.operator) {
  966. if (inputState.operator == command.operator) {
  967. // Typing an operator twice like 'dd' makes the operator operate
  968. // linewise
  969. inputState.motion = 'expandToLine';
  970. inputState.motionArgs = { linewise: true };
  971. this.evalInput(cm, vim);
  972. return;
  973. } else {
  974. // 2 different operators in a row doesn't make sense.
  975. vim.inputState = new InputState();
  976. }
  977. }
  978. inputState.operator = command.operator;
  979. inputState.operatorArgs = copyArgs(command.operatorArgs);
  980. if (vim.visualMode) {
  981. // Operating on a selection in visual mode. We don't need a motion.
  982. this.evalInput(cm, vim);
  983. }
  984. },
  985. processOperatorMotion: function(cm, vim, command) {
  986. var visualMode = vim.visualMode;
  987. var operatorMotionArgs = copyArgs(command.operatorMotionArgs);
  988. if (operatorMotionArgs) {
  989. // Operator motions may have special behavior in visual mode.
  990. if (visualMode && operatorMotionArgs.visualLine) {
  991. vim.visualLine = true;
  992. }
  993. }
  994. this.processOperator(cm, vim, command);
  995. if (!visualMode) {
  996. this.processMotion(cm, vim, command);
  997. }
  998. },
  999. processAction: function(cm, vim, command) {
  1000. var inputState = vim.inputState;
  1001. var repeat = inputState.getRepeat();
  1002. var repeatIsExplicit = !!repeat;
  1003. var actionArgs = copyArgs(command.actionArgs) || {};
  1004. if (inputState.selectedCharacter) {
  1005. actionArgs.selectedCharacter = inputState.selectedCharacter;
  1006. }
  1007. // Actions may or may not have motions and operators. Do these first.
  1008. if (command.operator) {
  1009. this.processOperator(cm, vim, command);
  1010. }
  1011. if (command.motion) {
  1012. this.processMotion(cm, vim, command);
  1013. }
  1014. if (command.motion || command.operator) {
  1015. this.evalInput(cm, vim);
  1016. }
  1017. actionArgs.repeat = repeat || 1;
  1018. actionArgs.repeatIsExplicit = repeatIsExplicit;
  1019. actionArgs.registerName = inputState.registerName;
  1020. vim.inputState = new InputState();
  1021. vim.lastMotion = null;
  1022. if (command.isEdit) {
  1023. this.recordLastEdit(vim, inputState, command);
  1024. }
  1025. actions[command.action](cm, actionArgs, vim);
  1026. },
  1027. processSearch: function(cm, vim, command) {
  1028. if (!cm.getSearchCursor) {
  1029. // Search depends on SearchCursor.
  1030. return;
  1031. }
  1032. var forward = command.searchArgs.forward;
  1033. getSearchState(cm).setReversed(!forward);
  1034. var promptPrefix = (forward) ? '/' : '?';
  1035. var originalQuery = getSearchState(cm).getQuery();
  1036. var originalScrollPos = cm.getScrollInfo();
  1037. function handleQuery(query, ignoreCase, smartCase) {
  1038. try {
  1039. updateSearchQuery(cm, query, ignoreCase, smartCase);
  1040. } catch (e) {
  1041. showConfirm(cm, 'Invalid regex: ' + query);
  1042. return;
  1043. }
  1044. commandDispatcher.processMotion(cm, vim, {
  1045. type: 'motion',
  1046. motion: 'findNext',
  1047. motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist }
  1048. });
  1049. }
  1050. function onPromptClose(query) {
  1051. cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
  1052. handleQuery(query, true /** ignoreCase */, true /** smartCase */);
  1053. }
  1054. function onPromptKeyUp(_e, query) {
  1055. var parsedQuery;
  1056. try {
  1057. parsedQuery = updateSearchQuery(cm, query,
  1058. true /** ignoreCase */, true /** smartCase */);
  1059. } catch (e) {
  1060. // Swallow bad regexes for incremental search.
  1061. }
  1062. if (parsedQuery) {
  1063. cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30);
  1064. } else {
  1065. clearSearchHighlight(cm);
  1066. cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
  1067. }
  1068. }
  1069. function onPromptKeyDown(e, _query, close) {
  1070. var keyName = CodeMirror.keyName(e);
  1071. if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[') {
  1072. updateSearchQuery(cm, originalQuery);
  1073. clearSearchHighlight(cm);
  1074. cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
  1075. CodeMirror.e_stop(e);
  1076. close();
  1077. cm.focus();
  1078. }
  1079. }
  1080. switch (command.searchArgs.querySrc) {
  1081. case 'prompt':
  1082. showPrompt(cm, {
  1083. onClose: onPromptClose,
  1084. prefix: promptPrefix,
  1085. desc: searchPromptDesc,
  1086. onKeyUp: onPromptKeyUp,
  1087. onKeyDown: onPromptKeyDown
  1088. });
  1089. break;
  1090. case 'wordUnderCursor':
  1091. var word = expandWordUnderCursor(cm, false /** inclusive */,
  1092. true /** forward */, false /** bigWord */,
  1093. true /** noSymbol */);
  1094. var isKeyword = true;
  1095. if (!word) {
  1096. word = expandWordUnderCursor(cm, false /** inclusive */,
  1097. true /** forward */, false /** bigWord */,
  1098. false /** noSymbol */);
  1099. isKeyword = false;
  1100. }
  1101. if (!word) {
  1102. return;
  1103. }
  1104. var query = cm.getLine(word.start.line).substring(word.start.ch,
  1105. word.end.ch);
  1106. if (isKeyword) {
  1107. query = '\\b' + query + '\\b';
  1108. } else {
  1109. query = escapeRegex(query);
  1110. }
  1111. // cachedCursor is used to save the old position of the cursor
  1112. // when * or # causes vim to seek for the nearest word and shift
  1113. // the cursor before entering the motion.
  1114. vimGlobalState.jumpList.cachedCursor = cm.getCursor();
  1115. cm.setCursor(word.start);
  1116. handleQuery(query, true /** ignoreCase */, false /** smartCase */);
  1117. break;
  1118. }
  1119. },
  1120. processEx: function(cm, vim, command) {
  1121. function onPromptClose(input) {
  1122. // Give the prompt some time to close so that if processCommand shows
  1123. // an error, the elements don't overlap.
  1124. exCommandDispatcher.processCommand(cm, input);
  1125. }
  1126. function onPromptKeyDown(e, _input, close) {
  1127. var keyName = CodeMirror.keyName(e);
  1128. if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[') {
  1129. CodeMirror.e_stop(e);
  1130. close();
  1131. cm.focus();
  1132. }
  1133. }
  1134. if (command.type == 'keyToEx') {
  1135. // Handle user defined Ex to Ex mappings
  1136. exCommandDispatcher.processCommand(cm, command.exArgs.input);
  1137. } else {
  1138. if (vim.visualMode) {
  1139. showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>',
  1140. onKeyDown: onPromptKeyDown});
  1141. } else {
  1142. showPrompt(cm, { onClose: onPromptClose, prefix: ':',
  1143. onKeyDown: onPromptKeyDown});
  1144. }
  1145. }
  1146. },
  1147. evalInput: function(cm, vim) {
  1148. // If the motion comand is set, execute both the operator and motion.
  1149. // Otherwise return.
  1150. var inputState = vim.inputState;
  1151. var motion = inputState.motion;
  1152. var motionArgs = inputState.motionArgs || {};
  1153. var operator = inputState.operator;
  1154. var operatorArgs = inputState.operatorArgs || {};
  1155. var registerName = inputState.registerName;
  1156. var selectionEnd = copyCursor(cm.getCursor('head'));
  1157. var selectionStart = copyCursor(cm.getCursor('anchor'));
  1158. // The difference between cur and selection cursors are that cur is
  1159. // being operated on and ignores that there is a selection.
  1160. var curStart = copyCursor(selectionEnd);
  1161. var curOriginal = copyCursor(curStart);
  1162. var curEnd;
  1163. var repeat;
  1164. if (operator) {
  1165. this.recordLastEdit(vim, inputState);
  1166. }
  1167. if (inputState.repeatOverride !== undefined) {
  1168. // If repeatOverride is specified, that takes precedence over the
  1169. // input state's repeat. Used by Ex mode and can be user defined.
  1170. repeat = inputState.repeatOverride;
  1171. } else {
  1172. repeat = inputState.getRepeat();
  1173. }
  1174. if (repeat > 0 && motionArgs.explicitRepeat) {
  1175. motionArgs.repeatIsExplicit = true;
  1176. } else if (motionArgs.noRepeat ||
  1177. (!motionArgs.explicitRepeat && repeat === 0)) {
  1178. repeat = 1;
  1179. motionArgs.repeatIsExplicit = false;
  1180. }
  1181. if (inputState.selectedCharacter) {
  1182. // If there is a character input, stick it in all of the arg arrays.
  1183. motionArgs.selectedCharacter = operatorArgs.selectedCharacter =
  1184. inputState.selectedCharacter;
  1185. }
  1186. motionArgs.repeat = repeat;
  1187. vim.inputState = new InputState();
  1188. if (motion) {
  1189. var motionResult = motions[motion](cm, motionArgs, vim);
  1190. vim.lastMotion = motions[motion];
  1191. if (!motionResult) {
  1192. return;
  1193. }
  1194. if (motionArgs.toJumplist) {
  1195. var jumpList = vimGlobalState.jumpList;
  1196. // if the current motion is # or *, use cachedCursor
  1197. var cachedCursor = jumpList.cachedCursor;
  1198. if (cachedCursor) {
  1199. recordJumpPosition(cm, cachedCursor, motionResult);
  1200. delete jumpList.cachedCursor;
  1201. } else {
  1202. recordJumpPosition(cm, curOriginal, motionResult);
  1203. }
  1204. }
  1205. if (motionResult instanceof Array) {
  1206. curStart = motionResult[0];
  1207. curEnd = motionResult[1];
  1208. } else {
  1209. curEnd = motionResult;
  1210. }
  1211. // TODO: Handle null returns from motion commands better.
  1212. if (!curEnd) {
  1213. curEnd = Pos(curStart.line, curStart.ch);
  1214. }
  1215. if (vim.visualMode) {
  1216. // Check if the selection crossed over itself. Will need to shift
  1217. // the start point if that happened.
  1218. if (cursorIsBefore(selectionStart, selectionEnd) &&
  1219. (cursorEqual(selectionStart, curEnd) ||
  1220. cursorIsBefore(curEnd, selectionStart))) {
  1221. // The end of the selection has moved from after the start to
  1222. // before the start. We will shift the start right by 1.
  1223. selectionStart.ch += 1;
  1224. } else if (cursorIsBefore(selectionEnd, selectionStart) &&
  1225. (cursorEqual(selectionStart, curEnd) ||
  1226. cursorIsBefore(selectionStart, curEnd))) {
  1227. // The opposite happened. We will shift the start left by 1.
  1228. selectionStart.ch -= 1;
  1229. }
  1230. selectionEnd = curEnd;
  1231. selectionStart = (motionResult instanceof Array) ? curStart : selectionStart;
  1232. if (vim.visualLine) {
  1233. if (cursorIsBefore(selectionStart, selectionEnd)) {
  1234. selectionStart.ch = 0;
  1235. var lastLine = cm.lastLine();
  1236. if (selectionEnd.line > lastLine) {
  1237. selectionEnd.line = lastLine;
  1238. }
  1239. selectionEnd.ch = lineLength(cm, selectionEnd.line);
  1240. } else {
  1241. selectionEnd.ch = 0;
  1242. selectionStart.ch = lineLength(cm, selectionStart.line);
  1243. }
  1244. }
  1245. cm.setSelection(selectionStart, selectionEnd);
  1246. updateMark(cm, vim, '<',
  1247. cursorIsBefore(selectionStart, selectionEnd) ? selectionStart
  1248. : selectionEnd);
  1249. updateMark(cm, vim, '>',
  1250. cursorIsBefore(selectionStart, selectionEnd) ? selectionEnd
  1251. : selectionStart);
  1252. } else if (!operator) {
  1253. curEnd = clipCursorToContent(cm, curEnd);
  1254. cm.setCursor(curEnd.line, curEnd.ch);
  1255. }
  1256. }
  1257. if (operator) {
  1258. var inverted = false;
  1259. vim.lastMotion = null;
  1260. operatorArgs.repeat = repeat; // Indent in visual mode needs this.
  1261. if (vim.visualMode) {
  1262. curStart = selectionStart;
  1263. curEnd = selectionEnd;
  1264. motionArgs.inclusive = true;
  1265. }
  1266. // Swap start and end if motion was backward.
  1267. if (cursorIsBefore(curEnd, curStart)) {
  1268. var tmp = curStart;
  1269. curStart = curEnd;
  1270. curEnd = tmp;
  1271. inverted = true;
  1272. }
  1273. if (motionArgs.inclusive && !(vim.visualMode && inverted)) {
  1274. // Move the selection end one to the right to include the last
  1275. // character.
  1276. curEnd.ch++;
  1277. }
  1278. var linewise = motionArgs.linewise ||
  1279. (vim.visualMode && vim.visualLine);
  1280. if (linewise) {
  1281. // Expand selection to entire line.
  1282. expandSelectionToLine(cm, curStart, curEnd);
  1283. } else if (motionArgs.forward) {
  1284. // Clip to trailing newlines only if the motion goes forward.
  1285. clipToLine(cm, curStart, curEnd);
  1286. }
  1287. operatorArgs.registerName = registerName;
  1288. // Keep track of linewise as it affects how paste and change behave.
  1289. operatorArgs.linewise = linewise;
  1290. operators[operator](cm, operatorArgs, vim, curStart,
  1291. curEnd, curOriginal);
  1292. if (vim.visualMode) {
  1293. exitVisualMode(cm);
  1294. }
  1295. }
  1296. },
  1297. recordLastEdit: function(vim, inputState, actionCommand) {
  1298. var macroModeState = vimGlobalState.macroModeState;
  1299. if (macroModeState.isPlaying) { return; }
  1300. vim.lastEditInputState = inputState;
  1301. vim.lastEditActionCommand = actionCommand;
  1302. macroModeState.lastInsertModeChanges.changes = [];
  1303. macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false;
  1304. }
  1305. };
  1306. /**
  1307. * typedef {Object{line:number,ch:number}} Cursor An object containing the
  1308. * position of the cursor.
  1309. */
  1310. // All of the functions below return Cursor objects.
  1311. var motions = {
  1312. moveToTopLine: function(cm, motionArgs) {
  1313. var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;
  1314. return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
  1315. },
  1316. moveToMiddleLine: function(cm) {
  1317. var range = getUserVisibleLines(cm);
  1318. var line = Math.floor((range.top + range.bottom) * 0.5);
  1319. return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
  1320. },
  1321. moveToBottomLine: function(cm, motionArgs) {
  1322. var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;
  1323. return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
  1324. },
  1325. expandToLine: function(cm, motionArgs) {
  1326. // Expands forward to end of line, and then to next line if repeat is
  1327. // >1. Does not handle backward motion!
  1328. var cur = cm.getCursor();
  1329. return Pos(cur.line + motionArgs.repeat - 1, Infinity);
  1330. },
  1331. findNext: function(cm, motionArgs) {
  1332. var state = getSearchState(cm);
  1333. var query = state.getQuery();
  1334. if (!query) {
  1335. return;
  1336. }
  1337. var prev = !motionArgs.forward;
  1338. // If search is initiated with ? instead of /, negate direction.
  1339. prev = (state.isReversed()) ? !prev : prev;
  1340. highlightSearchMatches(cm, query);
  1341. return findNext(cm, prev/** prev */, query, motionArgs.repeat);
  1342. },
  1343. goToMark: function(_cm, motionArgs, vim) {
  1344. var mark = vim.marks[motionArgs.selectedCharacter];
  1345. if (mark) {
  1346. return mark.find();
  1347. }
  1348. return null;
  1349. },
  1350. moveToOtherHighlightedEnd: function(cm) {
  1351. var curEnd = copyCursor(cm.getCursor('head'));
  1352. var curStart = copyCursor(cm.getCursor('anchor'));
  1353. if (cursorIsBefore(curStart, curEnd)) {
  1354. curEnd.ch += 1;
  1355. } else if (cursorIsBefore(curEnd, curStart)) {
  1356. curStart.ch -= 1;
  1357. }
  1358. return ([curEnd,curStart]);
  1359. },
  1360. jumpToMark: function(cm, motionArgs, vim) {
  1361. var best = cm.getCursor();
  1362. for (var i = 0; i < motionArgs.repeat; i++) {
  1363. var cursor = best;
  1364. for (var key in vim.marks) {
  1365. if (!isLowerCase(key)) {
  1366. continue;
  1367. }
  1368. var mark = vim.marks[key].find();
  1369. var isWrongDirection = (motionArgs.forward) ?
  1370. cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark);
  1371. if (isWrongDirection) {
  1372. continue;
  1373. }
  1374. if (motionArgs.linewise && (mark.line == cursor.line)) {
  1375. continue;
  1376. }
  1377. var equal = cursorEqual(cursor, best);
  1378. var between = (motionArgs.forward) ?
  1379. cusrorIsBetween(cursor, mark, best) :
  1380. cusrorIsBetween(best, mark, cursor);
  1381. if (equal || between) {
  1382. best = mark;
  1383. }
  1384. }
  1385. }
  1386. if (motionArgs.linewise) {
  1387. // Vim places the cursor on the first non-whitespace character of
  1388. // the line if there is one, else it places the cursor at the end
  1389. // of the line, regardless of whether a mark was found.
  1390. best = Pos(best.line, findFirstNonWhiteSpaceCharacter(cm.getLine(best.line)));
  1391. }
  1392. return best;
  1393. },
  1394. moveByCharacters: function(cm, motionArgs) {
  1395. var cur = cm.getCursor();
  1396. var repeat = motionArgs.repeat;
  1397. var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;
  1398. return Pos(cur.line, ch);
  1399. },
  1400. moveByLines: function(cm, motionArgs, vim) {
  1401. var cur = cm.getCursor();
  1402. var endCh = cur.ch;
  1403. // Depending what our last motion was, we may want to do different
  1404. // things. If our last motion was moving vertically, we want to
  1405. // preserve the HPos from our last horizontal move. If our last motion
  1406. // was going to the end of a line, moving vertically we should go to
  1407. // the end of the line, etc.
  1408. switch (vim.lastMotion) {
  1409. case this.moveByLines:
  1410. case this.moveByDisplayLines:
  1411. case this.moveByScroll:
  1412. case this.moveToColumn:
  1413. case this.moveToEol:
  1414. endCh = vim.lastHPos;
  1415. break;
  1416. default:
  1417. vim.lastHPos = endCh;
  1418. }
  1419. var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0);
  1420. var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat;
  1421. var first = cm.firstLine();
  1422. var last = cm.lastLine();
  1423. // Vim cancels linewise motions that start on an edge and move beyond
  1424. // that edge. It does not cancel motions that do not start on an edge.
  1425. if ((line < first && cur.line == first) ||
  1426. (line > last && cur.line == last)) {
  1427. return;
  1428. }
  1429. if (motionArgs.toFirstChar){
  1430. endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));
  1431. vim.lastHPos = endCh;
  1432. }
  1433. vim.lastHSPos = cm.charCoords(Pos(line, endCh),'div').left;
  1434. return Pos(line, endCh);
  1435. },
  1436. moveByDisplayLines: function(cm, motionArgs, vim) {
  1437. var cur = cm.getCursor();
  1438. switch (vim.lastMotion) {
  1439. case this.moveByDisplayLines:
  1440. case this.moveByScroll:
  1441. case this.moveByLines:
  1442. case this.moveToColumn:
  1443. case this.moveToEol:
  1444. break;
  1445. default:
  1446. vim.lastHSPos = cm.charCoords(cur,'div').left;
  1447. }
  1448. var repeat = motionArgs.repeat;
  1449. var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos);
  1450. if (res.hitSide) {
  1451. if (motionArgs.forward) {
  1452. var lastCharCoords = cm.charCoords(res, 'div');
  1453. var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos };
  1454. var res = cm.coordsChar(goalCoords, 'div');
  1455. } else {
  1456. var resCoords = cm.charCoords(Pos(cm.firstLine(), 0), 'div');
  1457. resCoords.left = vim.lastHSPos;
  1458. res = cm.coordsChar(resCoords, 'div');
  1459. }
  1460. }
  1461. vim.lastHPos = res.ch;
  1462. return res;
  1463. },
  1464. moveByPage: function(cm, motionArgs) {
  1465. // CodeMirror only exposes functions that move the cursor page down, so
  1466. // doing this bad hack to move the cursor and move it back. evalInput
  1467. // will move the cursor to where it should be in the end.
  1468. var curStart = cm.getCursor();
  1469. var repeat = motionArgs.repeat;
  1470. cm.moveV((motionArgs.forward ? repeat : -repeat), 'page');
  1471. var curEnd = cm.getCursor();
  1472. cm.setCursor(curStart);
  1473. return curEnd;
  1474. },
  1475. moveByParagraph: function(cm, motionArgs) {
  1476. var line = cm.getCursor().line;
  1477. var repeat = motionArgs.repeat;
  1478. var inc = motionArgs.forward ? 1 : -1;
  1479. for (var i = 0; i < repeat; i++) {
  1480. if ((!motionArgs.forward && line === cm.firstLine() ) ||
  1481. (motionArgs.forward && line == cm.lastLine())) {
  1482. break;
  1483. }
  1484. line += inc;
  1485. while (line !== cm.firstLine() && line != cm.lastLine() && cm.getLine(line)) {
  1486. line += inc;
  1487. }
  1488. }
  1489. return Pos(line, 0);
  1490. },
  1491. moveByScroll: function(cm, motionArgs, vim) {
  1492. var scrollbox = cm.getScrollInfo();
  1493. var curEnd = null;
  1494. var repeat = motionArgs.repeat;
  1495. if (!repeat) {
  1496. repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
  1497. }
  1498. var orig = cm.charCoords(cm.getCursor(), 'local');
  1499. motionArgs.repeat = repeat;
  1500. var curEnd = motions.moveByDisplayLines(cm, motionArgs, vim);
  1501. if (!curEnd) {
  1502. return null;
  1503. }
  1504. var dest = cm.charCoords(curEnd, 'local');
  1505. cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
  1506. return curEnd;
  1507. },
  1508. moveByWords: function(cm, motionArgs) {
  1509. return moveToWord(cm, motionArgs.repeat, !!motionArgs.forward,
  1510. !!motionArgs.wordEnd, !!motionArgs.bigWord);
  1511. },
  1512. moveTillCharacter: function(cm, motionArgs) {
  1513. var repeat = motionArgs.repeat;
  1514. var curEnd = moveToCharacter(cm, repeat, motionArgs.forward,
  1515. motionArgs.selectedCharacter);
  1516. var increment = motionArgs.forward ? -1 : 1;
  1517. recordLastCharacterSearch(increment, motionArgs);
  1518. if (!curEnd) return null;
  1519. curEnd.ch += increment;
  1520. return curEnd;
  1521. },
  1522. moveToCharacter: function(cm, motionArgs) {
  1523. var repeat = motionArgs.repeat;
  1524. recordLastCharacterSearch(0, motionArgs);
  1525. return moveToCharacter(cm, repeat, motionArgs.forward,
  1526. motionArgs.selectedCharacter) || cm.getCursor();
  1527. },
  1528. moveToSymbol: function(cm, motionArgs) {
  1529. var repeat = motionArgs.repeat;
  1530. return findSymbol(cm, repeat, motionArgs.forward,
  1531. motionArgs.selectedCharacter) || cm.getCursor();
  1532. },
  1533. moveToColumn: function(cm, motionArgs, vim) {
  1534. var repeat = motionArgs.repeat;
  1535. // repeat is equivalent to which column we want to move to!
  1536. vim.lastHPos = repeat - 1;
  1537. vim.lastHSPos = cm.charCoords(cm.getCursor(),'div').left;
  1538. return moveToColumn(cm, repeat);
  1539. },
  1540. moveToEol: function(cm, motionArgs, vim) {
  1541. var cur = cm.getCursor();
  1542. vim.lastHPos = Infinity;
  1543. var retval= Pos(cur.line + motionArgs.repeat - 1, Infinity);
  1544. var end=cm.clipPos(retval);
  1545. end.ch--;
  1546. vim.lastHSPos = cm.charCoords(end,'div').left;
  1547. return retval;
  1548. },
  1549. moveToFirstNonWhiteSpaceCharacter: function(cm) {
  1550. // Go to the start of the line where the text begins, or the end for
  1551. // whitespace-only lines
  1552. var cursor = cm.getCursor();
  1553. return Pos(cursor.line,
  1554. findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)));
  1555. },
  1556. moveToMatchedSymbol: function(cm) {
  1557. var cursor = cm.getCursor();
  1558. var line = cursor.line;
  1559. var ch = cursor.ch;
  1560. var lineText = cm.getLine(line);
  1561. var symbol;
  1562. var startContext = cm.getTokenAt(cursor).type;
  1563. var startCtxLevel = getContextLevel(startContext);
  1564. do {
  1565. symbol = lineText.charAt(ch++);
  1566. if (symbol && isMatchableSymbol(symbol)) {
  1567. var endContext = cm.getTokenAt(Pos(line, ch)).type;
  1568. var endCtxLevel = getContextLevel(endContext);
  1569. if (startCtxLevel >= endCtxLevel) {
  1570. break;
  1571. }
  1572. }
  1573. } while (symbol);
  1574. if (symbol) {
  1575. return findMatchedSymbol(cm, Pos(line, ch-1), symbol);
  1576. } else {
  1577. return cursor;
  1578. }
  1579. },
  1580. moveToStartOfLine: function(cm) {
  1581. var cursor = cm.getCursor();
  1582. return Pos(cursor.line, 0);
  1583. },
  1584. moveToLineOrEdgeOfDocument: function(cm, motionArgs) {
  1585. var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine();
  1586. if (motionArgs.repeatIsExplicit) {
  1587. lineNum = motionArgs.repeat - cm.getOption('firstLineNumber');
  1588. }
  1589. return Pos(lineNum,
  1590. findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)));
  1591. },
  1592. textObjectManipulation: function(cm, motionArgs) {
  1593. // TODO: lots of possible exceptions that can be thrown here. Try da(
  1594. // outside of a () block.
  1595. // TODO: adding <> >< to this map doesn't work, presumably because
  1596. // they're operators
  1597. var mirroredPairs = {'(': ')', ')': '(',
  1598. '{': '}', '}': '{',
  1599. '[': ']', ']': '['};
  1600. var selfPaired = {'\'': true, '"': true};
  1601. var character = motionArgs.selectedCharacter;
  1602. // Inclusive is the difference between a and i
  1603. // TODO: Instead of using the additional text object map to perform text
  1604. // object operations, merge the map into the defaultKeyMap and use
  1605. // motionArgs to define behavior. Define separate entries for 'aw',
  1606. // 'iw', 'a[', 'i[', etc.
  1607. var inclusive = !motionArgs.textObjectInner;
  1608. var tmp;
  1609. if (mirroredPairs[character]) {
  1610. tmp = selectCompanionObject(cm, mirroredPairs[character], inclusive);
  1611. } else if (selfPaired[character]) {
  1612. tmp = findBeginningAndEnd(cm, character, inclusive);
  1613. } else if (character === 'W') {
  1614. tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
  1615. true /** bigWord */);
  1616. } else if (character === 'w') {
  1617. tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
  1618. false /** bigWord */);
  1619. } else {
  1620. // No text object defined for this, don't move.
  1621. return null;
  1622. }
  1623. return [tmp.start, tmp.end];
  1624. },
  1625. repeatLastCharacterSearch: function(cm, motionArgs) {
  1626. var lastSearch = vimGlobalState.lastChararacterSearch;
  1627. var repeat = motionArgs.repeat;
  1628. var forward = motionArgs.forward === lastSearch.forward;
  1629. var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1);
  1630. cm.moveH(-increment, 'char');
  1631. motionArgs.inclusive = forward ? true : false;
  1632. var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);
  1633. if (!curEnd) {
  1634. cm.moveH(increment, 'char');
  1635. return cm.getCursor();
  1636. }
  1637. curEnd.ch += increment;
  1638. return curEnd;
  1639. }
  1640. };
  1641. var operators = {
  1642. change: function(cm, operatorArgs, _vim, curStart, curEnd) {
  1643. vimGlobalState.registerController.pushText(
  1644. operatorArgs.registerName, 'change', cm.getRange(curStart, curEnd),
  1645. operatorArgs.linewise);
  1646. if (operatorArgs.linewise) {
  1647. // Push the next line back down, if there is a next line.
  1648. var replacement = curEnd.line > cm.lastLine() ? '' : '\n';
  1649. cm.replaceRange(replacement, curStart, curEnd);
  1650. cm.indentLine(curStart.line, 'smart');
  1651. // null ch so setCursor moves to end of line.
  1652. curStart.ch = null;
  1653. } else {
  1654. // Exclude trailing whitespace if the range is not all whitespace.
  1655. var text = cm.getRange(curStart, curEnd);
  1656. if (!isWhiteSpaceString(text)) {
  1657. var match = (/\s+$/).exec(text);
  1658. if (match) {
  1659. curEnd = offsetCursor(curEnd, 0, - match[0].length);
  1660. }
  1661. }
  1662. cm.replaceRange('', curStart, curEnd);
  1663. }
  1664. actions.enterInsertMode(cm, {}, cm.state.vim);
  1665. cm.setCursor(curStart);
  1666. },
  1667. // delete is a javascript keyword.
  1668. 'delete': function(cm, operatorArgs, _vim, curStart, curEnd) {
  1669. // If the ending line is past the last line, inclusive, instead of
  1670. // including the trailing \n, include the \n before the starting line
  1671. if (operatorArgs.linewise &&
  1672. curEnd.line > cm.lastLine() && curStart.line > cm.firstLine()) {
  1673. curStart.line--;
  1674. curStart.ch = lineLength(cm, curStart.line);
  1675. }
  1676. vimGlobalState.registerController.pushText(
  1677. operatorArgs.registerName, 'delete', cm.getRange(curStart, curEnd),
  1678. operatorArgs.linewise);
  1679. cm.replaceRange('', curStart, curEnd);
  1680. if (operatorArgs.linewise) {
  1681. cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
  1682. } else {
  1683. cm.setCursor(curStart);
  1684. }
  1685. },
  1686. indent: function(cm, operatorArgs, vim, curStart, curEnd) {
  1687. var startLine = curStart.line;
  1688. var endLine = curEnd.line;
  1689. // In visual mode, n> shifts the selection right n times, instead of
  1690. // shifting n lines right once.
  1691. var repeat = (vim.visualMode) ? operatorArgs.repeat : 1;
  1692. if (operatorArgs.linewise) {
  1693. // The only way to delete a newline is to delete until the start of
  1694. // the next line, so in linewise mode evalInput will include the next
  1695. // line. We don't want this in indent, so we go back a line.
  1696. endLine--;
  1697. }
  1698. for (var i = startLine; i <= endLine; i++) {
  1699. for (var j = 0; j < repeat; j++) {
  1700. cm.indentLine(i, operatorArgs.indentRight);
  1701. }
  1702. }
  1703. cm.setCursor(curStart);
  1704. cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
  1705. },
  1706. swapcase: function(cm, operatorArgs, _vim, curStart, curEnd, curOriginal) {
  1707. var toSwap = cm.getRange(curStart, curEnd);
  1708. var swapped = '';
  1709. for (var i = 0; i < toSwap.length; i++) {
  1710. var character = toSwap.charAt(i);
  1711. swapped += isUpperCase(character) ? character.toLowerCase() :
  1712. character.toUpperCase();
  1713. }
  1714. cm.replaceRange(swapped, curStart, curEnd);
  1715. if (!operatorArgs.shouldMoveCursor) {
  1716. cm.setCursor(curOriginal);
  1717. }
  1718. },
  1719. yank: function(cm, operatorArgs, _vim, curStart, curEnd, curOriginal) {
  1720. vimGlobalState.registerController.pushText(
  1721. operatorArgs.registerName, 'yank',
  1722. cm.getRange(curStart, curEnd), operatorArgs.linewise);
  1723. cm.setCursor(curOriginal);
  1724. }
  1725. };
  1726. var actions = {
  1727. jumpListWalk: function(cm, actionArgs, vim) {
  1728. if (vim.visualMode) {
  1729. return;
  1730. }
  1731. var repeat = actionArgs.repeat;
  1732. var forward = actionArgs.forward;
  1733. var jumpList = vimGlobalState.jumpList;
  1734. var mark = jumpList.move(cm, forward ? repeat : -repeat);
  1735. var markPos = mark ? mark.find() : undefined;
  1736. markPos = markPos ? markPos : cm.getCursor();
  1737. cm.setCursor(markPos);
  1738. },
  1739. scroll: function(cm, actionArgs, vim) {
  1740. if (vim.visualMode) {
  1741. return;
  1742. }
  1743. var repeat = actionArgs.repeat || 1;
  1744. var lineHeight = cm.defaultTextHeight();
  1745. var top = cm.getScrollInfo().top;
  1746. var delta = lineHeight * repeat;
  1747. var newPos = actionArgs.forward ? top + delta : top - delta;
  1748. var cursor = copyCursor(cm.getCursor());
  1749. var cursorCoords = cm.charCoords(cursor, 'local');
  1750. if (actionArgs.forward) {
  1751. if (newPos > cursorCoords.top) {
  1752. cursor.line += (newPos - cursorCoords.top) / lineHeight;
  1753. cursor.line = Math.ceil(cursor.line);
  1754. cm.setCursor(cursor);
  1755. cursorCoords = cm.charCoords(cursor, 'local');
  1756. cm.scrollTo(null, cursorCoords.top);
  1757. } else {
  1758. // Cursor stays within bounds. Just reposition the scroll window.
  1759. cm.scrollTo(null, newPos);
  1760. }
  1761. } else {
  1762. var newBottom = newPos + cm.getScrollInfo().clientHeight;
  1763. if (newBottom < cursorCoords.bottom) {
  1764. cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight;
  1765. cursor.line = Math.floor(cursor.line);
  1766. cm.setCursor(cursor);
  1767. cursorCoords = cm.charCoords(cursor, 'local');
  1768. cm.scrollTo(
  1769. null, cursorCoords.bottom - cm.getScrollInfo().clientHeight);
  1770. } else {
  1771. // Cursor stays within bounds. Just reposition the scroll window.
  1772. cm.scrollTo(null, newPos);
  1773. }
  1774. }
  1775. },
  1776. scrollToCursor: function(cm, actionArgs) {
  1777. var lineNum = cm.getCursor().line;
  1778. var charCoords = cm.charCoords(Pos(lineNum, 0), 'local');
  1779. var height = cm.getScrollInfo().clientHeight;
  1780. var y = charCoords.top;
  1781. var lineHeight = charCoords.bottom - y;
  1782. switch (actionArgs.position) {
  1783. case 'center': y = y - (height / 2) + lineHeight;
  1784. break;
  1785. case 'bottom': y = y - height + lineHeight*1.4;
  1786. break;
  1787. case 'top': y = y + lineHeight*0.4;
  1788. break;
  1789. }
  1790. cm.scrollTo(null, y);
  1791. },
  1792. replayMacro: function(cm, actionArgs, vim) {
  1793. var registerName = actionArgs.selectedCharacter;
  1794. var repeat = actionArgs.repeat;
  1795. var macroModeState = vimGlobalState.macroModeState;
  1796. if (registerName == '@') {
  1797. registerName = macroModeState.latestRegister;
  1798. }
  1799. while(repeat--){
  1800. executeMacroRegister(cm, vim, macroModeState, registerName);
  1801. }
  1802. },
  1803. enterMacroRecordMode: function(cm, actionArgs) {
  1804. var macroModeState = vimGlobalState.macroModeState;
  1805. var registerName = actionArgs.selectedCharacter;
  1806. macroModeState.enterMacroRecordMode(cm, registerName);
  1807. },
  1808. enterInsertMode: function(cm, actionArgs, vim) {
  1809. if (cm.getOption('readOnly')) { return; }
  1810. vim.insertMode = true;
  1811. vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1;
  1812. var insertAt = (actionArgs) ? actionArgs.insertAt : null;
  1813. if (insertAt == 'eol') {
  1814. var cursor = cm.getCursor();
  1815. cursor = Pos(cursor.line, lineLength(cm, cursor.line));
  1816. cm.setCursor(cursor);
  1817. } else if (insertAt == 'charAfter') {
  1818. cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
  1819. } else if (insertAt == 'firstNonBlank') {
  1820. cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
  1821. }
  1822. cm.setOption('keyMap', 'vim-insert');
  1823. cm.setOption('disableInput', false);
  1824. if (actionArgs && actionArgs.replace) {
  1825. // Handle Replace-mode as a special case of insert mode.
  1826. cm.toggleOverwrite(true);
  1827. cm.setOption('keyMap', 'vim-replace');
  1828. CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
  1829. } else {
  1830. cm.setOption('keyMap', 'vim-insert');
  1831. CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
  1832. }
  1833. if (!vimGlobalState.macroModeState.isPlaying) {
  1834. // Only record if not replaying.
  1835. cm.on('change', onChange);
  1836. cm.on('cursorActivity', onCursorActivity);
  1837. CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
  1838. }
  1839. },
  1840. toggleVisualMode: function(cm, actionArgs, vim) {
  1841. var repeat = actionArgs.repeat;
  1842. var curStart = cm.getCursor();
  1843. var curEnd;
  1844. // TODO: The repeat should actually select number of characters/lines
  1845. // equal to the repeat times the size of the previous visual
  1846. // operation.
  1847. if (!vim.visualMode) {
  1848. cm.on('mousedown', exitVisualMode);
  1849. vim.visualMode = true;
  1850. vim.visualLine = !!actionArgs.linewise;
  1851. if (vim.visualLine) {
  1852. curStart.ch = 0;
  1853. curEnd = clipCursorToContent(
  1854. cm, Pos(curStart.line + repeat - 1, lineLength(cm, curStart.line)),
  1855. true /** includeLineBreak */);
  1856. } else {
  1857. curEnd = clipCursorToContent(
  1858. cm, Pos(curStart.line, curStart.ch + repeat),
  1859. true /** includeLineBreak */);
  1860. }
  1861. // Make the initial selection.
  1862. if (!actionArgs.repeatIsExplicit && !vim.visualLine) {
  1863. // This is a strange case. Here the implicit repeat is 1. The
  1864. // following commands lets the cursor hover over the 1 character
  1865. // selection.
  1866. cm.setCursor(curEnd);
  1867. cm.setSelection(curEnd, curStart);
  1868. } else {
  1869. cm.setSelection(curStart, curEnd);
  1870. }
  1871. CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : ""});
  1872. } else {
  1873. curStart = cm.getCursor('anchor');
  1874. curEnd = cm.getCursor('head');
  1875. if (!vim.visualLine && actionArgs.linewise) {
  1876. // Shift-V pressed in characterwise visual mode. Switch to linewise
  1877. // visual mode instead of exiting visual mode.
  1878. vim.visualLine = true;
  1879. curStart.ch = cursorIsBefore(curStart, curEnd) ? 0 :
  1880. lineLength(cm, curStart.line);
  1881. curEnd.ch = cursorIsBefore(curStart, curEnd) ?
  1882. lineLength(cm, curEnd.line) : 0;
  1883. cm.setSelection(curStart, curEnd);
  1884. CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: "linewise"});
  1885. } else if (vim.visualLine && !actionArgs.linewise) {
  1886. // v pressed in linewise visual mode. Switch to characterwise visual
  1887. // mode instead of exiting visual mode.
  1888. vim.visualLine = false;
  1889. CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
  1890. } else {
  1891. exitVisualMode(cm);
  1892. }
  1893. }
  1894. updateMark(cm, vim, '<', cursorIsBefore(curStart, curEnd) ? curStart
  1895. : curEnd);
  1896. updateMark(cm, vim, '>', cursorIsBefore(curStart, curEnd) ? curEnd
  1897. : curStart);
  1898. },
  1899. reselectLastSelection: function(cm, _actionArgs, vim) {
  1900. if (vim.lastSelection) {
  1901. var lastSelection = vim.lastSelection;
  1902. cm.setSelection(lastSelection.curStart, lastSelection.curEnd);
  1903. if (lastSelection.visualLine) {
  1904. vim.visualMode = true;
  1905. vim.visualLine = true;
  1906. }
  1907. else {
  1908. vim.visualMode = true;
  1909. vim.visualLine = false;
  1910. }
  1911. CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : ""});
  1912. }
  1913. },
  1914. joinLines: function(cm, actionArgs, vim) {
  1915. var curStart, curEnd;
  1916. if (vim.visualMode) {
  1917. curStart = cm.getCursor('anchor');
  1918. curEnd = cm.getCursor('head');
  1919. curEnd.ch = lineLength(cm, curEnd.line) - 1;
  1920. } else {
  1921. // Repeat is the number of lines to join. Minimum 2 lines.
  1922. var repeat = Math.max(actionArgs.repeat, 2);
  1923. curStart = cm.getCursor();
  1924. curEnd = clipCursorToContent(cm, Pos(curStart.line + repeat - 1,
  1925. Infinity));
  1926. }
  1927. var finalCh = 0;
  1928. cm.operation(function() {
  1929. for (var i = curStart.line; i < curEnd.line; i++) {
  1930. finalCh = lineLength(cm, curStart.line);
  1931. var tmp = Pos(curStart.line + 1,
  1932. lineLength(cm, curStart.line + 1));
  1933. var text = cm.getRange(curStart, tmp);
  1934. text = text.replace(/\n\s*/g, ' ');
  1935. cm.replaceRange(text, curStart, tmp);
  1936. }
  1937. var curFinalPos = Pos(curStart.line, finalCh);
  1938. cm.setCursor(curFinalPos);
  1939. });
  1940. },
  1941. newLineAndEnterInsertMode: function(cm, actionArgs, vim) {
  1942. vim.insertMode = true;
  1943. var insertAt = copyCursor(cm.getCursor());
  1944. if (insertAt.line === cm.firstLine() && !actionArgs.after) {
  1945. // Special case for inserting newline before start of document.
  1946. cm.replaceRange('\n', Pos(cm.firstLine(), 0));
  1947. cm.setCursor(cm.firstLine(), 0);
  1948. } else {
  1949. insertAt.line = (actionArgs.after) ? insertAt.line :
  1950. insertAt.line - 1;
  1951. insertAt.ch = lineLength(cm, insertAt.line);
  1952. cm.setCursor(insertAt);
  1953. var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||
  1954. CodeMirror.commands.newlineAndIndent;
  1955. newlineFn(cm);
  1956. }
  1957. this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim);
  1958. },
  1959. paste: function(cm, actionArgs) {
  1960. var cur = copyCursor(cm.getCursor());
  1961. var register = vimGlobalState.registerController.getRegister(
  1962. actionArgs.registerName);
  1963. var text = register.toString();
  1964. if (!text) {
  1965. return;
  1966. }
  1967. if (actionArgs.repeat > 1) {
  1968. var text = Array(actionArgs.repeat + 1).join(text);
  1969. }
  1970. var linewise = register.linewise;
  1971. if (linewise) {
  1972. if (actionArgs.after) {
  1973. // Move the newline at the end to the start instead, and paste just
  1974. // before the newline character of the line we are on right now.
  1975. text = '\n' + text.slice(0, text.length - 1);
  1976. cur.ch = lineLength(cm, cur.line);
  1977. } else {
  1978. cur.ch = 0;
  1979. }
  1980. } else {
  1981. cur.ch += actionArgs.after ? 1 : 0;
  1982. }
  1983. cm.replaceRange(text, cur);
  1984. // Now fine tune the cursor to where we want it.
  1985. var curPosFinal;
  1986. var idx;
  1987. if (linewise && actionArgs.after) {
  1988. curPosFinal = Pos(
  1989. cur.line + 1,
  1990. findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1)));
  1991. } else if (linewise && !actionArgs.after) {
  1992. curPosFinal = Pos(
  1993. cur.line,
  1994. findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line)));
  1995. } else if (!linewise && actionArgs.after) {
  1996. idx = cm.indexFromPos(cur);
  1997. curPosFinal = cm.posFromIndex(idx + text.length - 1);
  1998. } else {
  1999. idx = cm.indexFromPos(cur);
  2000. curPosFinal = cm.posFromIndex(idx + text.length);
  2001. }
  2002. cm.setCursor(curPosFinal);
  2003. },
  2004. undo: function(cm, actionArgs) {
  2005. cm.operation(function() {
  2006. repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();
  2007. cm.setCursor(cm.getCursor('anchor'));
  2008. });
  2009. },
  2010. redo: function(cm, actionArgs) {
  2011. repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();
  2012. },
  2013. setRegister: function(_cm, actionArgs, vim) {
  2014. vim.inputState.registerName = actionArgs.selectedCharacter;
  2015. },
  2016. setMark: function(cm, actionArgs, vim) {
  2017. var markName = actionArgs.selectedCharacter;
  2018. updateMark(cm, vim, markName, cm.getCursor());
  2019. },
  2020. replace: function(cm, actionArgs, vim) {
  2021. var replaceWith = actionArgs.selectedCharacter;
  2022. var curStart = cm.getCursor();
  2023. var replaceTo;
  2024. var curEnd;
  2025. if (vim.visualMode){
  2026. curStart=cm.getCursor('start');
  2027. curEnd=cm.getCursor('end');
  2028. // workaround to catch the character under the cursor
  2029. // existing workaround doesn't cover actions
  2030. curEnd=cm.clipPos(Pos(curEnd.line, curEnd.ch+1));
  2031. }else{
  2032. var line = cm.getLine(curStart.line);
  2033. replaceTo = curStart.ch + actionArgs.repeat;
  2034. if (replaceTo > line.length) {
  2035. replaceTo=line.length;
  2036. }
  2037. curEnd = Pos(curStart.line, replaceTo);
  2038. }
  2039. if (replaceWith=='\n'){
  2040. if (!vim.visualMode) cm.replaceRange('', curStart, curEnd);
  2041. // special case, where vim help says to replace by just one line-break
  2042. (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm);
  2043. }else {
  2044. var replaceWithStr=cm.getRange(curStart, curEnd);
  2045. //replace all characters in range by selected, but keep linebreaks
  2046. replaceWithStr=replaceWithStr.replace(/[^\n]/g,replaceWith);
  2047. cm.replaceRange(replaceWithStr, curStart, curEnd);
  2048. if (vim.visualMode){
  2049. cm.setCursor(curStart);
  2050. exitVisualMode(cm);
  2051. }else{
  2052. cm.setCursor(offsetCursor(curEnd, 0, -1));
  2053. }
  2054. }
  2055. },
  2056. incrementNumberToken: function(cm, actionArgs) {
  2057. var cur = cm.getCursor();
  2058. var lineStr = cm.getLine(cur.line);
  2059. var re = /-?\d+/g;
  2060. var match;
  2061. var start;
  2062. var end;
  2063. var numberStr;
  2064. var token;
  2065. while ((match = re.exec(lineStr)) !== null) {
  2066. token = match[0];
  2067. start = match.index;
  2068. end = start + token.length;
  2069. if (cur.ch < end)break;
  2070. }
  2071. if (!actionArgs.backtrack && (end <= cur.ch))return;
  2072. if (token) {
  2073. var increment = actionArgs.increase ? 1 : -1;
  2074. var number = parseInt(token) + (increment * actionArgs.repeat);
  2075. var from = Pos(cur.line, start);
  2076. var to = Pos(cur.line, end);
  2077. numberStr = number.toString();
  2078. cm.replaceRange(numberStr, from, to);
  2079. } else {
  2080. return;
  2081. }
  2082. cm.setCursor(Pos(cur.line, start + numberStr.length - 1));
  2083. },
  2084. repeatLastEdit: function(cm, actionArgs, vim) {
  2085. var lastEditInputState = vim.lastEditInputState;
  2086. if (!lastEditInputState) { return; }
  2087. var repeat = actionArgs.repeat;
  2088. if (repeat && actionArgs.repeatIsExplicit) {
  2089. vim.lastEditInputState.repeatOverride = repeat;
  2090. } else {
  2091. repeat = vim.lastEditInputState.repeatOverride || repeat;
  2092. }
  2093. repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);
  2094. }
  2095. };
  2096. /*
  2097. * Below are miscellaneous utility functions used by vim.js
  2098. */
  2099. /**
  2100. * Clips cursor to ensure that line is within the buffer's range
  2101. * If includeLineBreak is true, then allow cur.ch == lineLength.
  2102. */
  2103. function clipCursorToContent(cm, cur, includeLineBreak) {
  2104. var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() );
  2105. var maxCh = lineLength(cm, line) - 1;
  2106. maxCh = (includeLineBreak) ? maxCh + 1 : maxCh;
  2107. var ch = Math.min(Math.max(0, cur.ch), maxCh);
  2108. return Pos(line, ch);
  2109. }
  2110. function copyArgs(args) {
  2111. var ret = {};
  2112. for (var prop in args) {
  2113. if (args.hasOwnProperty(prop)) {
  2114. ret[prop] = args[prop];
  2115. }
  2116. }
  2117. return ret;
  2118. }
  2119. function offsetCursor(cur, offsetLine, offsetCh) {
  2120. return Pos(cur.line + offsetLine, cur.ch + offsetCh);
  2121. }
  2122. function matchKeysPartial(pressed, mapped) {
  2123. for (var i = 0; i < pressed.length; i++) {
  2124. // 'character' means any character. For mark, register commads, etc.
  2125. if (pressed[i] != mapped[i] && mapped[i] != 'character') {
  2126. return false;
  2127. }
  2128. }
  2129. return true;
  2130. }
  2131. function repeatFn(cm, fn, repeat) {
  2132. return function() {
  2133. for (var i = 0; i < repeat; i++) {
  2134. fn(cm);
  2135. }
  2136. };
  2137. }
  2138. function copyCursor(cur) {
  2139. return Pos(cur.line, cur.ch);
  2140. }
  2141. function cursorEqual(cur1, cur2) {
  2142. return cur1.ch == cur2.ch && cur1.line == cur2.line;
  2143. }
  2144. function cursorIsBefore(cur1, cur2) {
  2145. if (cur1.line < cur2.line) {
  2146. return true;
  2147. }
  2148. if (cur1.line == cur2.line && cur1.ch < cur2.ch) {
  2149. return true;
  2150. }
  2151. return false;
  2152. }
  2153. function cusrorIsBetween(cur1, cur2, cur3) {
  2154. // returns true if cur2 is between cur1 and cur3.
  2155. var cur1before2 = cursorIsBefore(cur1, cur2);
  2156. var cur2before3 = cursorIsBefore(cur2, cur3);
  2157. return cur1before2 && cur2before3;
  2158. }
  2159. function lineLength(cm, lineNum) {
  2160. return cm.getLine(lineNum).length;
  2161. }
  2162. function reverse(s){
  2163. return s.split('').reverse().join('');
  2164. }
  2165. function trim(s) {
  2166. if (s.trim) {
  2167. return s.trim();
  2168. }
  2169. return s.replace(/^\s+|\s+$/g, '');
  2170. }
  2171. function escapeRegex(s) {
  2172. return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1');
  2173. }
  2174. function exitVisualMode(cm) {
  2175. cm.off('mousedown', exitVisualMode);
  2176. var vim = cm.state.vim;
  2177. // can't use selection state here because yank has already reset its cursor
  2178. vim.lastSelection = {'curStart': vim.marks['<'].find(),
  2179. 'curEnd': vim.marks['>'].find(), 'visualMode': vim.visualMode,
  2180. 'visualLine': vim.visualLine};
  2181. vim.visualMode = false;
  2182. vim.visualLine = false;
  2183. var selectionStart = cm.getCursor('anchor');
  2184. var selectionEnd = cm.getCursor('head');
  2185. if (!cursorEqual(selectionStart, selectionEnd)) {
  2186. // Clear the selection and set the cursor only if the selection has not
  2187. // already been cleared. Otherwise we risk moving the cursor somewhere
  2188. // it's not supposed to be.
  2189. cm.setCursor(clipCursorToContent(cm, selectionEnd));
  2190. }
  2191. CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
  2192. }
  2193. // Remove any trailing newlines from the selection. For
  2194. // example, with the caret at the start of the last word on the line,
  2195. // 'dw' should word, but not the newline, while 'w' should advance the
  2196. // caret to the first character of the next line.
  2197. function clipToLine(cm, curStart, curEnd) {
  2198. var selection = cm.getRange(curStart, curEnd);
  2199. // Only clip if the selection ends with trailing newline + whitespace
  2200. if (/\n\s*$/.test(selection)) {
  2201. var lines = selection.split('\n');
  2202. // We know this is all whitepsace.
  2203. lines.pop();
  2204. // Cases:
  2205. // 1. Last word is an empty line - do not clip the trailing '\n'
  2206. // 2. Last word is not an empty line - clip the trailing '\n'
  2207. var line;
  2208. // Find the line containing the last word, and clip all whitespace up
  2209. // to it.
  2210. for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {
  2211. curEnd.line--;
  2212. curEnd.ch = 0;
  2213. }
  2214. // If the last word is not an empty line, clip an additional newline
  2215. if (line) {
  2216. curEnd.line--;
  2217. curEnd.ch = lineLength(cm, curEnd.line);
  2218. } else {
  2219. curEnd.ch = 0;
  2220. }
  2221. }
  2222. }
  2223. // Expand the selection to line ends.
  2224. function expandSelectionToLine(_cm, curStart, curEnd) {
  2225. curStart.ch = 0;
  2226. curEnd.ch = 0;
  2227. curEnd.line++;
  2228. }
  2229. function findFirstNonWhiteSpaceCharacter(text) {
  2230. if (!text) {
  2231. return 0;
  2232. }
  2233. var firstNonWS = text.search(/\S/);
  2234. return firstNonWS == -1 ? text.length : firstNonWS;
  2235. }
  2236. function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) {
  2237. var cur = cm.getCursor();
  2238. var line = cm.getLine(cur.line);
  2239. var idx = cur.ch;
  2240. // Seek to first word or non-whitespace character, depending on if
  2241. // noSymbol is true.
  2242. var textAfterIdx = line.substring(idx);
  2243. var firstMatchedChar;
  2244. if (noSymbol) {
  2245. firstMatchedChar = textAfterIdx.search(/\w/);
  2246. } else {
  2247. firstMatchedChar = textAfterIdx.search(/\S/);
  2248. }
  2249. if (firstMatchedChar == -1) {
  2250. return null;
  2251. }
  2252. idx += firstMatchedChar;
  2253. textAfterIdx = line.substring(idx);
  2254. var textBeforeIdx = line.substring(0, idx);
  2255. var matchRegex;
  2256. // Greedy matchers for the "word" we are trying to expand.
  2257. if (bigWord) {
  2258. matchRegex = /^\S+/;
  2259. } else {
  2260. if ((/\w/).test(line.charAt(idx))) {
  2261. matchRegex = /^\w+/;
  2262. } else {
  2263. matchRegex = /^[^\w\s]+/;
  2264. }
  2265. }
  2266. var wordAfterRegex = matchRegex.exec(textAfterIdx);
  2267. var wordStart = idx;
  2268. var wordEnd = idx + wordAfterRegex[0].length;
  2269. // TODO: Find a better way to do this. It will be slow on very long lines.
  2270. var revTextBeforeIdx = reverse(textBeforeIdx);
  2271. var wordBeforeRegex = matchRegex.exec(revTextBeforeIdx);
  2272. if (wordBeforeRegex) {
  2273. wordStart -= wordBeforeRegex[0].length;
  2274. }
  2275. if (inclusive) {
  2276. // If present, trim all whitespace after word.
  2277. // Otherwise, trim all whitespace before word.
  2278. var textAfterWordEnd = line.substring(wordEnd);
  2279. var whitespacesAfterWord = textAfterWordEnd.match(/^\s*/)[0].length;
  2280. if (whitespacesAfterWord > 0) {
  2281. wordEnd += whitespacesAfterWord;
  2282. } else {
  2283. var revTrim = revTextBeforeIdx.length - wordStart;
  2284. var textBeforeWordStart = revTextBeforeIdx.substring(revTrim);
  2285. var whitespacesBeforeWord = textBeforeWordStart.match(/^\s*/)[0].length;
  2286. wordStart -= whitespacesBeforeWord;
  2287. }
  2288. }
  2289. return { start: Pos(cur.line, wordStart),
  2290. end: Pos(cur.line, wordEnd) };
  2291. }
  2292. function recordJumpPosition(cm, oldCur, newCur) {
  2293. if (!cursorEqual(oldCur, newCur)) {
  2294. vimGlobalState.jumpList.add(cm, oldCur, newCur);
  2295. }
  2296. }
  2297. function recordLastCharacterSearch(increment, args) {
  2298. vimGlobalState.lastChararacterSearch.increment = increment;
  2299. vimGlobalState.lastChararacterSearch.forward = args.forward;
  2300. vimGlobalState.lastChararacterSearch.selectedCharacter = args.selectedCharacter;
  2301. }
  2302. var symbolToMode = {
  2303. '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',
  2304. '[': 'section', ']': 'section',
  2305. '*': 'comment', '/': 'comment',
  2306. 'm': 'method', 'M': 'method',
  2307. '#': 'preprocess'
  2308. };
  2309. var findSymbolModes = {
  2310. bracket: {
  2311. isComplete: function(state) {
  2312. if (state.nextCh === state.symb) {
  2313. state.depth++;
  2314. if (state.depth >= 1)return true;
  2315. } else if (state.nextCh === state.reverseSymb) {
  2316. state.depth--;
  2317. }
  2318. return false;
  2319. }
  2320. },
  2321. section: {
  2322. init: function(state) {
  2323. state.curMoveThrough = true;
  2324. state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';
  2325. },
  2326. isComplete: function(state) {
  2327. return state.index === 0 && state.nextCh === state.symb;
  2328. }
  2329. },
  2330. comment: {
  2331. isComplete: function(state) {
  2332. var found = state.lastCh === '*' && state.nextCh === '/';
  2333. state.lastCh = state.nextCh;
  2334. return found;
  2335. }
  2336. },
  2337. // TODO: The original Vim implementation only operates on level 1 and 2.
  2338. // The current implementation doesn't check for code block level and
  2339. // therefore it operates on any levels.
  2340. method: {
  2341. init: function(state) {
  2342. state.symb = (state.symb === 'm' ? '{' : '}');
  2343. state.reverseSymb = state.symb === '{' ? '}' : '{';
  2344. },
  2345. isComplete: function(state) {
  2346. if (state.nextCh === state.symb)return true;
  2347. return false;
  2348. }
  2349. },
  2350. preprocess: {
  2351. init: function(state) {
  2352. state.index = 0;
  2353. },
  2354. isComplete: function(state) {
  2355. if (state.nextCh === '#') {
  2356. var token = state.lineText.match(/#(\w+)/)[1];
  2357. if (token === 'endif') {
  2358. if (state.forward && state.depth === 0) {
  2359. return true;
  2360. }
  2361. state.depth++;
  2362. } else if (token === 'if') {
  2363. if (!state.forward && state.depth === 0) {
  2364. return true;
  2365. }
  2366. state.depth--;
  2367. }
  2368. if (token === 'else' && state.depth === 0)return true;
  2369. }
  2370. return false;
  2371. }
  2372. }
  2373. };
  2374. function findSymbol(cm, repeat, forward, symb) {
  2375. var cur = copyCursor(cm.getCursor());
  2376. var increment = forward ? 1 : -1;
  2377. var endLine = forward ? cm.lineCount() : -1;
  2378. var curCh = cur.ch;
  2379. var line = cur.line;
  2380. var lineText = cm.getLine(line);
  2381. var state = {
  2382. lineText: lineText,
  2383. nextCh: lineText.charAt(curCh),
  2384. lastCh: null,
  2385. index: curCh,
  2386. symb: symb,
  2387. reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],
  2388. forward: forward,
  2389. depth: 0,
  2390. curMoveThrough: false
  2391. };
  2392. var mode = symbolToMode[symb];
  2393. if (!mode)return cur;
  2394. var init = findSymbolModes[mode].init;
  2395. var isComplete = findSymbolModes[mode].isComplete;
  2396. if (init) { init(state); }
  2397. while (line !== endLine && repeat) {
  2398. state.index += increment;
  2399. state.nextCh = state.lineText.charAt(state.index);
  2400. if (!state.nextCh) {
  2401. line += increment;
  2402. state.lineText = cm.getLine(line) || '';
  2403. if (increment > 0) {
  2404. state.index = 0;
  2405. } else {
  2406. var lineLen = state.lineText.length;
  2407. state.index = (lineLen > 0) ? (lineLen-1) : 0;
  2408. }
  2409. state.nextCh = state.lineText.charAt(state.index);
  2410. }
  2411. if (isComplete(state)) {
  2412. cur.line = line;
  2413. cur.ch = state.index;
  2414. repeat--;
  2415. }
  2416. }
  2417. if (state.nextCh || state.curMoveThrough) {
  2418. return Pos(line, state.index);
  2419. }
  2420. return cur;
  2421. }
  2422. /*
  2423. * Returns the boundaries of the next word. If the cursor in the middle of
  2424. * the word, then returns the boundaries of the current word, starting at
  2425. * the cursor. If the cursor is at the start/end of a word, and we are going
  2426. * forward/backward, respectively, find the boundaries of the next word.
  2427. *
  2428. * @param {CodeMirror} cm CodeMirror object.
  2429. * @param {Cursor} cur The cursor position.
  2430. * @param {boolean} forward True to search forward. False to search
  2431. * backward.
  2432. * @param {boolean} bigWord True if punctuation count as part of the word.
  2433. * False if only [a-zA-Z0-9] characters count as part of the word.
  2434. * @param {boolean} emptyLineIsWord True if empty lines should be treated
  2435. * as words.
  2436. * @return {Object{from:number, to:number, line: number}} The boundaries of
  2437. * the word, or null if there are no more words.
  2438. */
  2439. function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {
  2440. var lineNum = cur.line;
  2441. var pos = cur.ch;
  2442. var line = cm.getLine(lineNum);
  2443. var dir = forward ? 1 : -1;
  2444. var regexps = bigWord ? bigWordRegexp : wordRegexp;
  2445. if (emptyLineIsWord && line == '') {
  2446. lineNum += dir;
  2447. line = cm.getLine(lineNum);
  2448. if (!isLine(cm, lineNum)) {
  2449. return null;
  2450. }
  2451. pos = (forward) ? 0 : line.length;
  2452. }
  2453. while (true) {
  2454. if (emptyLineIsWord && line == '') {
  2455. return { from: 0, to: 0, line: lineNum };
  2456. }
  2457. var stop = (dir > 0) ? line.length : -1;
  2458. var wordStart = stop, wordEnd = stop;
  2459. // Find bounds of next word.
  2460. while (pos != stop) {
  2461. var foundWord = false;
  2462. for (var i = 0; i < regexps.length && !foundWord; ++i) {
  2463. if (regexps[i].test(line.charAt(pos))) {
  2464. wordStart = pos;
  2465. // Advance to end of word.
  2466. while (pos != stop && regexps[i].test(line.charAt(pos))) {
  2467. pos += dir;
  2468. }
  2469. wordEnd = pos;
  2470. foundWord = wordStart != wordEnd;
  2471. if (wordStart == cur.ch && lineNum == cur.line &&
  2472. wordEnd == wordStart + dir) {
  2473. // We started at the end of a word. Find the next one.
  2474. continue;
  2475. } else {
  2476. return {
  2477. from: Math.min(wordStart, wordEnd + 1),
  2478. to: Math.max(wordStart, wordEnd),
  2479. line: lineNum };
  2480. }
  2481. }
  2482. }
  2483. if (!foundWord) {
  2484. pos += dir;
  2485. }
  2486. }
  2487. // Advance to next/prev line.
  2488. lineNum += dir;
  2489. if (!isLine(cm, lineNum)) {
  2490. return null;
  2491. }
  2492. line = cm.getLine(lineNum);
  2493. pos = (dir > 0) ? 0 : line.length;
  2494. }
  2495. // Should never get here.
  2496. throw new Error('The impossible happened.');
  2497. }
  2498. /**
  2499. * @param {CodeMirror} cm CodeMirror object.
  2500. * @param {int} repeat Number of words to move past.
  2501. * @param {boolean} forward True to search forward. False to search
  2502. * backward.
  2503. * @param {boolean} wordEnd True to move to end of word. False to move to
  2504. * beginning of word.
  2505. * @param {boolean} bigWord True if punctuation count as part of the word.
  2506. * False if only alphabet characters count as part of the word.
  2507. * @return {Cursor} The position the cursor should move to.
  2508. */
  2509. function moveToWord(cm, repeat, forward, wordEnd, bigWord) {
  2510. var cur = cm.getCursor();
  2511. var curStart = copyCursor(cur);
  2512. var words = [];
  2513. if (forward && !wordEnd || !forward && wordEnd) {
  2514. repeat++;
  2515. }
  2516. // For 'e', empty lines are not considered words, go figure.
  2517. var emptyLineIsWord = !(forward && wordEnd);
  2518. for (var i = 0; i < repeat; i++) {
  2519. var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord);
  2520. if (!word) {
  2521. var eodCh = lineLength(cm, cm.lastLine());
  2522. words.push(forward
  2523. ? {line: cm.lastLine(), from: eodCh, to: eodCh}
  2524. : {line: 0, from: 0, to: 0});
  2525. break;
  2526. }
  2527. words.push(word);
  2528. cur = Pos(word.line, forward ? (word.to - 1) : word.from);
  2529. }
  2530. var shortCircuit = words.length != repeat;
  2531. var firstWord = words[0];
  2532. var lastWord = words.pop();
  2533. if (forward && !wordEnd) {
  2534. // w
  2535. if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) {
  2536. // We did not start in the middle of a word. Discard the extra word at the end.
  2537. lastWord = words.pop();
  2538. }
  2539. return Pos(lastWord.line, lastWord.from);
  2540. } else if (forward && wordEnd) {
  2541. return Pos(lastWord.line, lastWord.to - 1);
  2542. } else if (!forward && wordEnd) {
  2543. // ge
  2544. if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) {
  2545. // We did not start in the middle of a word. Discard the extra word at the end.
  2546. lastWord = words.pop();
  2547. }
  2548. return Pos(lastWord.line, lastWord.to);
  2549. } else {
  2550. // b
  2551. return Pos(lastWord.line, lastWord.from);
  2552. }
  2553. }
  2554. function moveToCharacter(cm, repeat, forward, character) {
  2555. var cur = cm.getCursor();
  2556. var start = cur.ch;
  2557. var idx;
  2558. for (var i = 0; i < repeat; i ++) {
  2559. var line = cm.getLine(cur.line);
  2560. idx = charIdxInLine(start, line, character, forward, true);
  2561. if (idx == -1) {
  2562. return null;
  2563. }
  2564. start = idx;
  2565. }
  2566. return Pos(cm.getCursor().line, idx);
  2567. }
  2568. function moveToColumn(cm, repeat) {
  2569. // repeat is always >= 1, so repeat - 1 always corresponds
  2570. // to the column we want to go to.
  2571. var line = cm.getCursor().line;
  2572. return clipCursorToContent(cm, Pos(line, repeat - 1));
  2573. }
  2574. function updateMark(cm, vim, markName, pos) {
  2575. if (!inArray(markName, validMarks)) {
  2576. return;
  2577. }
  2578. if (vim.marks[markName]) {
  2579. vim.marks[markName].clear();
  2580. }
  2581. vim.marks[markName] = cm.setBookmark(pos);
  2582. }
  2583. function charIdxInLine(start, line, character, forward, includeChar) {
  2584. // Search for char in line.
  2585. // motion_options: {forward, includeChar}
  2586. // If includeChar = true, include it too.
  2587. // If forward = true, search forward, else search backwards.
  2588. // If char is not found on this line, do nothing
  2589. var idx;
  2590. if (forward) {
  2591. idx = line.indexOf(character, start + 1);
  2592. if (idx != -1 && !includeChar) {
  2593. idx -= 1;
  2594. }
  2595. } else {
  2596. idx = line.lastIndexOf(character, start - 1);
  2597. if (idx != -1 && !includeChar) {
  2598. idx += 1;
  2599. }
  2600. }
  2601. return idx;
  2602. }
  2603. function getContextLevel(ctx) {
  2604. return (ctx === 'string' || ctx === 'comment') ? 1 : 0;
  2605. }
  2606. function findMatchedSymbol(cm, cur, symb) {
  2607. var line = cur.line;
  2608. var ch = cur.ch;
  2609. symb = symb ? symb : cm.getLine(line).charAt(ch);
  2610. var symbContext = cm.getTokenAt(Pos(line, ch + 1)).type;
  2611. var symbCtxLevel = getContextLevel(symbContext);
  2612. var reverseSymb = ({
  2613. '(': ')', ')': '(',
  2614. '[': ']', ']': '[',
  2615. '{': '}', '}': '{'})[symb];
  2616. // Couldn't find a matching symbol, abort
  2617. if (!reverseSymb) {
  2618. return cur;
  2619. }
  2620. // set our increment to move forward (+1) or backwards (-1)
  2621. // depending on which bracket we're matching
  2622. var increment = ({'(': 1, '{': 1, '[': 1})[symb] || -1;
  2623. var endLine = increment === 1 ? cm.lineCount() : -1;
  2624. var depth = 1, nextCh = symb, index = ch, lineText = cm.getLine(line);
  2625. // Simple search for closing paren--just count openings and closings till
  2626. // we find our match
  2627. // TODO: use info from CodeMirror to ignore closing brackets in comments
  2628. // and quotes, etc.
  2629. while (line !== endLine && depth > 0) {
  2630. index += increment;
  2631. nextCh = lineText.charAt(index);
  2632. if (!nextCh) {
  2633. line += increment;
  2634. lineText = cm.getLine(line) || '';
  2635. if (increment > 0) {
  2636. index = 0;
  2637. } else {
  2638. var lineLen = lineText.length;
  2639. index = (lineLen > 0) ? (lineLen-1) : 0;
  2640. }
  2641. nextCh = lineText.charAt(index);
  2642. }
  2643. var revSymbContext = cm.getTokenAt(Pos(line, index + 1)).type;
  2644. var revSymbCtxLevel = getContextLevel(revSymbContext);
  2645. if (symbCtxLevel >= revSymbCtxLevel) {
  2646. if (nextCh === symb) {
  2647. depth++;
  2648. } else if (nextCh === reverseSymb) {
  2649. depth--;
  2650. }
  2651. }
  2652. }
  2653. if (nextCh) {
  2654. return Pos(line, index);
  2655. }
  2656. return cur;
  2657. }
  2658. // TODO: perhaps this finagling of start and end positions belonds
  2659. // in codmirror/replaceRange?
  2660. function selectCompanionObject(cm, revSymb, inclusive) {
  2661. var cur = copyCursor(cm.getCursor());
  2662. var end = findMatchedSymbol(cm, cur, revSymb);
  2663. var start = findMatchedSymbol(cm, end);
  2664. if ((start.line == end.line && start.ch > end.ch)
  2665. || (start.line > end.line)) {
  2666. var tmp = start;
  2667. start = end;
  2668. end = tmp;
  2669. }
  2670. if (inclusive) {
  2671. end.ch += 1;
  2672. } else {
  2673. start.ch += 1;
  2674. }
  2675. return { start: start, end: end };
  2676. }
  2677. // Takes in a symbol and a cursor and tries to simulate text objects that
  2678. // have identical opening and closing symbols
  2679. // TODO support across multiple lines
  2680. function findBeginningAndEnd(cm, symb, inclusive) {
  2681. var cur = copyCursor(cm.getCursor());
  2682. var line = cm.getLine(cur.line);
  2683. var chars = line.split('');
  2684. var start, end, i, len;
  2685. var firstIndex = chars.indexOf(symb);
  2686. // the decision tree is to always look backwards for the beginning first,
  2687. // but if the cursor is in front of the first instance of the symb,
  2688. // then move the cursor forward
  2689. if (cur.ch < firstIndex) {
  2690. cur.ch = firstIndex;
  2691. // Why is this line even here???
  2692. // cm.setCursor(cur.line, firstIndex+1);
  2693. }
  2694. // otherwise if the cursor is currently on the closing symbol
  2695. else if (firstIndex < cur.ch && chars[cur.ch] == symb) {
  2696. end = cur.ch; // assign end to the current cursor
  2697. --cur.ch; // make sure to look backwards
  2698. }
  2699. // if we're currently on the symbol, we've got a start
  2700. if (chars[cur.ch] == symb && !end) {
  2701. start = cur.ch + 1; // assign start to ahead of the cursor
  2702. } else {
  2703. // go backwards to find the start
  2704. for (i = cur.ch; i > -1 && !start; i--) {
  2705. if (chars[i] == symb) {
  2706. start = i + 1;
  2707. }
  2708. }
  2709. }
  2710. // look forwards for the end symbol
  2711. if (start && !end) {
  2712. for (i = start, len = chars.length; i < len && !end; i++) {
  2713. if (chars[i] == symb) {
  2714. end = i;
  2715. }
  2716. }
  2717. }
  2718. // nothing found
  2719. if (!start || !end) {
  2720. return { start: cur, end: cur };
  2721. }
  2722. // include the symbols
  2723. if (inclusive) {
  2724. --start; ++end;
  2725. }
  2726. return {
  2727. start: Pos(cur.line, start),
  2728. end: Pos(cur.line, end)
  2729. };
  2730. }
  2731. // Search functions
  2732. defineOption('pcre', true, 'boolean');
  2733. function SearchState() {}
  2734. SearchState.prototype = {
  2735. getQuery: function() {
  2736. return vimGlobalState.query;
  2737. },
  2738. setQuery: function(query) {
  2739. vimGlobalState.query = query;
  2740. },
  2741. getOverlay: function() {
  2742. return this.searchOverlay;
  2743. },
  2744. setOverlay: function(overlay) {
  2745. this.searchOverlay = overlay;
  2746. },
  2747. isReversed: function() {
  2748. return vimGlobalState.isReversed;
  2749. },
  2750. setReversed: function(reversed) {
  2751. vimGlobalState.isReversed = reversed;
  2752. }
  2753. };
  2754. function getSearchState(cm) {
  2755. var vim = cm.state.vim;
  2756. return vim.searchState_ || (vim.searchState_ = new SearchState());
  2757. }
  2758. function dialog(cm, template, shortText, onClose, options) {
  2759. if (cm.openDialog) {
  2760. cm.openDialog(template, onClose, { bottom: true, value: options.value,
  2761. onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp });
  2762. }
  2763. else {
  2764. onClose(prompt(shortText, ''));
  2765. }
  2766. }
  2767. function findUnescapedSlashes(str) {
  2768. var escapeNextChar = false;
  2769. var slashes = [];
  2770. for (var i = 0; i < str.length; i++) {
  2771. var c = str.charAt(i);
  2772. if (!escapeNextChar && c == '/') {
  2773. slashes.push(i);
  2774. }
  2775. escapeNextChar = !escapeNextChar && (c == '\\');
  2776. }
  2777. return slashes;
  2778. }
  2779. // Translates a search string from ex (vim) syntax into javascript form.
  2780. function translateRegex(str) {
  2781. // When these match, add a '\' if unescaped or remove one if escaped.
  2782. var specials = ['|', '(', ')', '{'];
  2783. // Remove, but never add, a '\' for these.
  2784. var unescape = ['}'];
  2785. var escapeNextChar = false;
  2786. var out = [];
  2787. for (var i = -1; i < str.length; i++) {
  2788. var c = str.charAt(i) || '';
  2789. var n = str.charAt(i+1) || '';
  2790. var specialComesNext = (specials.indexOf(n) != -1);
  2791. if (escapeNextChar) {
  2792. if (c !== '\\' || !specialComesNext) {
  2793. out.push(c);
  2794. }
  2795. escapeNextChar = false;
  2796. } else {
  2797. if (c === '\\') {
  2798. escapeNextChar = true;
  2799. // Treat the unescape list as special for removing, but not adding '\'.
  2800. if (unescape.indexOf(n) != -1) {
  2801. specialComesNext = true;
  2802. }
  2803. // Not passing this test means removing a '\'.
  2804. if (!specialComesNext || n === '\\') {
  2805. out.push(c);
  2806. }
  2807. } else {
  2808. out.push(c);
  2809. if (specialComesNext && n !== '\\') {
  2810. out.push('\\');
  2811. }
  2812. }
  2813. }
  2814. }
  2815. return out.join('');
  2816. }
  2817. // Translates the replace part of a search and replace from ex (vim) syntax into
  2818. // javascript form. Similar to translateRegex, but additionally fixes back references
  2819. // (translates '\[0..9]' to '$[0..9]') and follows different rules for escaping '$'.
  2820. function translateRegexReplace(str) {
  2821. var escapeNextChar = false;
  2822. var out = [];
  2823. for (var i = -1; i < str.length; i++) {
  2824. var c = str.charAt(i) || '';
  2825. var n = str.charAt(i+1) || '';
  2826. if (escapeNextChar) {
  2827. // At any point in the loop, escapeNextChar is true if the previous
  2828. // character was a '\' and was not escaped.
  2829. out.push(c);
  2830. escapeNextChar = false;
  2831. } else {
  2832. if (c === '\\') {
  2833. escapeNextChar = true;
  2834. if ((isNumber(n) || n === '$')) {
  2835. out.push('$');
  2836. } else if (n !== '/' && n !== '\\') {
  2837. out.push('\\');
  2838. }
  2839. } else {
  2840. if (c === '$') {
  2841. out.push('$');
  2842. }
  2843. out.push(c);
  2844. if (n === '/') {
  2845. out.push('\\');
  2846. }
  2847. }
  2848. }
  2849. }
  2850. return out.join('');
  2851. }
  2852. // Unescape \ and / in the replace part, for PCRE mode.
  2853. function unescapeRegexReplace(str) {
  2854. var stream = new CodeMirror.StringStream(str);
  2855. var output = [];
  2856. while (!stream.eol()) {
  2857. // Search for \.
  2858. while (stream.peek() && stream.peek() != '\\') {
  2859. output.push(stream.next());
  2860. }
  2861. if (stream.match('\\/', true)) {
  2862. // \/ => /
  2863. output.push('/');
  2864. } else if (stream.match('\\\\', true)) {
  2865. // \\ => \
  2866. output.push('\\');
  2867. } else {
  2868. // Don't change anything
  2869. output.push(stream.next());
  2870. }
  2871. }
  2872. return output.join('');
  2873. }
  2874. /**
  2875. * Extract the regular expression from the query and return a Regexp object.
  2876. * Returns null if the query is blank.
  2877. * If ignoreCase is passed in, the Regexp object will have the 'i' flag set.
  2878. * If smartCase is passed in, and the query contains upper case letters,
  2879. * then ignoreCase is overridden, and the 'i' flag will not be set.
  2880. * If the query contains the /i in the flag part of the regular expression,
  2881. * then both ignoreCase and smartCase are ignored, and 'i' will be passed
  2882. * through to the Regex object.
  2883. */
  2884. function parseQuery(query, ignoreCase, smartCase) {
  2885. // Check if the query is already a regex.
  2886. if (query instanceof RegExp) { return query; }
  2887. // First try to extract regex + flags from the input. If no flags found,
  2888. // extract just the regex. IE does not accept flags directly defined in
  2889. // the regex string in the form /regex/flags
  2890. var slashes = findUnescapedSlashes(query);
  2891. var regexPart;
  2892. var forceIgnoreCase;
  2893. if (!slashes.length) {
  2894. // Query looks like 'regexp'
  2895. regexPart = query;
  2896. } else {
  2897. // Query looks like 'regexp/...'
  2898. regexPart = query.substring(0, slashes[0]);
  2899. var flagsPart = query.substring(slashes[0]);
  2900. forceIgnoreCase = (flagsPart.indexOf('i') != -1);
  2901. }
  2902. if (!regexPart) {
  2903. return null;
  2904. }
  2905. if (!getOption('pcre')) {
  2906. regexPart = translateRegex(regexPart);
  2907. }
  2908. if (smartCase) {
  2909. ignoreCase = (/^[^A-Z]*$/).test(regexPart);
  2910. }
  2911. var regexp = new RegExp(regexPart,
  2912. (ignoreCase || forceIgnoreCase) ? 'i' : undefined);
  2913. return regexp;
  2914. }
  2915. function showConfirm(cm, text) {
  2916. if (cm.openNotification) {
  2917. cm.openNotification('<span style="color: red">' + text + '</span>',
  2918. {bottom: true, duration: 5000});
  2919. } else {
  2920. alert(text);
  2921. }
  2922. }
  2923. function makePrompt(prefix, desc) {
  2924. var raw = '';
  2925. if (prefix) {
  2926. raw += '<span style="font-family: monospace">' + prefix + '</span>';
  2927. }
  2928. raw += '<input type="text"/> ' +
  2929. '<span style="color: #888">';
  2930. if (desc) {
  2931. raw += '<span style="color: #888">';
  2932. raw += desc;
  2933. raw += '</span>';
  2934. }
  2935. return raw;
  2936. }
  2937. var searchPromptDesc = '(Javascript regexp)';
  2938. function showPrompt(cm, options) {
  2939. var shortText = (options.prefix || '') + ' ' + (options.desc || '');
  2940. var prompt = makePrompt(options.prefix, options.desc);
  2941. dialog(cm, prompt, shortText, options.onClose, options);
  2942. }
  2943. function regexEqual(r1, r2) {
  2944. if (r1 instanceof RegExp && r2 instanceof RegExp) {
  2945. var props = ['global', 'multiline', 'ignoreCase', 'source'];
  2946. for (var i = 0; i < props.length; i++) {
  2947. var prop = props[i];
  2948. if (r1[prop] !== r2[prop]) {
  2949. return false;
  2950. }
  2951. }
  2952. return true;
  2953. }
  2954. return false;
  2955. }
  2956. // Returns true if the query is valid.
  2957. function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {
  2958. if (!rawQuery) {
  2959. return;
  2960. }
  2961. var state = getSearchState(cm);
  2962. var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase);
  2963. if (!query) {
  2964. return;
  2965. }
  2966. highlightSearchMatches(cm, query);
  2967. if (regexEqual(query, state.getQuery())) {
  2968. return query;
  2969. }
  2970. state.setQuery(query);
  2971. return query;
  2972. }
  2973. function searchOverlay(query) {
  2974. if (query.source.charAt(0) == '^') {
  2975. var matchSol = true;
  2976. }
  2977. return {
  2978. token: function(stream) {
  2979. if (matchSol && !stream.sol()) {
  2980. stream.skipToEnd();
  2981. return;
  2982. }
  2983. var match = stream.match(query, false);
  2984. if (match) {
  2985. if (match[0].length == 0) {
  2986. // Matched empty string, skip to next.
  2987. stream.next();
  2988. return 'searching';
  2989. }
  2990. if (!stream.sol()) {
  2991. // Backtrack 1 to match \b
  2992. stream.backUp(1);
  2993. if (!query.exec(stream.next() + match[0])) {
  2994. stream.next();
  2995. return null;
  2996. }
  2997. }
  2998. stream.match(query);
  2999. return 'searching';
  3000. }
  3001. while (!stream.eol()) {
  3002. stream.next();
  3003. if (stream.match(query, false)) break;
  3004. }
  3005. },
  3006. query: query
  3007. };
  3008. }
  3009. function highlightSearchMatches(cm, query) {
  3010. var overlay = getSearchState(cm).getOverlay();
  3011. if (!overlay || query != overlay.query) {
  3012. if (overlay) {
  3013. cm.removeOverlay(overlay);
  3014. }
  3015. overlay = searchOverlay(query);
  3016. cm.addOverlay(overlay);
  3017. getSearchState(cm).setOverlay(overlay);
  3018. }
  3019. }
  3020. function findNext(cm, prev, query, repeat) {
  3021. if (repeat === undefined) { repeat = 1; }
  3022. return cm.operation(function() {
  3023. var pos = cm.getCursor();
  3024. var cursor = cm.getSearchCursor(query, pos);
  3025. for (var i = 0; i < repeat; i++) {
  3026. var found = cursor.find(prev);
  3027. if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); }
  3028. if (!found) {
  3029. // SearchCursor may have returned null because it hit EOF, wrap
  3030. // around and try again.
  3031. cursor = cm.getSearchCursor(query,
  3032. (prev) ? Pos(cm.lastLine()) : Pos(cm.firstLine(), 0) );
  3033. if (!cursor.find(prev)) {
  3034. return;
  3035. }
  3036. }
  3037. }
  3038. return cursor.from();
  3039. });
  3040. }
  3041. function clearSearchHighlight(cm) {
  3042. cm.removeOverlay(getSearchState(cm).getOverlay());
  3043. getSearchState(cm).setOverlay(null);
  3044. }
  3045. /**
  3046. * Check if pos is in the specified range, INCLUSIVE.
  3047. * Range can be specified with 1 or 2 arguments.
  3048. * If the first range argument is an array, treat it as an array of line
  3049. * numbers. Match pos against any of the lines.
  3050. * If the first range argument is a number,
  3051. * if there is only 1 range argument, check if pos has the same line
  3052. * number
  3053. * if there are 2 range arguments, then check if pos is in between the two
  3054. * range arguments.
  3055. */
  3056. function isInRange(pos, start, end) {
  3057. if (typeof pos != 'number') {
  3058. // Assume it is a cursor position. Get the line number.
  3059. pos = pos.line;
  3060. }
  3061. if (start instanceof Array) {
  3062. return inArray(pos, start);
  3063. } else {
  3064. if (end) {
  3065. return (pos >= start && pos <= end);
  3066. } else {
  3067. return pos == start;
  3068. }
  3069. }
  3070. }
  3071. function getUserVisibleLines(cm) {
  3072. var scrollInfo = cm.getScrollInfo();
  3073. var occludeToleranceTop = 6;
  3074. var occludeToleranceBottom = 10;
  3075. var from = cm.coordsChar({left:0, top: occludeToleranceTop + scrollInfo.top}, 'local');
  3076. var bottomY = scrollInfo.clientHeight - occludeToleranceBottom + scrollInfo.top;
  3077. var to = cm.coordsChar({left:0, top: bottomY}, 'local');
  3078. return {top: from.line, bottom: to.line};
  3079. }
  3080. // Ex command handling
  3081. // Care must be taken when adding to the default Ex command map. For any
  3082. // pair of commands that have a shared prefix, at least one of their
  3083. // shortNames must not match the prefix of the other command.
  3084. var defaultExCommandMap = [
  3085. { name: 'map' },
  3086. { name: 'nmap', shortName: 'nm' },
  3087. { name: 'vmap', shortName: 'vm' },
  3088. { name: 'unmap' },
  3089. { name: 'write', shortName: 'w' },
  3090. { name: 'undo', shortName: 'u' },
  3091. { name: 'redo', shortName: 'red' },
  3092. { name: 'set', shortName: 'set' },
  3093. { name: 'sort', shortName: 'sor' },
  3094. { name: 'substitute', shortName: 's' },
  3095. { name: 'nohlsearch', shortName: 'noh' },
  3096. { name: 'delmarks', shortName: 'delm' },
  3097. { name: 'registers', shortName: 'reg' }
  3098. ];
  3099. Vim.ExCommandDispatcher = function() {
  3100. this.buildCommandMap_();
  3101. };
  3102. Vim.ExCommandDispatcher.prototype = {
  3103. processCommand: function(cm, input) {
  3104. var vim = cm.state.vim;
  3105. if (vim.visualMode) {
  3106. exitVisualMode(cm);
  3107. }
  3108. var inputStream = new CodeMirror.StringStream(input);
  3109. var params = {};
  3110. params.input = input;
  3111. try {
  3112. this.parseInput_(cm, inputStream, params);
  3113. } catch(e) {
  3114. showConfirm(cm, e);
  3115. throw e;
  3116. }
  3117. var commandName;
  3118. if (!params.commandName) {
  3119. // If only a line range is defined, move to the line.
  3120. if (params.line !== undefined) {
  3121. commandName = 'move';
  3122. }
  3123. } else {
  3124. var command = this.matchCommand_(params.commandName);
  3125. if (command) {
  3126. commandName = command.name;
  3127. this.parseCommandArgs_(inputStream, params, command);
  3128. if (command.type == 'exToKey') {
  3129. // Handle Ex to Key mapping.
  3130. for (var i = 0; i < command.toKeys.length; i++) {
  3131. CodeMirror.Vim.handleKey(cm, command.toKeys[i]);
  3132. }
  3133. return;
  3134. } else if (command.type == 'exToEx') {
  3135. // Handle Ex to Ex mapping.
  3136. this.processCommand(cm, command.toInput);
  3137. return;
  3138. }
  3139. }
  3140. }
  3141. if (!commandName) {
  3142. showConfirm(cm, 'Not an editor command ":' + input + '"');
  3143. return;
  3144. }
  3145. try {
  3146. exCommands[commandName](cm, params);
  3147. } catch(e) {
  3148. showConfirm(cm, e);
  3149. throw e;
  3150. }
  3151. },
  3152. parseInput_: function(cm, inputStream, result) {
  3153. inputStream.eatWhile(':');
  3154. // Parse range.
  3155. if (inputStream.eat('%')) {
  3156. result.line = cm.firstLine();
  3157. result.lineEnd = cm.lastLine();
  3158. } else {
  3159. result.line = this.parseLineSpec_(cm, inputStream);
  3160. if (result.line !== undefined && inputStream.eat(',')) {
  3161. result.lineEnd = this.parseLineSpec_(cm, inputStream);
  3162. }
  3163. }
  3164. // Parse command name.
  3165. var commandMatch = inputStream.match(/^(\w+)/);
  3166. if (commandMatch) {
  3167. result.commandName = commandMatch[1];
  3168. } else {
  3169. result.commandName = inputStream.match(/.*/)[0];
  3170. }
  3171. return result;
  3172. },
  3173. parseLineSpec_: function(cm, inputStream) {
  3174. var numberMatch = inputStream.match(/^(\d+)/);
  3175. if (numberMatch) {
  3176. return parseInt(numberMatch[1], 10) - 1;
  3177. }
  3178. switch (inputStream.next()) {
  3179. case '.':
  3180. return cm.getCursor().line;
  3181. case '$':
  3182. return cm.lastLine();
  3183. case '\'':
  3184. var mark = cm.state.vim.marks[inputStream.next()];
  3185. if (mark && mark.find()) {
  3186. return mark.find().line;
  3187. }
  3188. throw new Error('Mark not set');
  3189. default:
  3190. inputStream.backUp(1);
  3191. return undefined;
  3192. }
  3193. },
  3194. parseCommandArgs_: function(inputStream, params, command) {
  3195. if (inputStream.eol()) {
  3196. return;
  3197. }
  3198. params.argString = inputStream.match(/.*/)[0];
  3199. // Parse command-line arguments
  3200. var delim = command.argDelimiter || /\s+/;
  3201. var args = trim(params.argString).split(delim);
  3202. if (args.length && args[0]) {
  3203. params.args = args;
  3204. }
  3205. },
  3206. matchCommand_: function(commandName) {
  3207. // Return the command in the command map that matches the shortest
  3208. // prefix of the passed in command name. The match is guaranteed to be
  3209. // unambiguous if the defaultExCommandMap's shortNames are set up
  3210. // correctly. (see @code{defaultExCommandMap}).
  3211. for (var i = commandName.length; i > 0; i--) {
  3212. var prefix = commandName.substring(0, i);
  3213. if (this.commandMap_[prefix]) {
  3214. var command = this.commandMap_[prefix];
  3215. if (command.name.indexOf(commandName) === 0) {
  3216. return command;
  3217. }
  3218. }
  3219. }
  3220. return null;
  3221. },
  3222. buildCommandMap_: function() {
  3223. this.commandMap_ = {};
  3224. for (var i = 0; i < defaultExCommandMap.length; i++) {
  3225. var command = defaultExCommandMap[i];
  3226. var key = command.shortName || command.name;
  3227. this.commandMap_[key] = command;
  3228. }
  3229. },
  3230. map: function(lhs, rhs, ctx) {
  3231. if (lhs != ':' && lhs.charAt(0) == ':') {
  3232. if (ctx) { throw Error('Mode not supported for ex mappings'); }
  3233. var commandName = lhs.substring(1);
  3234. if (rhs != ':' && rhs.charAt(0) == ':') {
  3235. // Ex to Ex mapping
  3236. this.commandMap_[commandName] = {
  3237. name: commandName,
  3238. type: 'exToEx',
  3239. toInput: rhs.substring(1),
  3240. user: true
  3241. };
  3242. } else {
  3243. // Ex to key mapping
  3244. this.commandMap_[commandName] = {
  3245. name: commandName,
  3246. type: 'exToKey',
  3247. toKeys: parseKeyString(rhs),
  3248. user: true
  3249. };
  3250. }
  3251. } else {
  3252. if (rhs != ':' && rhs.charAt(0) == ':') {
  3253. // Key to Ex mapping.
  3254. var mapping = {
  3255. keys: parseKeyString(lhs),
  3256. type: 'keyToEx',
  3257. exArgs: { input: rhs.substring(1) },
  3258. user: true};
  3259. if (ctx) { mapping.context = ctx; }
  3260. defaultKeymap.unshift(mapping);
  3261. } else {
  3262. // Key to key mapping
  3263. var mapping = {
  3264. keys: parseKeyString(lhs),
  3265. type: 'keyToKey',
  3266. toKeys: parseKeyString(rhs),
  3267. user: true
  3268. };
  3269. if (ctx) { mapping.context = ctx; }
  3270. defaultKeymap.unshift(mapping);
  3271. }
  3272. }
  3273. },
  3274. unmap: function(lhs, ctx) {
  3275. var arrayEquals = function(a, b) {
  3276. if (a === b) return true;
  3277. if (a == null || b == null) return true;
  3278. if (a.length != b.length) return false;
  3279. for (var i = 0; i < a.length; i++) {
  3280. if (a[i] !== b[i]) return false;
  3281. }
  3282. return true;
  3283. };
  3284. if (lhs != ':' && lhs.charAt(0) == ':') {
  3285. // Ex to Ex or Ex to key mapping
  3286. if (ctx) { throw Error('Mode not supported for ex mappings'); }
  3287. var commandName = lhs.substring(1);
  3288. if (this.commandMap_[commandName] && this.commandMap_[commandName].user) {
  3289. delete this.commandMap_[commandName];
  3290. return;
  3291. }
  3292. } else {
  3293. // Key to Ex or key to key mapping
  3294. var keys = parseKeyString(lhs);
  3295. for (var i = 0; i < defaultKeymap.length; i++) {
  3296. if (arrayEquals(keys, defaultKeymap[i].keys)
  3297. && defaultKeymap[i].context === ctx
  3298. && defaultKeymap[i].user) {
  3299. defaultKeymap.splice(i, 1);
  3300. return;
  3301. }
  3302. }
  3303. }
  3304. throw Error('No such mapping.');
  3305. }
  3306. };
  3307. // Converts a key string sequence of the form a<C-w>bd<Left> into Vim's
  3308. // keymap representation.
  3309. function parseKeyString(str) {
  3310. var key, match;
  3311. var keys = [];
  3312. while (str) {
  3313. match = (/<\w+-.+?>|<\w+>|./).exec(str);
  3314. if (match === null)break;
  3315. key = match[0];
  3316. str = str.substring(match.index + key.length);
  3317. keys.push(key);
  3318. }
  3319. return keys;
  3320. }
  3321. var exCommands = {
  3322. map: function(cm, params, ctx) {
  3323. var mapArgs = params.args;
  3324. if (!mapArgs || mapArgs.length < 2) {
  3325. if (cm) {
  3326. showConfirm(cm, 'Invalid mapping: ' + params.input);
  3327. }
  3328. return;
  3329. }
  3330. exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx);
  3331. },
  3332. nmap: function(cm, params) { this.map(cm, params, 'normal'); },
  3333. vmap: function(cm, params) { this.map(cm, params, 'visual'); },
  3334. unmap: function(cm, params, ctx) {
  3335. var mapArgs = params.args;
  3336. if (!mapArgs || mapArgs.length < 1) {
  3337. if (cm) {
  3338. showConfirm(cm, 'No such mapping: ' + params.input);
  3339. }
  3340. return;
  3341. }
  3342. exCommandDispatcher.unmap(mapArgs[0], ctx);
  3343. },
  3344. move: function(cm, params) {
  3345. commandDispatcher.processCommand(cm, cm.state.vim, {
  3346. type: 'motion',
  3347. motion: 'moveToLineOrEdgeOfDocument',
  3348. motionArgs: { forward: false, explicitRepeat: true,
  3349. linewise: true },
  3350. repeatOverride: params.line+1});
  3351. },
  3352. set: function(cm, params) {
  3353. var setArgs = params.args;
  3354. if (!setArgs || setArgs.length < 1) {
  3355. if (cm) {
  3356. showConfirm(cm, 'Invalid mapping: ' + params.input);
  3357. }
  3358. return;
  3359. }
  3360. var expr = setArgs[0].split('=');
  3361. var optionName = expr[0];
  3362. var value = expr[1];
  3363. var forceGet = false;
  3364. if (optionName.charAt(optionName.length - 1) == '?') {
  3365. // If post-fixed with ?, then the set is actually a get.
  3366. if (value) { throw Error('Trailing characters: ' + params.argString); }
  3367. optionName = optionName.substring(0, optionName.length - 1);
  3368. forceGet = true;
  3369. }
  3370. if (value === undefined && optionName.substring(0, 2) == 'no') {
  3371. // To set boolean options to false, the option name is prefixed with
  3372. // 'no'.
  3373. optionName = optionName.substring(2);
  3374. value = false;
  3375. }
  3376. var optionIsBoolean = options[optionName] && options[optionName].type == 'boolean';
  3377. if (optionIsBoolean && value == undefined) {
  3378. // Calling set with a boolean option sets it to true.
  3379. value = true;
  3380. }
  3381. if (!optionIsBoolean && !value || forceGet) {
  3382. var oldValue = getOption(optionName);
  3383. // If no value is provided, then we assume this is a get.
  3384. if (oldValue === true || oldValue === false) {
  3385. showConfirm(cm, ' ' + (oldValue ? '' : 'no') + optionName);
  3386. } else {
  3387. showConfirm(cm, ' ' + optionName + '=' + oldValue);
  3388. }
  3389. } else {
  3390. setOption(optionName, value);
  3391. }
  3392. },
  3393. registers: function(cm,params) {
  3394. var regArgs = params.args;
  3395. var registers = vimGlobalState.registerController.registers;
  3396. var regInfo = '----------Registers----------<br><br>';
  3397. if (!regArgs) {
  3398. for (var registerName in registers) {
  3399. var text = registers[registerName].toString();
  3400. if (text.length) {
  3401. regInfo += '"' + registerName + ' ' + text + '<br>';
  3402. }
  3403. }
  3404. } else {
  3405. var registerName;
  3406. regArgs = regArgs.join('');
  3407. for (var i = 0; i < regArgs.length; i++) {
  3408. registerName = regArgs.charAt(i);
  3409. if (!vimGlobalState.registerController.isValidRegister(registerName)) {
  3410. continue;
  3411. }
  3412. var register = registers[registerName] || new Register();
  3413. regInfo += '"' + registerName + ' ' + register.text + '<br>';
  3414. }
  3415. }
  3416. showConfirm(cm, regInfo);
  3417. },
  3418. sort: function(cm, params) {
  3419. var reverse, ignoreCase, unique, number;
  3420. function parseArgs() {
  3421. if (params.argString) {
  3422. var args = new CodeMirror.StringStream(params.argString);
  3423. if (args.eat('!')) { reverse = true; }
  3424. if (args.eol()) { return; }
  3425. if (!args.eatSpace()) { return 'Invalid arguments'; }
  3426. var opts = args.match(/[a-z]+/);
  3427. if (opts) {
  3428. opts = opts[0];
  3429. ignoreCase = opts.indexOf('i') != -1;
  3430. unique = opts.indexOf('u') != -1;
  3431. var decimal = opts.indexOf('d') != -1 && 1;
  3432. var hex = opts.indexOf('x') != -1 && 1;
  3433. var octal = opts.indexOf('o') != -1 && 1;
  3434. if (decimal + hex + octal > 1) { return 'Invalid arguments'; }
  3435. number = decimal && 'decimal' || hex && 'hex' || octal && 'octal';
  3436. }
  3437. if (args.eatSpace() && args.match(/\/.*\//)) { 'patterns not supported'; }
  3438. }
  3439. }
  3440. var err = parseArgs();
  3441. if (err) {
  3442. showConfirm(cm, err + ': ' + params.argString);
  3443. return;
  3444. }
  3445. var lineStart = params.line || cm.firstLine();
  3446. var lineEnd = params.lineEnd || params.line || cm.lastLine();
  3447. if (lineStart == lineEnd) { return; }
  3448. var curStart = Pos(lineStart, 0);
  3449. var curEnd = Pos(lineEnd, lineLength(cm, lineEnd));
  3450. var text = cm.getRange(curStart, curEnd).split('\n');
  3451. var numberRegex = (number == 'decimal') ? /(-?)([\d]+)/ :
  3452. (number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i :
  3453. (number == 'octal') ? /([0-7]+)/ : null;
  3454. var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null;
  3455. var numPart = [], textPart = [];
  3456. if (number) {
  3457. for (var i = 0; i < text.length; i++) {
  3458. if (numberRegex.exec(text[i])) {
  3459. numPart.push(text[i]);
  3460. } else {
  3461. textPart.push(text[i]);
  3462. }
  3463. }
  3464. } else {
  3465. textPart = text;
  3466. }
  3467. function compareFn(a, b) {
  3468. if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
  3469. if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); }
  3470. var anum = number && numberRegex.exec(a);
  3471. var bnum = number && numberRegex.exec(b);
  3472. if (!anum) { return a < b ? -1 : 1; }
  3473. anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix);
  3474. bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix);
  3475. return anum - bnum;
  3476. }
  3477. numPart.sort(compareFn);
  3478. textPart.sort(compareFn);
  3479. text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart);
  3480. if (unique) { // Remove duplicate lines
  3481. var textOld = text;
  3482. var lastLine;
  3483. text = [];
  3484. for (var i = 0; i < textOld.length; i++) {
  3485. if (textOld[i] != lastLine) {
  3486. text.push(textOld[i]);
  3487. }
  3488. lastLine = textOld[i];
  3489. }
  3490. }
  3491. cm.replaceRange(text.join('\n'), curStart, curEnd);
  3492. },
  3493. substitute: function(cm, params) {
  3494. if (!cm.getSearchCursor) {
  3495. throw new Error('Search feature not available. Requires searchcursor.js or ' +
  3496. 'any other getSearchCursor implementation.');
  3497. }
  3498. var argString = params.argString;
  3499. var slashes = findUnescapedSlashes(argString);
  3500. if (slashes[0] !== 0) {
  3501. showConfirm(cm, 'Substitutions should be of the form ' +
  3502. ':s/pattern/replace/');
  3503. return;
  3504. }
  3505. var regexPart = argString.substring(slashes[0] + 1, slashes[1]);
  3506. var replacePart = '';
  3507. var flagsPart;
  3508. var count;
  3509. var confirm = false; // Whether to confirm each replace.
  3510. if (slashes[1]) {
  3511. replacePart = argString.substring(slashes[1] + 1, slashes[2]);
  3512. if (getOption('pcre')) {
  3513. replacePart = unescapeRegexReplace(replacePart);
  3514. } else {
  3515. replacePart = translateRegexReplace(replacePart);
  3516. }
  3517. }
  3518. if (slashes[2]) {
  3519. // After the 3rd slash, we can have flags followed by a space followed
  3520. // by count.
  3521. var trailing = argString.substring(slashes[2] + 1).split(' ');
  3522. flagsPart = trailing[0];
  3523. count = parseInt(trailing[1]);
  3524. }
  3525. if (flagsPart) {
  3526. if (flagsPart.indexOf('c') != -1) {
  3527. confirm = true;
  3528. flagsPart.replace('c', '');
  3529. }
  3530. regexPart = regexPart + '/' + flagsPart;
  3531. }
  3532. if (regexPart) {
  3533. // If regex part is empty, then use the previous query. Otherwise use
  3534. // the regex part as the new query.
  3535. try {
  3536. updateSearchQuery(cm, regexPart, true /** ignoreCase */,
  3537. true /** smartCase */);
  3538. } catch (e) {
  3539. showConfirm(cm, 'Invalid regex: ' + regexPart);
  3540. return;
  3541. }
  3542. }
  3543. var state = getSearchState(cm);
  3544. var query = state.getQuery();
  3545. var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line;
  3546. var lineEnd = params.lineEnd || lineStart;
  3547. if (count) {
  3548. lineStart = lineEnd;
  3549. lineEnd = lineStart + count - 1;
  3550. }
  3551. var startPos = clipCursorToContent(cm, Pos(lineStart, 0));
  3552. var cursor = cm.getSearchCursor(query, startPos);
  3553. doReplace(cm, confirm, lineStart, lineEnd, cursor, query, replacePart);
  3554. },
  3555. redo: CodeMirror.commands.redo,
  3556. undo: CodeMirror.commands.undo,
  3557. write: function(cm) {
  3558. if (CodeMirror.commands.save) {
  3559. // If a save command is defined, call it.
  3560. CodeMirror.commands.save(cm);
  3561. } else {
  3562. // Saves to text area if no save command is defined.
  3563. cm.save();
  3564. }
  3565. },
  3566. nohlsearch: function(cm) {
  3567. clearSearchHighlight(cm);
  3568. },
  3569. delmarks: function(cm, params) {
  3570. if (!params.argString || !trim(params.argString)) {
  3571. showConfirm(cm, 'Argument required');
  3572. return;
  3573. }
  3574. var state = cm.state.vim;
  3575. var stream = new CodeMirror.StringStream(trim(params.argString));
  3576. while (!stream.eol()) {
  3577. stream.eatSpace();
  3578. // Record the streams position at the beginning of the loop for use
  3579. // in error messages.
  3580. var count = stream.pos;
  3581. if (!stream.match(/[a-zA-Z]/, false)) {
  3582. showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
  3583. return;
  3584. }
  3585. var sym = stream.next();
  3586. // Check if this symbol is part of a range
  3587. if (stream.match('-', true)) {
  3588. // This symbol is part of a range.
  3589. // The range must terminate at an alphabetic character.
  3590. if (!stream.match(/[a-zA-Z]/, false)) {
  3591. showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
  3592. return;
  3593. }
  3594. var startMark = sym;
  3595. var finishMark = stream.next();
  3596. // The range must terminate at an alphabetic character which
  3597. // shares the same case as the start of the range.
  3598. if (isLowerCase(startMark) && isLowerCase(finishMark) ||
  3599. isUpperCase(startMark) && isUpperCase(finishMark)) {
  3600. var start = startMark.charCodeAt(0);
  3601. var finish = finishMark.charCodeAt(0);
  3602. if (start >= finish) {
  3603. showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
  3604. return;
  3605. }
  3606. // Because marks are always ASCII values, and we have
  3607. // determined that they are the same case, we can use
  3608. // their char codes to iterate through the defined range.
  3609. for (var j = 0; j <= finish - start; j++) {
  3610. var mark = String.fromCharCode(start + j);
  3611. delete state.marks[mark];
  3612. }
  3613. } else {
  3614. showConfirm(cm, 'Invalid argument: ' + startMark + '-');
  3615. return;
  3616. }
  3617. } else {
  3618. // This symbol is a valid mark, and is not part of a range.
  3619. delete state.marks[sym];
  3620. }
  3621. }
  3622. }
  3623. };
  3624. var exCommandDispatcher = new Vim.ExCommandDispatcher();
  3625. /**
  3626. * @param {CodeMirror} cm CodeMirror instance we are in.
  3627. * @param {boolean} confirm Whether to confirm each replace.
  3628. * @param {Cursor} lineStart Line to start replacing from.
  3629. * @param {Cursor} lineEnd Line to stop replacing at.
  3630. * @param {RegExp} query Query for performing matches with.
  3631. * @param {string} replaceWith Text to replace matches with. May contain $1,
  3632. * $2, etc for replacing captured groups using Javascript replace.
  3633. */
  3634. function doReplace(cm, confirm, lineStart, lineEnd, searchCursor, query,
  3635. replaceWith) {
  3636. // Set up all the functions.
  3637. cm.state.vim.exMode = true;
  3638. var done = false;
  3639. var lastPos = searchCursor.from();
  3640. function replaceAll() {
  3641. cm.operation(function() {
  3642. while (!done) {
  3643. replace();
  3644. next();
  3645. }
  3646. stop();
  3647. });
  3648. }
  3649. function replace() {
  3650. var text = cm.getRange(searchCursor.from(), searchCursor.to());
  3651. var newText = text.replace(query, replaceWith);
  3652. searchCursor.replace(newText);
  3653. }
  3654. function next() {
  3655. var found = searchCursor.findNext();
  3656. if (!found) {
  3657. done = true;
  3658. } else if (isInRange(searchCursor.from(), lineStart, lineEnd)) {
  3659. cm.scrollIntoView(searchCursor.from(), 30);
  3660. cm.setSelection(searchCursor.from(), searchCursor.to());
  3661. lastPos = searchCursor.from();
  3662. done = false;
  3663. } else {
  3664. done = true;
  3665. }
  3666. }
  3667. function stop(close) {
  3668. if (close) { close(); }
  3669. cm.focus();
  3670. if (lastPos) {
  3671. cm.setCursor(lastPos);
  3672. var vim = cm.state.vim;
  3673. vim.exMode = false;
  3674. vim.lastHPos = vim.lastHSPos = lastPos.ch;
  3675. }
  3676. }
  3677. function onPromptKeyDown(e, _value, close) {
  3678. // Swallow all keys.
  3679. CodeMirror.e_stop(e);
  3680. var keyName = CodeMirror.keyName(e);
  3681. switch (keyName) {
  3682. case 'Y':
  3683. replace(); next(); break;
  3684. case 'N':
  3685. next(); break;
  3686. case 'A':
  3687. cm.operation(replaceAll); break;
  3688. case 'L':
  3689. replace();
  3690. // fall through and exit.
  3691. case 'Q':
  3692. case 'Esc':
  3693. case 'Ctrl-C':
  3694. case 'Ctrl-[':
  3695. stop(close);
  3696. break;
  3697. }
  3698. if (done) { stop(close); }
  3699. }
  3700. // Actually do replace.
  3701. next();
  3702. if (done) {
  3703. showConfirm(cm, 'No matches for ' + query.source);
  3704. return;
  3705. }
  3706. if (!confirm) {
  3707. replaceAll();
  3708. return;
  3709. }
  3710. showPrompt(cm, {
  3711. prefix: 'replace with <strong>' + replaceWith + '</strong> (y/n/a/q/l)',
  3712. onKeyDown: onPromptKeyDown
  3713. });
  3714. }
  3715. // Register Vim with CodeMirror
  3716. function buildVimKeyMap() {
  3717. /**
  3718. * Handle the raw key event from CodeMirror. Translate the
  3719. * Shift + key modifier to the resulting letter, while preserving other
  3720. * modifers.
  3721. */
  3722. function cmKeyToVimKey(key, modifier) {
  3723. var vimKey = key;
  3724. if (isUpperCase(vimKey) && modifier == 'Ctrl') {
  3725. vimKey = vimKey.toLowerCase();
  3726. }
  3727. if (modifier) {
  3728. // Vim will parse modifier+key combination as a single key.
  3729. vimKey = modifier.charAt(0) + '-' + vimKey;
  3730. }
  3731. var specialKey = ({Enter:'CR',Backspace:'BS',Delete:'Del'})[vimKey];
  3732. vimKey = specialKey ? specialKey : vimKey;
  3733. vimKey = vimKey.length > 1 ? '<'+ vimKey + '>' : vimKey;
  3734. return vimKey;
  3735. }
  3736. // Closure to bind CodeMirror, key, modifier.
  3737. function keyMapper(vimKey) {
  3738. return function(cm) {
  3739. CodeMirror.Vim.handleKey(cm, vimKey);
  3740. };
  3741. }
  3742. var cmToVimKeymap = {
  3743. 'nofallthrough': true,
  3744. 'style': 'fat-cursor'
  3745. };
  3746. function bindKeys(keys, modifier) {
  3747. for (var i = 0; i < keys.length; i++) {
  3748. var key = keys[i];
  3749. if (!modifier && key.length == 1) {
  3750. // Wrap all keys without modifiers with '' to identify them by their
  3751. // key characters instead of key identifiers.
  3752. key = "'" + key + "'";
  3753. }
  3754. var vimKey = cmKeyToVimKey(keys[i], modifier);
  3755. var cmKey = modifier ? modifier + '-' + key : key;
  3756. cmToVimKeymap[cmKey] = keyMapper(vimKey);
  3757. }
  3758. }
  3759. bindKeys(upperCaseAlphabet);
  3760. bindKeys(lowerCaseAlphabet);
  3761. bindKeys(upperCaseAlphabet, 'Ctrl');
  3762. bindKeys(specialSymbols);
  3763. bindKeys(specialSymbols, 'Ctrl');
  3764. bindKeys(numbers);
  3765. bindKeys(numbers, 'Ctrl');
  3766. bindKeys(specialKeys);
  3767. bindKeys(specialKeys, 'Ctrl');
  3768. return cmToVimKeymap;
  3769. }
  3770. CodeMirror.keyMap.vim = buildVimKeyMap();
  3771. function exitInsertMode(cm) {
  3772. var vim = cm.state.vim;
  3773. var macroModeState = vimGlobalState.macroModeState;
  3774. var isPlaying = macroModeState.isPlaying;
  3775. if (!isPlaying) {
  3776. cm.off('change', onChange);
  3777. cm.off('cursorActivity', onCursorActivity);
  3778. CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
  3779. }
  3780. if (!isPlaying && vim.insertModeRepeat > 1) {
  3781. // Perform insert mode repeat for commands like 3,a and 3,o.
  3782. repeatLastEdit(cm, vim, vim.insertModeRepeat - 1,
  3783. true /** repeatForInsert */);
  3784. vim.lastEditInputState.repeatOverride = vim.insertModeRepeat;
  3785. }
  3786. delete vim.insertModeRepeat;
  3787. cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1);
  3788. vim.insertMode = false;
  3789. cm.setOption('keyMap', 'vim');
  3790. cm.setOption('disableInput', true);
  3791. cm.toggleOverwrite(false); // exit replace mode if we were in it.
  3792. CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
  3793. if (macroModeState.isRecording) {
  3794. logInsertModeChange(macroModeState);
  3795. }
  3796. }
  3797. CodeMirror.keyMap['vim-insert'] = {
  3798. // TODO: override navigation keys so that Esc will cancel automatic
  3799. // indentation from o, O, i_<CR>
  3800. 'Esc': exitInsertMode,
  3801. 'Ctrl-[': exitInsertMode,
  3802. 'Ctrl-C': exitInsertMode,
  3803. 'Ctrl-N': 'autocomplete',
  3804. 'Ctrl-P': 'autocomplete',
  3805. 'Enter': function(cm) {
  3806. var fn = CodeMirror.commands.newlineAndIndentContinueComment ||
  3807. CodeMirror.commands.newlineAndIndent;
  3808. fn(cm);
  3809. },
  3810. fallthrough: ['default']
  3811. };
  3812. CodeMirror.keyMap['vim-replace'] = {
  3813. 'Backspace': 'goCharLeft',
  3814. fallthrough: ['vim-insert']
  3815. };
  3816. function executeMacroRegister(cm, vim, macroModeState, registerName) {
  3817. var register = vimGlobalState.registerController.getRegister(registerName);
  3818. var keyBuffer = register.keyBuffer;
  3819. var imc = 0;
  3820. macroModeState.isPlaying = true;
  3821. for (var i = 0; i < keyBuffer.length; i++) {
  3822. var text = keyBuffer[i];
  3823. var match, key;
  3824. while (text) {
  3825. // Pull off one command key, which is either a single character
  3826. // or a special sequence wrapped in '<' and '>', e.g. '<Space>'.
  3827. match = (/<\w+-.+?>|<\w+>|./).exec(text);
  3828. key = match[0];
  3829. text = text.substring(match.index + key.length);
  3830. CodeMirror.Vim.handleKey(cm, key);
  3831. if (vim.insertMode) {
  3832. repeatInsertModeChanges(
  3833. cm, register.insertModeChanges[imc++].changes, 1);
  3834. exitInsertMode(cm);
  3835. }
  3836. }
  3837. };
  3838. macroModeState.isPlaying = false;
  3839. }
  3840. function logKey(macroModeState, key) {
  3841. if (macroModeState.isPlaying) { return; }
  3842. var registerName = macroModeState.latestRegister;
  3843. var register = vimGlobalState.registerController.getRegister(registerName);
  3844. if (register) {
  3845. register.pushText(key);
  3846. }
  3847. }
  3848. function logInsertModeChange(macroModeState) {
  3849. if (macroModeState.isPlaying) { return; }
  3850. var registerName = macroModeState.latestRegister;
  3851. var register = vimGlobalState.registerController.getRegister(registerName);
  3852. if (register) {
  3853. register.pushInsertModeChanges(macroModeState.lastInsertModeChanges);
  3854. }
  3855. }
  3856. /**
  3857. * Listens for changes made in insert mode.
  3858. * Should only be active in insert mode.
  3859. */
  3860. function onChange(_cm, changeObj) {
  3861. var macroModeState = vimGlobalState.macroModeState;
  3862. var lastChange = macroModeState.lastInsertModeChanges;
  3863. if (!macroModeState.isPlaying) {
  3864. while(changeObj) {
  3865. lastChange.expectCursorActivityForChange = true;
  3866. if (changeObj.origin == '+input' || changeObj.origin == 'paste'
  3867. || changeObj.origin === undefined /* only in testing */) {
  3868. var text = changeObj.text.join('\n');
  3869. lastChange.changes.push(text);
  3870. }
  3871. // Change objects may be chained with next.
  3872. changeObj = changeObj.next;
  3873. }
  3874. }
  3875. }
  3876. /**
  3877. * Listens for any kind of cursor activity on CodeMirror.
  3878. * - For tracking cursor activity in insert mode.
  3879. * - Should only be active in insert mode.
  3880. */
  3881. function onCursorActivity() {
  3882. var macroModeState = vimGlobalState.macroModeState;
  3883. if (macroModeState.isPlaying) { return; }
  3884. var lastChange = macroModeState.lastInsertModeChanges;
  3885. if (lastChange.expectCursorActivityForChange) {
  3886. lastChange.expectCursorActivityForChange = false;
  3887. } else {
  3888. // Cursor moved outside the context of an edit. Reset the change.
  3889. lastChange.changes = [];
  3890. }
  3891. }
  3892. /** Wrapper for special keys pressed in insert mode */
  3893. function InsertModeKey(keyName) {
  3894. this.keyName = keyName;
  3895. }
  3896. /**
  3897. * Handles raw key down events from the text area.
  3898. * - Should only be active in insert mode.
  3899. * - For recording deletes in insert mode.
  3900. */
  3901. function onKeyEventTargetKeyDown(e) {
  3902. var macroModeState = vimGlobalState.macroModeState;
  3903. var lastChange = macroModeState.lastInsertModeChanges;
  3904. var keyName = CodeMirror.keyName(e);
  3905. function onKeyFound() {
  3906. lastChange.changes.push(new InsertModeKey(keyName));
  3907. return true;
  3908. }
  3909. if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
  3910. CodeMirror.lookupKey(keyName, ['vim-insert'], onKeyFound);
  3911. }
  3912. }
  3913. /**
  3914. * Repeats the last edit, which includes exactly 1 command and at most 1
  3915. * insert. Operator and motion commands are read from lastEditInputState,
  3916. * while action commands are read from lastEditActionCommand.
  3917. *
  3918. * If repeatForInsert is true, then the function was called by
  3919. * exitInsertMode to repeat the insert mode changes the user just made. The
  3920. * corresponding enterInsertMode call was made with a count.
  3921. */
  3922. function repeatLastEdit(cm, vim, repeat, repeatForInsert) {
  3923. var macroModeState = vimGlobalState.macroModeState;
  3924. macroModeState.isPlaying = true;
  3925. var isAction = !!vim.lastEditActionCommand;
  3926. var cachedInputState = vim.inputState;
  3927. function repeatCommand() {
  3928. if (isAction) {
  3929. commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand);
  3930. } else {
  3931. commandDispatcher.evalInput(cm, vim);
  3932. }
  3933. }
  3934. function repeatInsert(repeat) {
  3935. if (macroModeState.lastInsertModeChanges.changes.length > 0) {
  3936. // For some reason, repeat cw in desktop VIM does not repeat
  3937. // insert mode changes. Will conform to that behavior.
  3938. repeat = !vim.lastEditActionCommand ? 1 : repeat;
  3939. var changeObject = macroModeState.lastInsertModeChanges;
  3940. // This isn't strictly necessary, but since lastInsertModeChanges is
  3941. // supposed to be immutable during replay, this helps catch bugs.
  3942. macroModeState.lastInsertModeChanges = {};
  3943. repeatInsertModeChanges(cm, changeObject.changes, repeat);
  3944. macroModeState.lastInsertModeChanges = changeObject;
  3945. }
  3946. }
  3947. vim.inputState = vim.lastEditInputState;
  3948. if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) {
  3949. // o and O repeat have to be interlaced with insert repeats so that the
  3950. // insertions appear on separate lines instead of the last line.
  3951. for (var i = 0; i < repeat; i++) {
  3952. repeatCommand();
  3953. repeatInsert(1);
  3954. }
  3955. } else {
  3956. if (!repeatForInsert) {
  3957. // Hack to get the cursor to end up at the right place. If I is
  3958. // repeated in insert mode repeat, cursor will be 1 insert
  3959. // change set left of where it should be.
  3960. repeatCommand();
  3961. }
  3962. repeatInsert(repeat);
  3963. }
  3964. vim.inputState = cachedInputState;
  3965. if (vim.insertMode && !repeatForInsert) {
  3966. // Don't exit insert mode twice. If repeatForInsert is set, then we
  3967. // were called by an exitInsertMode call lower on the stack.
  3968. exitInsertMode(cm);
  3969. }
  3970. macroModeState.isPlaying = false;
  3971. };
  3972. function repeatInsertModeChanges(cm, changes, repeat) {
  3973. function keyHandler(binding) {
  3974. if (typeof binding == 'string') {
  3975. CodeMirror.commands[binding](cm);
  3976. } else {
  3977. binding(cm);
  3978. }
  3979. return true;
  3980. }
  3981. for (var i = 0; i < repeat; i++) {
  3982. for (var j = 0; j < changes.length; j++) {
  3983. var change = changes[j];
  3984. if (change instanceof InsertModeKey) {
  3985. CodeMirror.lookupKey(change.keyName, ['vim-insert'], keyHandler);
  3986. } else {
  3987. var cur = cm.getCursor();
  3988. cm.replaceRange(change, cur, cur);
  3989. }
  3990. }
  3991. }
  3992. }
  3993. resetVimGlobalState();
  3994. return vimApi;
  3995. };
  3996. // Initialize Vim and make it available as an API.
  3997. CodeMirror.Vim = Vim();
  3998. });