vim.js 120 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308
  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: unamed, -, 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. * Code structure:
  44. * 1. Default keymap
  45. * 2. Variable declarations and short basic helpers
  46. * 3. Instance (External API) implementation
  47. * 4. Internal state tracking objects (input state, counter) implementation
  48. * and instanstiation
  49. * 5. Key handler (the main command dispatcher) implementation
  50. * 6. Motion, operator, and action implementations
  51. * 7. Helper functions for the key handler, motions, operators, and actions
  52. * 8. Set up Vim to work as a keymap for CodeMirror.
  53. */
  54. (function() {
  55. 'use strict';
  56. var defaultKeymap = [
  57. // Key to key mapping. This goes first to make it possible to override
  58. // existing mappings.
  59. { keys: ['<Left>'], type: 'keyToKey', toKeys: ['h'] },
  60. { keys: ['<Right>'], type: 'keyToKey', toKeys: ['l'] },
  61. { keys: ['<Up>'], type: 'keyToKey', toKeys: ['k'] },
  62. { keys: ['<Down>'], type: 'keyToKey', toKeys: ['j'] },
  63. { keys: ['<Space>'], type: 'keyToKey', toKeys: ['l'] },
  64. { keys: ['<BS>'], type: 'keyToKey', toKeys: ['h'] },
  65. { keys: ['<C-Space>'], type: 'keyToKey', toKeys: ['W'] },
  66. { keys: ['<C-BS>'], type: 'keyToKey', toKeys: ['B'] },
  67. { keys: ['<S-Space>'], type: 'keyToKey', toKeys: ['w'] },
  68. { keys: ['<S-BS>'], type: 'keyToKey', toKeys: ['b'] },
  69. { keys: ['<C-n>'], type: 'keyToKey', toKeys: ['j'] },
  70. { keys: ['<C-p>'], type: 'keyToKey', toKeys: ['k'] },
  71. { keys: ['C-['], type: 'keyToKey', toKeys: ['<Esc>'] },
  72. { keys: ['<C-c>'], type: 'keyToKey', toKeys: ['<Esc>'] },
  73. { keys: ['s'], type: 'keyToKey', toKeys: ['c', 'l'] },
  74. { keys: ['S'], type: 'keyToKey', toKeys: ['c', 'c'] },
  75. { keys: ['<Home>'], type: 'keyToKey', toKeys: ['0'] },
  76. { keys: ['<End>'], type: 'keyToKey', toKeys: ['$'] },
  77. { keys: ['<PageUp>'], type: 'keyToKey', toKeys: ['<C-b>'] },
  78. { keys: ['<PageDown>'], type: 'keyToKey', toKeys: ['<C-f>'] },
  79. // Motions
  80. { keys: ['H'], type: 'motion',
  81. motion: 'moveToTopLine',
  82. motionArgs: { linewise: true, toJumplist: true }},
  83. { keys: ['M'], type: 'motion',
  84. motion: 'moveToMiddleLine',
  85. motionArgs: { linewise: true, toJumplist: true }},
  86. { keys: ['L'], type: 'motion',
  87. motion: 'moveToBottomLine',
  88. motionArgs: { linewise: true, toJumplist: true }},
  89. { keys: ['h'], type: 'motion',
  90. motion: 'moveByCharacters',
  91. motionArgs: { forward: false }},
  92. { keys: ['l'], type: 'motion',
  93. motion: 'moveByCharacters',
  94. motionArgs: { forward: true }},
  95. { keys: ['j'], type: 'motion',
  96. motion: 'moveByLines',
  97. motionArgs: { forward: true, linewise: true }},
  98. { keys: ['k'], type: 'motion',
  99. motion: 'moveByLines',
  100. motionArgs: { forward: false, linewise: true }},
  101. { keys: ['g','j'], type: 'motion',
  102. motion: 'moveByDisplayLines',
  103. motionArgs: { forward: true }},
  104. { keys: ['g','k'], type: 'motion',
  105. motion: 'moveByDisplayLines',
  106. motionArgs: { forward: false }},
  107. { keys: ['w'], type: 'motion',
  108. motion: 'moveByWords',
  109. motionArgs: { forward: true, wordEnd: false }},
  110. { keys: ['W'], type: 'motion',
  111. motion: 'moveByWords',
  112. motionArgs: { forward: true, wordEnd: false, bigWord: true }},
  113. { keys: ['e'], type: 'motion',
  114. motion: 'moveByWords',
  115. motionArgs: { forward: true, wordEnd: true, inclusive: true }},
  116. { keys: ['E'], type: 'motion',
  117. motion: 'moveByWords',
  118. motionArgs: { forward: true, wordEnd: true, bigWord: true,
  119. inclusive: true }},
  120. { keys: ['b'], type: 'motion',
  121. motion: 'moveByWords',
  122. motionArgs: { forward: false, wordEnd: false }},
  123. { keys: ['B'], type: 'motion',
  124. motion: 'moveByWords',
  125. motionArgs: { forward: false, wordEnd: false, bigWord: true }},
  126. { keys: ['g', 'e'], type: 'motion',
  127. motion: 'moveByWords',
  128. motionArgs: { forward: false, wordEnd: true, inclusive: true }},
  129. { keys: ['g', 'E'], type: 'motion',
  130. motion: 'moveByWords',
  131. motionArgs: { forward: false, wordEnd: true, bigWord: true,
  132. inclusive: true }},
  133. { keys: ['{'], type: 'motion', motion: 'moveByParagraph',
  134. motionArgs: { forward: false, toJumplist: true }},
  135. { keys: ['}'], type: 'motion', motion: 'moveByParagraph',
  136. motionArgs: { forward: true, toJumplist: true }},
  137. { keys: ['<C-f>'], type: 'motion',
  138. motion: 'moveByPage', motionArgs: { forward: true }},
  139. { keys: ['<C-b>'], type: 'motion',
  140. motion: 'moveByPage', motionArgs: { forward: false }},
  141. { keys: ['<C-d>'], type: 'motion',
  142. motion: 'moveByScroll',
  143. motionArgs: { forward: true, explicitRepeat: true }},
  144. { keys: ['<C-u>'], type: 'motion',
  145. motion: 'moveByScroll',
  146. motionArgs: { forward: false, explicitRepeat: true }},
  147. { keys: ['g', 'g'], type: 'motion',
  148. motion: 'moveToLineOrEdgeOfDocument',
  149. motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},
  150. { keys: ['G'], type: 'motion',
  151. motion: 'moveToLineOrEdgeOfDocument',
  152. motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},
  153. { keys: ['0'], type: 'motion', motion: 'moveToStartOfLine' },
  154. { keys: ['^'], type: 'motion',
  155. motion: 'moveToFirstNonWhiteSpaceCharacter' },
  156. { keys: ['+'], type: 'motion',
  157. motion: 'moveByLines',
  158. motionArgs: { forward: true, toFirstChar:true }},
  159. { keys: ['-'], type: 'motion',
  160. motion: 'moveByLines',
  161. motionArgs: { forward: false, toFirstChar:true }},
  162. { keys: ['_'], type: 'motion',
  163. motion: 'moveByLines',
  164. motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},
  165. { keys: ['$'], type: 'motion',
  166. motion: 'moveToEol',
  167. motionArgs: { inclusive: true }},
  168. { keys: ['%'], type: 'motion',
  169. motion: 'moveToMatchedSymbol',
  170. motionArgs: { inclusive: true, toJumplist: true }},
  171. { keys: ['f', 'character'], type: 'motion',
  172. motion: 'moveToCharacter',
  173. motionArgs: { forward: true , inclusive: true }},
  174. { keys: ['F', 'character'], type: 'motion',
  175. motion: 'moveToCharacter',
  176. motionArgs: { forward: false }},
  177. { keys: ['t', 'character'], type: 'motion',
  178. motion: 'moveTillCharacter',
  179. motionArgs: { forward: true, inclusive: true }},
  180. { keys: ['T', 'character'], type: 'motion',
  181. motion: 'moveTillCharacter',
  182. motionArgs: { forward: false }},
  183. { keys: [';'], type: 'motion', motion: 'repeatLastCharacterSearch',
  184. motionArgs: { forward: true }},
  185. { keys: [','], type: 'motion', motion: 'repeatLastCharacterSearch',
  186. motionArgs: { forward: false }},
  187. { keys: ['\'', 'character'], type: 'motion', motion: 'goToMark',
  188. motionArgs: {toJumplist: true}},
  189. { keys: ['`', 'character'], type: 'motion', motion: 'goToMark',
  190. motionArgs: {toJumplist: true}},
  191. { keys: [']', '`',], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
  192. { keys: ['[', '`',], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
  193. { keys: [']', '\''], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
  194. { keys: ['[', '\''], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
  195. { keys: [']', 'character'], type: 'motion',
  196. motion: 'moveToSymbol',
  197. motionArgs: { forward: true, toJumplist: true}},
  198. { keys: ['[', 'character'], type: 'motion',
  199. motion: 'moveToSymbol',
  200. motionArgs: { forward: false, toJumplist: true}},
  201. { keys: ['|'], type: 'motion',
  202. motion: 'moveToColumn',
  203. motionArgs: { }},
  204. // Operators
  205. { keys: ['d'], type: 'operator', operator: 'delete' },
  206. { keys: ['y'], type: 'operator', operator: 'yank' },
  207. { keys: ['c'], type: 'operator', operator: 'change',
  208. operatorArgs: { enterInsertMode: true } },
  209. { keys: ['>'], type: 'operator', operator: 'indent',
  210. operatorArgs: { indentRight: true }},
  211. { keys: ['<'], type: 'operator', operator: 'indent',
  212. operatorArgs: { indentRight: false }},
  213. { keys: ['g', '~'], type: 'operator', operator: 'swapcase' },
  214. { keys: ['n'], type: 'motion', motion: 'findNext',
  215. motionArgs: { forward: true, toJumplist: true }},
  216. { keys: ['N'], type: 'motion', motion: 'findNext',
  217. motionArgs: { forward: false, toJumplist: true }},
  218. // Operator-Motion dual commands
  219. { keys: ['x'], type: 'operatorMotion', operator: 'delete',
  220. motion: 'moveByCharacters', motionArgs: { forward: true },
  221. operatorMotionArgs: { visualLine: false }},
  222. { keys: ['X'], type: 'operatorMotion', operator: 'delete',
  223. motion: 'moveByCharacters', motionArgs: { forward: false },
  224. operatorMotionArgs: { visualLine: true }},
  225. { keys: ['D'], type: 'operatorMotion', operator: 'delete',
  226. motion: 'moveToEol', motionArgs: { inclusive: true },
  227. operatorMotionArgs: { visualLine: true }},
  228. { keys: ['Y'], type: 'operatorMotion', operator: 'yank',
  229. motion: 'moveToEol', motionArgs: { inclusive: true },
  230. operatorMotionArgs: { visualLine: true }},
  231. { keys: ['C'], type: 'operatorMotion',
  232. operator: 'change', operatorArgs: { enterInsertMode: true },
  233. motion: 'moveToEol', motionArgs: { inclusive: true },
  234. operatorMotionArgs: { visualLine: true }},
  235. { keys: ['~'], type: 'operatorMotion', operator: 'swapcase',
  236. motion: 'moveByCharacters', motionArgs: { forward: true }},
  237. // Actions
  238. { keys: ['<C-i>'], type: 'action', action: 'jumpListWalk',
  239. actionArgs: { forward: true }},
  240. { keys: ['<C-o>'], type: 'action', action: 'jumpListWalk',
  241. actionArgs: { forward: false }},
  242. { keys: ['a'], type: 'action', action: 'enterInsertMode',
  243. actionArgs: { insertAt: 'charAfter' }},
  244. { keys: ['A'], type: 'action', action: 'enterInsertMode',
  245. actionArgs: { insertAt: 'eol' }},
  246. { keys: ['i'], type: 'action', action: 'enterInsertMode',
  247. actionArgs: { insertAt: 'inplace' }},
  248. { keys: ['I'], type: 'action', action: 'enterInsertMode',
  249. actionArgs: { insertAt: 'firstNonBlank' }},
  250. { keys: ['o'], type: 'action', action: 'newLineAndEnterInsertMode',
  251. actionArgs: { after: true }},
  252. { keys: ['O'], type: 'action', action: 'newLineAndEnterInsertMode',
  253. actionArgs: { after: false }},
  254. { keys: ['v'], type: 'action', action: 'toggleVisualMode' },
  255. { keys: ['V'], type: 'action', action: 'toggleVisualMode',
  256. actionArgs: { linewise: true }},
  257. { keys: ['J'], type: 'action', action: 'joinLines' },
  258. { keys: ['p'], type: 'action', action: 'paste',
  259. actionArgs: { after: true }},
  260. { keys: ['P'], type: 'action', action: 'paste',
  261. actionArgs: { after: false }},
  262. { keys: ['r', 'character'], type: 'action', action: 'replace' },
  263. { keys: ['@', 'character'], type: 'action', action: 'replayMacro' },
  264. { keys: ['q', 'character'], type: 'action', action: 'enterMacroRecordMode' },
  265. { keys: ['R'], type: 'action', action: 'enterReplaceMode' },
  266. { keys: ['u'], type: 'action', action: 'undo' },
  267. { keys: ['<C-r>'], type: 'action', action: 'redo' },
  268. { keys: ['m', 'character'], type: 'action', action: 'setMark' },
  269. { keys: ['\"', 'character'], type: 'action', action: 'setRegister' },
  270. { keys: ['z', 'z'], type: 'action', action: 'scrollToCursor',
  271. actionArgs: { position: 'center' }},
  272. { keys: ['z', '.'], type: 'action', action: 'scrollToCursor',
  273. actionArgs: { position: 'center' },
  274. motion: 'moveToFirstNonWhiteSpaceCharacter' },
  275. { keys: ['z', 't'], type: 'action', action: 'scrollToCursor',
  276. actionArgs: { position: 'top' }},
  277. { keys: ['z', '<CR>'], type: 'action', action: 'scrollToCursor',
  278. actionArgs: { position: 'top' },
  279. motion: 'moveToFirstNonWhiteSpaceCharacter' },
  280. { keys: ['z', '-'], type: 'action', action: 'scrollToCursor',
  281. actionArgs: { position: 'bottom' }},
  282. { keys: ['z', 'b'], type: 'action', action: 'scrollToCursor',
  283. actionArgs: { position: 'bottom' },
  284. motion: 'moveToFirstNonWhiteSpaceCharacter' },
  285. { keys: ['.'], type: 'action', action: 'repeatLastEdit' },
  286. { keys: ['<C-a>'], type: 'action', action: 'incrementNumberToken',
  287. actionArgs: {increase: true, backtrack: false}},
  288. { keys: ['<C-x>'], type: 'action', action: 'incrementNumberToken',
  289. actionArgs: {increase: false, backtrack: false}},
  290. // Text object motions
  291. { keys: ['a', 'character'], type: 'motion',
  292. motion: 'textObjectManipulation' },
  293. { keys: ['i', 'character'], type: 'motion',
  294. motion: 'textObjectManipulation',
  295. motionArgs: { textObjectInner: true }},
  296. // Search
  297. { keys: ['/'], type: 'search',
  298. searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},
  299. { keys: ['?'], type: 'search',
  300. searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},
  301. { keys: ['*'], type: 'search',
  302. searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},
  303. { keys: ['#'], type: 'search',
  304. searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},
  305. // Ex command
  306. { keys: [':'], type: 'ex' }
  307. ];
  308. var Vim = function() {
  309. var alphabetRegex = /[A-Za-z]/;
  310. var numberRegex = /[\d]/;
  311. var whiteSpaceRegex = /\s/;
  312. var wordRegexp = [(/\w/), (/[^\w\s]/)], bigWordRegexp = [(/\S/)];
  313. function makeKeyRange(start, size) {
  314. var keys = [];
  315. for (var i = start; i < start + size; i++) {
  316. keys.push(String.fromCharCode(i));
  317. }
  318. return keys;
  319. }
  320. var upperCaseAlphabet = makeKeyRange(65, 26);
  321. var lowerCaseAlphabet = makeKeyRange(97, 26);
  322. var numbers = makeKeyRange(48, 10);
  323. var SPECIAL_SYMBOLS = '~`!@#$%^&*()_-+=[{}]\\|/?.,<>:;\"\'';
  324. var specialSymbols = SPECIAL_SYMBOLS.split('');
  325. var specialKeys = ['Left', 'Right', 'Up', 'Down', 'Space', 'Backspace',
  326. 'Esc', 'Home', 'End', 'PageUp', 'PageDown', 'Enter'];
  327. var validMarks = upperCaseAlphabet.concat(lowerCaseAlphabet).concat(
  328. numbers).concat(['<', '>']);
  329. var validRegisters = upperCaseAlphabet.concat(lowerCaseAlphabet).concat(
  330. numbers).concat('-\"'.split(''));
  331. function isAlphabet(k) {
  332. return alphabetRegex.test(k);
  333. }
  334. function isLine(cm, line) {
  335. return line >= cm.firstLine() && line <= cm.lastLine();
  336. }
  337. function isLowerCase(k) {
  338. return (/^[a-z]$/).test(k);
  339. }
  340. function isMatchableSymbol(k) {
  341. return '()[]{}'.indexOf(k) != -1;
  342. }
  343. function isNumber(k) {
  344. return numberRegex.test(k);
  345. }
  346. function isUpperCase(k) {
  347. return (/^[A-Z]$/).test(k);
  348. }
  349. function isAlphanumeric(k) {
  350. return (/^[\w]$/).test(k);
  351. }
  352. function isWhiteSpace(k) {
  353. return whiteSpaceRegex.test(k);
  354. }
  355. function isWhiteSpaceString(k) {
  356. return (/^\s*$/).test(k);
  357. }
  358. function inRangeInclusive(x, start, end) {
  359. return x >= start && x <= end;
  360. }
  361. function inArray(val, arr) {
  362. for (var i = 0; i < arr.length; i++) {
  363. if (arr[i] == val) {
  364. return true;
  365. }
  366. }
  367. return false;
  368. }
  369. var createCircularJumpList = function() {
  370. var size = 100;
  371. var pointer = -1;
  372. var head = 0;
  373. var tail = 0;
  374. var buffer = new Array(size);
  375. function add(cm, oldCur, newCur) {
  376. var current = pointer % size;
  377. var curMark = buffer[current];
  378. function useNextSlot(cursor) {
  379. var next = ++pointer % size;
  380. var trashMark = buffer[next];
  381. if (trashMark) {
  382. trashMark.clear();
  383. }
  384. buffer[next] = cm.setBookmark(cursor);
  385. }
  386. if (curMark) {
  387. var markPos = curMark.find();
  388. // avoid recording redundant cursor position
  389. if (markPos && !cursorEqual(markPos, oldCur)) {
  390. useNextSlot(oldCur);
  391. }
  392. } else {
  393. useNextSlot(oldCur);
  394. }
  395. useNextSlot(newCur);
  396. head = pointer;
  397. tail = pointer - size + 1;
  398. if (tail < 0) {
  399. tail = 0;
  400. }
  401. }
  402. function move(cm, offset) {
  403. pointer += offset;
  404. if (pointer > head) {
  405. pointer = head;
  406. } else if (pointer < tail) {
  407. pointer = tail;
  408. }
  409. var mark = buffer[(size + pointer) % size];
  410. // skip marks that are temporarily removed from text buffer
  411. if (mark && !mark.find()) {
  412. var inc = offset > 0 ? 1 : -1;
  413. var newCur;
  414. var oldCur = cm.getCursor();
  415. do {
  416. pointer += inc;
  417. mark = buffer[(size + pointer) % size];
  418. // skip marks that are the same as current position
  419. if (mark &&
  420. (newCur = mark.find()) &&
  421. !cursorEqual(oldCur, newCur)) {
  422. break;
  423. }
  424. } while (pointer < head && pointer > tail);
  425. }
  426. return mark;
  427. }
  428. return {
  429. cachedCursor: undefined, //used for # and * jumps
  430. add: add,
  431. move: move
  432. };
  433. };
  434. var createMacroState = function() {
  435. return {
  436. macroKeyBuffer: [],
  437. latestRegister: undefined,
  438. enteredMacroMode: undefined,
  439. isMacroPlaying: false,
  440. toggle: function(cm, registerName) {
  441. if (this.enteredMacroMode) { //onExit
  442. this.enteredMacroMode(); // close dialog
  443. this.enteredMacroMode = undefined;
  444. } else { //onEnter
  445. this.latestRegister = registerName;
  446. this.enteredMacroMode = cm.openDialog(
  447. '(recording)['+registerName+']', null, {bottom:true});
  448. }
  449. }
  450. }
  451. }
  452. // Global Vim state. Call getVimGlobalState to get and initialize.
  453. var vimGlobalState;
  454. function getVimGlobalState() {
  455. if (!vimGlobalState) {
  456. vimGlobalState = {
  457. // The current search query.
  458. searchQuery: null,
  459. // Whether we are searching backwards.
  460. searchIsReversed: false,
  461. jumpList: createCircularJumpList(),
  462. macroModeState: createMacroState(),
  463. // Recording latest f, t, F or T motion command.
  464. lastChararacterSearch: {increment:0, forward:true, selectedCharacter:''},
  465. registerController: new RegisterController({})
  466. };
  467. }
  468. return vimGlobalState;
  469. }
  470. function getVimState(cm) {
  471. if (!cm.vimState) {
  472. // Store instance state in the CodeMirror object.
  473. cm.vimState = {
  474. inputState: new InputState(),
  475. // When using jk for navigation, if you move from a longer line to a
  476. // shorter line, the cursor may clip to the end of the shorter line.
  477. // If j is pressed again and cursor goes to the next line, the
  478. // cursor should go back to its horizontal position on the longer
  479. // line if it can. This is to keep track of the horizontal position.
  480. lastHPos: -1,
  481. // Doing the same with screen-position for gj/gk
  482. lastHSPos: -1,
  483. // The last motion command run. Cleared if a non-motion command gets
  484. // executed in between.
  485. lastMotion: null,
  486. marks: {},
  487. visualMode: false,
  488. // If we are in visual line mode. No effect if visualMode is false.
  489. visualLine: false
  490. };
  491. }
  492. return cm.vimState;
  493. }
  494. var vimApi= {
  495. buildKeyMap: function() {
  496. // TODO: Convert keymap into dictionary format for fast lookup.
  497. },
  498. // Testing hook, though it might be useful to expose the register
  499. // controller anyways.
  500. getRegisterController: function() {
  501. return getVimGlobalState().registerController;
  502. },
  503. // Testing hook.
  504. clearVimGlobalState_: function() {
  505. vimGlobalState = null;
  506. },
  507. map: function(lhs, rhs) {
  508. // Add user defined key bindings.
  509. exCommandDispatcher.map(lhs, rhs);
  510. },
  511. defineEx: function(name, prefix, func){
  512. if (name.indexOf(prefix) === 0) {
  513. exCommands[name]=func;
  514. exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'};
  515. }else throw new Error("(Vim.defineEx) \""+prefix+"\" is not a prefix of \""+name+"\", command not registered");
  516. },
  517. // Initializes vim state variable on the CodeMirror object. Should only be
  518. // called lazily by handleKey or for testing.
  519. maybeInitState: function(cm) {
  520. getVimState(cm);
  521. },
  522. // This is the outermost function called by CodeMirror, after keys have
  523. // been mapped to their Vim equivalents.
  524. handleKey: function(cm, key) {
  525. var command;
  526. var vim = getVimState(cm);
  527. var macroModeState = getVimGlobalState().macroModeState;
  528. if (macroModeState.enteredMacroMode) {
  529. if (key == 'q') {
  530. actions.exitMacroRecordMode();
  531. return;
  532. }
  533. logKey(macroModeState, key);
  534. }
  535. if (key == '<Esc>') {
  536. // Clear input state and get back to normal mode.
  537. vim.inputState = new InputState();
  538. if (vim.visualMode) {
  539. exitVisualMode(cm, vim);
  540. }
  541. return;
  542. }
  543. if (vim.visualMode &&
  544. cursorEqual(cm.getCursor('head'), cm.getCursor('anchor'))) {
  545. // The selection was cleared. Exit visual mode.
  546. exitVisualMode(cm, vim);
  547. }
  548. if (!vim.visualMode &&
  549. !cursorEqual(cm.getCursor('head'), cm.getCursor('anchor'))) {
  550. vim.visualMode = true;
  551. vim.visualLine = false;
  552. }
  553. if (key != '0' || (key == '0' && vim.inputState.getRepeat() === 0)) {
  554. // Have to special case 0 since it's both a motion and a number.
  555. command = commandDispatcher.matchCommand(key, defaultKeymap, vim);
  556. }
  557. if (!command) {
  558. if (isNumber(key)) {
  559. // Increment count unless count is 0 and key is 0.
  560. vim.inputState.pushRepeatDigit(key);
  561. }
  562. return;
  563. }
  564. if (command.type == 'keyToKey') {
  565. // TODO: prevent infinite recursion.
  566. for (var i = 0; i < command.toKeys.length; i++) {
  567. this.handleKey(cm, command.toKeys[i]);
  568. }
  569. } else {
  570. commandDispatcher.processCommand(cm, vim, command);
  571. }
  572. }
  573. };
  574. // Represents the current input state.
  575. function InputState() {
  576. this.prefixRepeat = [];
  577. this.motionRepeat = [];
  578. this.operator = null;
  579. this.operatorArgs = null;
  580. this.motion = null;
  581. this.motionArgs = null;
  582. this.keyBuffer = []; // For matching multi-key commands.
  583. this.registerName = null; // Defaults to the unamed register.
  584. }
  585. InputState.prototype.pushRepeatDigit = function(n) {
  586. if (!this.operator) {
  587. this.prefixRepeat = this.prefixRepeat.concat(n);
  588. } else {
  589. this.motionRepeat = this.motionRepeat.concat(n);
  590. }
  591. };
  592. InputState.prototype.getRepeat = function() {
  593. var repeat = 0;
  594. if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) {
  595. repeat = 1;
  596. if (this.prefixRepeat.length > 0) {
  597. repeat *= parseInt(this.prefixRepeat.join(''), 10);
  598. }
  599. if (this.motionRepeat.length > 0) {
  600. repeat *= parseInt(this.motionRepeat.join(''), 10);
  601. }
  602. }
  603. return repeat;
  604. };
  605. /*
  606. * Register stores information about copy and paste registers. Besides
  607. * text, a register must store whether it is linewise (i.e., when it is
  608. * pasted, should it insert itself into a new line, or should the text be
  609. * inserted at the cursor position.)
  610. */
  611. function Register(text, linewise) {
  612. this.clear();
  613. if (text) {
  614. this.set(text, linewise);
  615. }
  616. }
  617. Register.prototype = {
  618. set: function(text, linewise) {
  619. this.text = text;
  620. this.linewise = !!linewise;
  621. },
  622. append: function(text, linewise) {
  623. // if this register has ever been set to linewise, use linewise.
  624. if (linewise || this.linewise) {
  625. this.text += '\n' + text;
  626. this.linewise = true;
  627. } else {
  628. this.text += text;
  629. }
  630. },
  631. clear: function() {
  632. this.text = '';
  633. this.linewise = false;
  634. },
  635. toString: function() { return this.text; }
  636. };
  637. /*
  638. * vim registers allow you to keep many independent copy and paste buffers.
  639. * See http://usevim.com/2012/04/13/registers/ for an introduction.
  640. *
  641. * RegisterController keeps the state of all the registers. An initial
  642. * state may be passed in. The unnamed register '"' will always be
  643. * overridden.
  644. */
  645. function RegisterController(registers) {
  646. this.registers = registers;
  647. this.unamedRegister = registers['\"'] = new Register();
  648. }
  649. RegisterController.prototype = {
  650. pushText: function(registerName, operator, text, linewise) {
  651. // Lowercase and uppercase registers refer to the same register.
  652. // Uppercase just means append.
  653. var register = this.isValidRegister(registerName) ?
  654. this.getRegister(registerName) : null;
  655. // if no register/an invalid register was specified, things go to the
  656. // default registers
  657. if (!register) {
  658. switch (operator) {
  659. case 'yank':
  660. // The 0 register contains the text from the most recent yank.
  661. this.registers['0'] = new Register(text, linewise);
  662. break;
  663. case 'delete':
  664. case 'change':
  665. if (text.indexOf('\n') == -1) {
  666. // Delete less than 1 line. Update the small delete register.
  667. this.registers['-'] = new Register(text, linewise);
  668. } else {
  669. // Shift down the contents of the numbered registers and put the
  670. // deleted text into register 1.
  671. this.shiftNumericRegisters_();
  672. this.registers['1'] = new Register(text, linewise);
  673. }
  674. break;
  675. }
  676. // Make sure the unnamed register is set to what just happened
  677. this.unamedRegister.set(text, linewise);
  678. return;
  679. }
  680. // If we've gotten to this point, we've actually specified a register
  681. var append = isUpperCase(registerName);
  682. if (append) {
  683. register.append(text, linewise);
  684. // The unamed register always has the same value as the last used
  685. // register.
  686. this.unamedRegister.append(text, linewise);
  687. } else {
  688. register.set(text, linewise);
  689. this.unamedRegister.set(text, linewise);
  690. }
  691. },
  692. setRegisterText: function(name, text, linewise) {
  693. this.getRegister(name).set(text, linewise);
  694. },
  695. // Gets the register named @name. If one of @name doesn't already exist,
  696. // create it. If @name is invalid, return the unamedRegister.
  697. getRegister: function(name) {
  698. if (!this.isValidRegister(name)) {
  699. return this.unamedRegister;
  700. }
  701. name = name.toLowerCase();
  702. if (!this.registers[name]) {
  703. this.registers[name] = new Register();
  704. }
  705. return this.registers[name];
  706. },
  707. isValidRegister: function(name) {
  708. return name && inArray(name, validRegisters);
  709. },
  710. shiftNumericRegisters_: function() {
  711. for (var i = 9; i >= 2; i--) {
  712. this.registers[i] = this.getRegister('' + (i - 1));
  713. }
  714. }
  715. };
  716. var commandDispatcher = {
  717. matchCommand: function(key, keyMap, vim) {
  718. var inputState = vim.inputState;
  719. var keys = inputState.keyBuffer.concat(key);
  720. for (var i = 0; i < keyMap.length; i++) {
  721. var command = keyMap[i];
  722. if (matchKeysPartial(keys, command.keys)) {
  723. if (keys.length < command.keys.length) {
  724. // Matches part of a multi-key command. Buffer and wait for next
  725. // stroke.
  726. inputState.keyBuffer.push(key);
  727. return null;
  728. } else {
  729. if (inputState.operator && command.type == 'action') {
  730. // Ignore matched action commands after an operator. Operators
  731. // only operate on motions. This check is really for text
  732. // objects since aW, a[ etcs conflicts with a.
  733. continue;
  734. }
  735. // Matches whole comand. Return the command.
  736. if (command.keys[keys.length - 1] == 'character') {
  737. inputState.selectedCharacter = keys[keys.length - 1];
  738. if(inputState.selectedCharacter.length>1){
  739. switch(inputState.selectedCharacter){
  740. case "<CR>":
  741. inputState.selectedCharacter='\n';
  742. break;
  743. case "<Space>":
  744. inputState.selectedCharacter=' ';
  745. break;
  746. default:
  747. continue;
  748. }
  749. }
  750. }
  751. inputState.keyBuffer = [];
  752. return command;
  753. }
  754. }
  755. }
  756. // Clear the buffer since there are no partial matches.
  757. inputState.keyBuffer = [];
  758. return null;
  759. },
  760. processCommand: function(cm, vim, command) {
  761. vim.inputState.repeatOverride = command.repeatOverride;
  762. switch (command.type) {
  763. case 'motion':
  764. this.processMotion(cm, vim, command);
  765. break;
  766. case 'operator':
  767. this.processOperator(cm, vim, command);
  768. break;
  769. case 'operatorMotion':
  770. this.processOperatorMotion(cm, vim, command);
  771. break;
  772. case 'action':
  773. this.processAction(cm, vim, command);
  774. break;
  775. case 'search':
  776. this.processSearch(cm, vim, command);
  777. break;
  778. case 'ex':
  779. case 'keyToEx':
  780. this.processEx(cm, vim, command);
  781. break;
  782. default:
  783. break;
  784. }
  785. },
  786. processMotion: function(cm, vim, command) {
  787. vim.inputState.motion = command.motion;
  788. vim.inputState.motionArgs = copyArgs(command.motionArgs);
  789. this.evalInput(cm, vim);
  790. },
  791. processOperator: function(cm, vim, command) {
  792. var inputState = vim.inputState;
  793. if (inputState.operator) {
  794. if (inputState.operator == command.operator) {
  795. // Typing an operator twice like 'dd' makes the operator operate
  796. // linewise
  797. inputState.motion = 'expandToLine';
  798. inputState.motionArgs = { linewise: true };
  799. this.evalInput(cm, vim);
  800. return;
  801. } else {
  802. // 2 different operators in a row doesn't make sense.
  803. vim.inputState = new InputState();
  804. }
  805. }
  806. inputState.operator = command.operator;
  807. inputState.operatorArgs = copyArgs(command.operatorArgs);
  808. if (vim.visualMode) {
  809. // Operating on a selection in visual mode. We don't need a motion.
  810. this.evalInput(cm, vim);
  811. }
  812. },
  813. processOperatorMotion: function(cm, vim, command) {
  814. var visualMode = vim.visualMode;
  815. var operatorMotionArgs = copyArgs(command.operatorMotionArgs);
  816. if (operatorMotionArgs) {
  817. // Operator motions may have special behavior in visual mode.
  818. if (visualMode && operatorMotionArgs.visualLine) {
  819. vim.visualLine = true;
  820. }
  821. }
  822. this.processOperator(cm, vim, command);
  823. if (!visualMode) {
  824. this.processMotion(cm, vim, command);
  825. }
  826. },
  827. processAction: function(cm, vim, command) {
  828. var inputState = vim.inputState;
  829. var repeat = inputState.getRepeat();
  830. var repeatIsExplicit = !!repeat;
  831. var actionArgs = copyArgs(command.actionArgs) || {};
  832. if (inputState.selectedCharacter) {
  833. actionArgs.selectedCharacter = inputState.selectedCharacter;
  834. }
  835. // Actions may or may not have motions and operators. Do these first.
  836. if (command.operator) {
  837. this.processOperator(cm, vim, command);
  838. }
  839. if (command.motion) {
  840. this.processMotion(cm, vim, command);
  841. }
  842. if (command.motion || command.operator) {
  843. this.evalInput(cm, vim);
  844. }
  845. actionArgs.repeat = repeat || 1;
  846. actionArgs.repeatIsExplicit = repeatIsExplicit;
  847. actionArgs.registerName = inputState.registerName;
  848. vim.inputState = new InputState();
  849. vim.lastMotion = null,
  850. actions[command.action](cm, actionArgs, vim);
  851. },
  852. processSearch: function(cm, vim, command) {
  853. if (!cm.getSearchCursor) {
  854. // Search depends on SearchCursor.
  855. return;
  856. }
  857. var forward = command.searchArgs.forward;
  858. getSearchState(cm).setReversed(!forward);
  859. var promptPrefix = (forward) ? '/' : '?';
  860. var originalQuery = getSearchState(cm).getQuery();
  861. var originalScrollPos = cm.getScrollInfo();
  862. function handleQuery(query, ignoreCase, smartCase) {
  863. try {
  864. updateSearchQuery(cm, query, ignoreCase, smartCase);
  865. } catch (e) {
  866. showConfirm(cm, 'Invalid regex: ' + query);
  867. return;
  868. }
  869. commandDispatcher.processMotion(cm, vim, {
  870. type: 'motion',
  871. motion: 'findNext',
  872. motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist }
  873. });
  874. }
  875. function onPromptClose(query) {
  876. cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
  877. handleQuery(query, true /** ignoreCase */, true /** smartCase */);
  878. }
  879. function onPromptKeyUp(e, query) {
  880. var parsedQuery;
  881. try {
  882. parsedQuery = updateSearchQuery(cm, query,
  883. true /** ignoreCase */, true /** smartCase */)
  884. } catch (e) {
  885. // Swallow bad regexes for incremental search.
  886. }
  887. if (parsedQuery) {
  888. cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30);
  889. } else {
  890. clearSearchHighlight(cm);
  891. cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
  892. }
  893. }
  894. function onPromptKeyDown(e, query, close) {
  895. var keyName = CodeMirror.keyName(e);
  896. if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[') {
  897. updateSearchQuery(cm, originalQuery);
  898. clearSearchHighlight(cm);
  899. cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
  900. CodeMirror.e_stop(e);
  901. close();
  902. cm.focus();
  903. }
  904. }
  905. switch (command.searchArgs.querySrc) {
  906. case 'prompt':
  907. showPrompt(cm, {
  908. onClose: onPromptClose,
  909. prefix: promptPrefix,
  910. desc: searchPromptDesc,
  911. onKeyUp: onPromptKeyUp,
  912. onKeyDown: onPromptKeyDown
  913. });
  914. break;
  915. case 'wordUnderCursor':
  916. var word = expandWordUnderCursor(cm, false /** inclusive */,
  917. true /** forward */, false /** bigWord */,
  918. true /** noSymbol */);
  919. var isKeyword = true;
  920. if (!word) {
  921. word = expandWordUnderCursor(cm, false /** inclusive */,
  922. true /** forward */, false /** bigWord */,
  923. false /** noSymbol */);
  924. isKeyword = false;
  925. }
  926. if (!word) {
  927. return;
  928. }
  929. var query = cm.getLine(word.start.line).substring(word.start.ch,
  930. word.end.ch);
  931. if (isKeyword) {
  932. query = '\\b' + query + '\\b';
  933. } else {
  934. query = escapeRegex(query);
  935. }
  936. // cachedCursor is used to save the old position of the cursor
  937. // when * or # causes vim to seek for the nearest word and shift
  938. // the cursor before entering the motion.
  939. getVimGlobalState().jumpList.cachedCursor = cm.getCursor();
  940. cm.setCursor(word.start);
  941. handleQuery(query, true /** ignoreCase */, false /** smartCase */);
  942. break;
  943. }
  944. },
  945. processEx: function(cm, vim, command) {
  946. function onPromptClose(input) {
  947. exCommandDispatcher.processCommand(cm, input);
  948. }
  949. function onPromptKeyDown(e, input, close) {
  950. var keyName = CodeMirror.keyName(e);
  951. if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[') {
  952. CodeMirror.e_stop(e);
  953. close();
  954. cm.focus();
  955. }
  956. }
  957. if (command.type == 'keyToEx') {
  958. // Handle user defined Ex to Ex mappings
  959. exCommandDispatcher.processCommand(cm, command.exArgs.input);
  960. } else {
  961. if (vim.visualMode) {
  962. showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>',
  963. onKeyDown: onPromptKeyDown});
  964. } else {
  965. showPrompt(cm, { onClose: onPromptClose, prefix: ':',
  966. onKeyDown: onPromptKeyDown});
  967. }
  968. }
  969. },
  970. evalInput: function(cm, vim) {
  971. // If the motion comand is set, execute both the operator and motion.
  972. // Otherwise return.
  973. var inputState = vim.inputState;
  974. var motion = inputState.motion;
  975. var motionArgs = inputState.motionArgs || {};
  976. var operator = inputState.operator;
  977. var operatorArgs = inputState.operatorArgs || {};
  978. var registerName = inputState.registerName;
  979. var selectionEnd = cm.getCursor('head');
  980. var selectionStart = cm.getCursor('anchor');
  981. // The difference between cur and selection cursors are that cur is
  982. // being operated on and ignores that there is a selection.
  983. var curStart = copyCursor(selectionEnd);
  984. var curOriginal = copyCursor(curStart);
  985. var curEnd;
  986. var repeat;
  987. if (operator) {
  988. this.recordLastEdit(cm, vim, inputState);
  989. }
  990. if (inputState.repeatOverride !== undefined) {
  991. // If repeatOverride is specified, that takes precedence over the
  992. // input state's repeat. Used by Ex mode and can be user defined.
  993. repeat = inputState.repeatOverride;
  994. } else {
  995. repeat = inputState.getRepeat();
  996. }
  997. if (repeat > 0 && motionArgs.explicitRepeat) {
  998. motionArgs.repeatIsExplicit = true;
  999. } else if (motionArgs.noRepeat ||
  1000. (!motionArgs.explicitRepeat && repeat === 0)) {
  1001. repeat = 1;
  1002. motionArgs.repeatIsExplicit = false;
  1003. }
  1004. if (inputState.selectedCharacter) {
  1005. // If there is a character input, stick it in all of the arg arrays.
  1006. motionArgs.selectedCharacter = operatorArgs.selectedCharacter =
  1007. inputState.selectedCharacter;
  1008. }
  1009. motionArgs.repeat = repeat;
  1010. vim.inputState = new InputState();
  1011. if (motion) {
  1012. var motionResult = motions[motion](cm, motionArgs, vim);
  1013. vim.lastMotion = motions[motion];
  1014. if (!motionResult) {
  1015. return;
  1016. }
  1017. if (motionArgs.toJumplist) {
  1018. var jumpList = getVimGlobalState().jumpList;
  1019. // if the current motion is # or *, use cachedCursor
  1020. var cachedCursor = jumpList.cachedCursor;
  1021. if (cachedCursor) {
  1022. recordJumpPosition(cm, cachedCursor, motionResult);
  1023. delete jumpList.cachedCursor;
  1024. } else {
  1025. recordJumpPosition(cm, curOriginal, motionResult);
  1026. }
  1027. }
  1028. if (motionResult instanceof Array) {
  1029. curStart = motionResult[0];
  1030. curEnd = motionResult[1];
  1031. } else {
  1032. curEnd = motionResult;
  1033. }
  1034. // TODO: Handle null returns from motion commands better.
  1035. if (!curEnd) {
  1036. curEnd = { ch: curStart.ch, line: curStart.line };
  1037. }
  1038. if (vim.visualMode) {
  1039. // Check if the selection crossed over itself. Will need to shift
  1040. // the start point if that happened.
  1041. if (cursorIsBefore(selectionStart, selectionEnd) &&
  1042. (cursorEqual(selectionStart, curEnd) ||
  1043. cursorIsBefore(curEnd, selectionStart))) {
  1044. // The end of the selection has moved from after the start to
  1045. // before the start. We will shift the start right by 1.
  1046. selectionStart.ch += 1;
  1047. } else if (cursorIsBefore(selectionEnd, selectionStart) &&
  1048. (cursorEqual(selectionStart, curEnd) ||
  1049. cursorIsBefore(selectionStart, curEnd))) {
  1050. // The opposite happened. We will shift the start left by 1.
  1051. selectionStart.ch -= 1;
  1052. }
  1053. selectionEnd = curEnd;
  1054. if (vim.visualLine) {
  1055. if (cursorIsBefore(selectionStart, selectionEnd)) {
  1056. selectionStart.ch = 0;
  1057. selectionEnd.ch = lineLength(cm, selectionEnd.line);
  1058. } else {
  1059. selectionEnd.ch = 0;
  1060. selectionStart.ch = lineLength(cm, selectionStart.line);
  1061. }
  1062. }
  1063. cm.setSelection(selectionStart, selectionEnd);
  1064. updateMark(cm, vim, '<',
  1065. cursorIsBefore(selectionStart, selectionEnd) ? selectionStart
  1066. : selectionEnd);
  1067. updateMark(cm, vim, '>',
  1068. cursorIsBefore(selectionStart, selectionEnd) ? selectionEnd
  1069. : selectionStart);
  1070. } else if (!operator) {
  1071. curEnd = clipCursorToContent(cm, curEnd);
  1072. cm.setCursor(curEnd.line, curEnd.ch);
  1073. }
  1074. }
  1075. if (operator) {
  1076. var inverted = false;
  1077. vim.lastMotion = null;
  1078. operatorArgs.repeat = repeat; // Indent in visual mode needs this.
  1079. if (vim.visualMode) {
  1080. curStart = selectionStart;
  1081. curEnd = selectionEnd;
  1082. motionArgs.inclusive = true;
  1083. }
  1084. // Swap start and end if motion was backward.
  1085. if (cursorIsBefore(curEnd, curStart)) {
  1086. var tmp = curStart;
  1087. curStart = curEnd;
  1088. curEnd = tmp;
  1089. inverted = true;
  1090. }
  1091. if (motionArgs.inclusive && !(vim.visualMode && inverted)) {
  1092. // Move the selection end one to the right to include the last
  1093. // character.
  1094. curEnd.ch++;
  1095. }
  1096. var linewise = motionArgs.linewise ||
  1097. (vim.visualMode && vim.visualLine);
  1098. if (linewise) {
  1099. // Expand selection to entire line.
  1100. expandSelectionToLine(cm, curStart, curEnd);
  1101. } else if (motionArgs.forward) {
  1102. // Clip to trailing newlines only if the motion goes forward.
  1103. clipToLine(cm, curStart, curEnd);
  1104. }
  1105. operatorArgs.registerName = registerName;
  1106. // Keep track of linewise as it affects how paste and change behave.
  1107. operatorArgs.linewise = linewise;
  1108. operators[operator](cm, operatorArgs, vim, curStart,
  1109. curEnd, curOriginal);
  1110. if (vim.visualMode) {
  1111. exitVisualMode(cm, vim);
  1112. }
  1113. if (operatorArgs.enterInsertMode) {
  1114. actions.enterInsertMode(cm);
  1115. }
  1116. }
  1117. },
  1118. recordLastEdit: function(cm, vim, inputState) {
  1119. vim.lastEdit = inputState;
  1120. }
  1121. };
  1122. /**
  1123. * typedef {Object{line:number,ch:number}} Cursor An object containing the
  1124. * position of the cursor.
  1125. */
  1126. // All of the functions below return Cursor objects.
  1127. var motions = {
  1128. moveToTopLine: function(cm, motionArgs) {
  1129. var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;
  1130. return { line: line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(line)) };
  1131. },
  1132. moveToMiddleLine: function(cm) {
  1133. var range = getUserVisibleLines(cm);
  1134. var line = Math.floor((range.top + range.bottom) * 0.5);
  1135. return { line: line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(line)) };
  1136. },
  1137. moveToBottomLine: function(cm, motionArgs) {
  1138. var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;
  1139. return { line: line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(line)) };
  1140. },
  1141. expandToLine: function(cm, motionArgs) {
  1142. // Expands forward to end of line, and then to next line if repeat is
  1143. // >1. Does not handle backward motion!
  1144. var cur = cm.getCursor();
  1145. return { line: cur.line + motionArgs.repeat - 1, ch: Infinity };
  1146. },
  1147. findNext: function(cm, motionArgs, vim) {
  1148. var state = getSearchState(cm);
  1149. var query = state.getQuery();
  1150. if (!query) {
  1151. return;
  1152. }
  1153. var prev = !motionArgs.forward;
  1154. // If search is initiated with ? instead of /, negate direction.
  1155. prev = (state.isReversed()) ? !prev : prev;
  1156. highlightSearchMatches(cm, query);
  1157. return findNext(cm, prev/** prev */, query, motionArgs.repeat);
  1158. },
  1159. goToMark: function(cm, motionArgs, vim) {
  1160. var mark = vim.marks[motionArgs.selectedCharacter];
  1161. if (mark) {
  1162. return mark.find();
  1163. }
  1164. return null;
  1165. },
  1166. jumpToMark: function(cm, motionArgs, vim) {
  1167. var best = cm.getCursor();
  1168. for (var i = 0; i < motionArgs.repeat; i++) {
  1169. var cursor = best;
  1170. for (var key in vim.marks) {
  1171. if (!isLowerCase(key)) {
  1172. continue;
  1173. }
  1174. var mark = vim.marks[key].find();
  1175. var isWrongDirection = (motionArgs.forward) ?
  1176. cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark)
  1177. if (isWrongDirection) {
  1178. continue;
  1179. }
  1180. if (motionArgs.linewise && (mark.line == cursor.line)) {
  1181. continue;
  1182. }
  1183. var equal = cursorEqual(cursor, best);
  1184. var between = (motionArgs.forward) ?
  1185. cusrorIsBetween(cursor, mark, best) :
  1186. cusrorIsBetween(best, mark, cursor);
  1187. if (equal || between) {
  1188. best = mark;
  1189. }
  1190. }
  1191. }
  1192. if (motionArgs.linewise) {
  1193. // Vim places the cursor on the first non-whitespace character of
  1194. // the line if there is one, else it places the cursor at the end
  1195. // of the line, regardless of whether a mark was found.
  1196. best.ch = findFirstNonWhiteSpaceCharacter(cm.getLine(best.line));
  1197. }
  1198. return best;
  1199. },
  1200. moveByCharacters: function(cm, motionArgs) {
  1201. var cur = cm.getCursor();
  1202. var repeat = motionArgs.repeat;
  1203. var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;
  1204. return { line: cur.line, ch: ch };
  1205. },
  1206. moveByLines: function(cm, motionArgs, vim) {
  1207. var cur = cm.getCursor();
  1208. var endCh = cur.ch;
  1209. // Depending what our last motion was, we may want to do different
  1210. // things. If our last motion was moving vertically, we want to
  1211. // preserve the HPos from our last horizontal move. If our last motion
  1212. // was going to the end of a line, moving vertically we should go to
  1213. // the end of the line, etc.
  1214. switch (vim.lastMotion) {
  1215. case this.moveByLines:
  1216. case this.moveByDisplayLines:
  1217. case this.moveByScroll:
  1218. case this.moveToColumn:
  1219. case this.moveToEol:
  1220. endCh = vim.lastHPos;
  1221. break;
  1222. default:
  1223. vim.lastHPos = endCh;
  1224. }
  1225. var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0);
  1226. var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat;
  1227. if (line < cm.firstLine() || line > cm.lastLine() ) {
  1228. return null;
  1229. }
  1230. if(motionArgs.toFirstChar){
  1231. endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));
  1232. vim.lastHPos = endCh;
  1233. }
  1234. vim.lastHSPos = cm.charCoords({line:line, ch:endCh},"div").left;
  1235. return { line: line, ch: endCh };
  1236. },
  1237. moveByDisplayLines: function(cm, motionArgs, vim) {
  1238. var cur = cm.getCursor();
  1239. switch (vim.lastMotion) {
  1240. case this.moveByDisplayLines:
  1241. case this.moveByScroll:
  1242. case this.moveByLines:
  1243. case this.moveToColumn:
  1244. case this.moveToEol:
  1245. break;
  1246. default:
  1247. vim.lastHSPos = cm.charCoords(cur,"div").left;
  1248. }
  1249. var repeat = motionArgs.repeat;
  1250. var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),"line",vim.lastHSPos);
  1251. if (res.hitSide) {
  1252. if (motionArgs.forward) {
  1253. var lastCharCoords = cm.charCoords(res, 'div');
  1254. var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos };
  1255. var res = cm.coordsChar(goalCoords, 'div');
  1256. } else {
  1257. var resCoords = cm.charCoords({ line: cm.firstLine(), ch: 0}, 'div');
  1258. resCoords.left = vim.lastHSPos;
  1259. res = cm.coordsChar(resCoords, 'div');
  1260. }
  1261. }
  1262. vim.lastHPos = res.ch;
  1263. return res;
  1264. },
  1265. moveByPage: function(cm, motionArgs) {
  1266. // CodeMirror only exposes functions that move the cursor page down, so
  1267. // doing this bad hack to move the cursor and move it back. evalInput
  1268. // will move the cursor to where it should be in the end.
  1269. var curStart = cm.getCursor();
  1270. var repeat = motionArgs.repeat;
  1271. cm.moveV((motionArgs.forward ? repeat : -repeat), 'page');
  1272. var curEnd = cm.getCursor();
  1273. cm.setCursor(curStart);
  1274. return curEnd;
  1275. },
  1276. moveByParagraph: function(cm, motionArgs) {
  1277. var line = cm.getCursor().line;
  1278. var repeat = motionArgs.repeat;
  1279. var inc = motionArgs.forward ? 1 : -1;
  1280. for (var i = 0; i < repeat; i++) {
  1281. if ((!motionArgs.forward && line === cm.firstLine() ) ||
  1282. (motionArgs.forward && line == cm.lastLine())) {
  1283. break;
  1284. }
  1285. line += inc;
  1286. while (line !== cm.firstLine() && line != cm.lastLine() && cm.getLine(line)) {
  1287. line += inc;
  1288. }
  1289. }
  1290. return { line: line, ch: 0 };
  1291. },
  1292. moveByScroll: function(cm, motionArgs, vim) {
  1293. var globalState = getVimGlobalState();
  1294. var scrollbox = cm.getScrollInfo();
  1295. var curEnd = null;
  1296. var repeat = motionArgs.repeat;
  1297. if (!repeat) {
  1298. repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
  1299. }
  1300. var orig = cm.charCoords(cm.getCursor(), 'local');
  1301. motionArgs.repeat = repeat;
  1302. var curEnd = motions.moveByDisplayLines(cm, motionArgs, vim);
  1303. if (!curEnd) {
  1304. return null;
  1305. }
  1306. var dest = cm.charCoords(curEnd, 'local');
  1307. cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
  1308. return curEnd;
  1309. },
  1310. moveByWords: function(cm, motionArgs) {
  1311. return moveToWord(cm, motionArgs.repeat, !!motionArgs.forward,
  1312. !!motionArgs.wordEnd, !!motionArgs.bigWord);
  1313. },
  1314. moveTillCharacter: function(cm, motionArgs) {
  1315. var repeat = motionArgs.repeat;
  1316. var curEnd = moveToCharacter(cm, repeat, motionArgs.forward,
  1317. motionArgs.selectedCharacter);
  1318. var increment = motionArgs.forward ? -1 : 1;
  1319. recordLastCharacterSearch(increment, motionArgs);
  1320. if(!curEnd)return cm.getCursor();
  1321. curEnd.ch += increment;
  1322. return curEnd;
  1323. },
  1324. moveToCharacter: function(cm, motionArgs) {
  1325. var repeat = motionArgs.repeat;
  1326. recordLastCharacterSearch(0, motionArgs);
  1327. return moveToCharacter(cm, repeat, motionArgs.forward,
  1328. motionArgs.selectedCharacter) || cm.getCursor();
  1329. },
  1330. moveToSymbol: function(cm, motionArgs) {
  1331. var repeat = motionArgs.repeat;
  1332. return findSymbol(cm, repeat, motionArgs.forward,
  1333. motionArgs.selectedCharacter) || cm.getCursor();
  1334. },
  1335. moveToColumn: function(cm, motionArgs, vim) {
  1336. var repeat = motionArgs.repeat;
  1337. // repeat is equivalent to which column we want to move to!
  1338. vim.lastHPos = repeat - 1;
  1339. vim.lastHSPos = cm.charCoords(cm.getCursor(),"div").left;
  1340. return moveToColumn(cm, repeat);
  1341. },
  1342. moveToEol: function(cm, motionArgs, vim) {
  1343. var cur = cm.getCursor();
  1344. vim.lastHPos = Infinity;
  1345. var retval={ line: cur.line + motionArgs.repeat - 1, ch: Infinity }
  1346. var end=cm.clipPos(retval);
  1347. end.ch--;
  1348. vim.lastHSPos = cm.charCoords(end,"div").left;
  1349. return retval;
  1350. },
  1351. moveToFirstNonWhiteSpaceCharacter: function(cm) {
  1352. // Go to the start of the line where the text begins, or the end for
  1353. // whitespace-only lines
  1354. var cursor = cm.getCursor();
  1355. return { line: cursor.line,
  1356. ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)) };
  1357. },
  1358. moveToMatchedSymbol: function(cm, motionArgs) {
  1359. var cursor = cm.getCursor();
  1360. var line = cursor.line;
  1361. var ch = cursor.ch;
  1362. var lineText = cm.getLine(line);
  1363. var symbol;
  1364. var startContext = cm.getTokenAt(cursor).type;
  1365. var startCtxLevel = getContextLevel(startContext);
  1366. do {
  1367. symbol = lineText.charAt(ch++);
  1368. if (symbol && isMatchableSymbol(symbol)) {
  1369. var endContext = cm.getTokenAt({line:line, ch:ch}).type;
  1370. var endCtxLevel = getContextLevel(endContext);
  1371. if (startCtxLevel >= endCtxLevel) {
  1372. break;
  1373. }
  1374. }
  1375. } while (symbol);
  1376. if (symbol) {
  1377. return findMatchedSymbol(cm, {line:line, ch:ch-1}, symbol);
  1378. } else {
  1379. return cursor;
  1380. }
  1381. },
  1382. moveToStartOfLine: function(cm) {
  1383. var cursor = cm.getCursor();
  1384. return { line: cursor.line, ch: 0 };
  1385. },
  1386. moveToLineOrEdgeOfDocument: function(cm, motionArgs) {
  1387. var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine();
  1388. if (motionArgs.repeatIsExplicit) {
  1389. lineNum = motionArgs.repeat - cm.getOption('firstLineNumber');
  1390. }
  1391. return { line: lineNum,
  1392. ch: findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)) };
  1393. },
  1394. textObjectManipulation: function(cm, motionArgs) {
  1395. var character = motionArgs.selectedCharacter;
  1396. // Inclusive is the difference between a and i
  1397. // TODO: Instead of using the additional text object map to perform text
  1398. // object operations, merge the map into the defaultKeyMap and use
  1399. // motionArgs to define behavior. Define separate entries for 'aw',
  1400. // 'iw', 'a[', 'i[', etc.
  1401. var inclusive = !motionArgs.textObjectInner;
  1402. if (!textObjects[character]) {
  1403. // No text object defined for this, don't move.
  1404. return null;
  1405. }
  1406. var tmp = textObjects[character](cm, inclusive);
  1407. var start = tmp.start;
  1408. var end = tmp.end;
  1409. return [start, end];
  1410. },
  1411. repeatLastCharacterSearch: function(cm, motionArgs) {
  1412. var lastSearch = getVimGlobalState().lastChararacterSearch;
  1413. var repeat = motionArgs.repeat;
  1414. var forward = motionArgs.forward === lastSearch.forward;
  1415. var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1);
  1416. cm.moveH(-increment, 'char');
  1417. motionArgs.inclusive = forward ? true : false;
  1418. var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);
  1419. if (!curEnd) {
  1420. cm.moveH(increment, 'char')
  1421. return cm.getCursor();
  1422. }
  1423. curEnd.ch += increment;
  1424. return curEnd;
  1425. }
  1426. };
  1427. var operators = {
  1428. change: function(cm, operatorArgs, vim, curStart, curEnd) {
  1429. getVimGlobalState().registerController.pushText(
  1430. operatorArgs.registerName, 'change', cm.getRange(curStart, curEnd),
  1431. operatorArgs.linewise);
  1432. if (operatorArgs.linewise) {
  1433. // Delete starting at the first nonwhitespace character of the first
  1434. // line, instead of from the start of the first line. This way we get
  1435. // an indent when we get into insert mode. This behavior isn't quite
  1436. // correct because we should treat this as a completely new line, and
  1437. // indent should be whatever codemirror thinks is the right indent.
  1438. // But cm.indentLine doesn't seem work on empty lines.
  1439. // TODO: Fix the above.
  1440. curStart.ch =
  1441. findFirstNonWhiteSpaceCharacter(cm.getLine(curStart.line));
  1442. // Insert an additional newline so that insert mode can start there.
  1443. // curEnd should be on the first character of the new line.
  1444. cm.replaceRange('\n', curStart, curEnd);
  1445. } else {
  1446. cm.replaceRange('', curStart, curEnd);
  1447. }
  1448. cm.setCursor(curStart);
  1449. },
  1450. // delete is a javascript keyword.
  1451. 'delete': function(cm, operatorArgs, vim, curStart, curEnd) {
  1452. getVimGlobalState().registerController.pushText(
  1453. operatorArgs.registerName, 'delete', cm.getRange(curStart, curEnd),
  1454. operatorArgs.linewise);
  1455. cm.replaceRange('', curStart, curEnd);
  1456. if (operatorArgs.linewise) {
  1457. cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
  1458. } else {
  1459. cm.setCursor(curStart);
  1460. }
  1461. },
  1462. indent: function(cm, operatorArgs, vim, curStart, curEnd) {
  1463. var startLine = curStart.line;
  1464. var endLine = curEnd.line;
  1465. // In visual mode, n> shifts the selection right n times, instead of
  1466. // shifting n lines right once.
  1467. var repeat = (vim.visualMode) ? operatorArgs.repeat : 1;
  1468. if (operatorArgs.linewise) {
  1469. // The only way to delete a newline is to delete until the start of
  1470. // the next line, so in linewise mode evalInput will include the next
  1471. // line. We don't want this in indent, so we go back a line.
  1472. endLine--;
  1473. }
  1474. for (var i = startLine; i <= endLine; i++) {
  1475. for (var j = 0; j < repeat; j++) {
  1476. cm.indentLine(i, operatorArgs.indentRight);
  1477. }
  1478. }
  1479. cm.setCursor(curStart);
  1480. cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
  1481. },
  1482. swapcase: function(cm, operatorArgs, vim, curStart, curEnd, curOriginal) {
  1483. var toSwap = cm.getRange(curStart, curEnd);
  1484. var swapped = '';
  1485. for (var i = 0; i < toSwap.length; i++) {
  1486. var character = toSwap.charAt(i);
  1487. swapped += isUpperCase(character) ? character.toLowerCase() :
  1488. character.toUpperCase();
  1489. }
  1490. cm.replaceRange(swapped, curStart, curEnd);
  1491. cm.setCursor(curOriginal);
  1492. },
  1493. yank: function(cm, operatorArgs, vim, curStart, curEnd, curOriginal) {
  1494. getVimGlobalState().registerController.pushText(
  1495. operatorArgs.registerName, 'yank',
  1496. cm.getRange(curStart, curEnd), operatorArgs.linewise);
  1497. cm.setCursor(curOriginal);
  1498. }
  1499. };
  1500. var actions = {
  1501. jumpListWalk: function(cm, actionArgs, vim) {
  1502. if (vim.visualMode) {
  1503. return;
  1504. }
  1505. var repeat = actionArgs.repeat;
  1506. var forward = actionArgs.forward;
  1507. var jumpList = getVimGlobalState().jumpList;
  1508. var mark = jumpList.move(cm, forward ? repeat : -repeat);
  1509. var markPos = mark ? mark.find() : undefined;
  1510. markPos = markPos ? markPos : cm.getCursor();
  1511. cm.setCursor(markPos);
  1512. },
  1513. scrollToCursor: function(cm, actionArgs) {
  1514. var lineNum = cm.getCursor().line;
  1515. var charCoords = cm.charCoords({line: lineNum, ch: 0}, "local");
  1516. var height = cm.getScrollInfo().clientHeight;
  1517. var y = charCoords.top;
  1518. var lineHeight = charCoords.bottom - y;
  1519. switch (actionArgs.position) {
  1520. case 'center': y = y - (height / 2) + lineHeight;
  1521. break;
  1522. case 'bottom': y = y - height + lineHeight*1.4;
  1523. break;
  1524. case 'top': y = y + lineHeight*0.4;
  1525. break;
  1526. }
  1527. cm.scrollTo(null, y);
  1528. },
  1529. replayMacro: function(cm, actionArgs) {
  1530. var registerName = actionArgs.selectedCharacter;
  1531. var repeat = actionArgs.repeat;
  1532. var macroModeState = getVimGlobalState().macroModeState;
  1533. if (registerName == '@') {
  1534. registerName = macroModeState.latestRegister;
  1535. }
  1536. var keyBuffer = parseRegisterToKeyBuffer(macroModeState, registerName);
  1537. while(repeat--){
  1538. executeMacroKeyBuffer(cm, macroModeState, keyBuffer);
  1539. }
  1540. },
  1541. exitMacroRecordMode: function(cm, actionArgs) {
  1542. var macroModeState = getVimGlobalState().macroModeState;
  1543. macroModeState.toggle();
  1544. parseKeyBufferToRegister(macroModeState.latestRegister,
  1545. macroModeState.macroKeyBuffer);
  1546. },
  1547. enterMacroRecordMode: function(cm, actionArgs) {
  1548. var macroModeState = getVimGlobalState().macroModeState;
  1549. var registerName = actionArgs.selectedCharacter;
  1550. macroModeState.toggle(cm, registerName);
  1551. emptyMacroKeyBuffer(macroModeState);
  1552. },
  1553. enterInsertMode: function(cm, actionArgs) {
  1554. var insertAt = (actionArgs) ? actionArgs.insertAt : null;
  1555. if (insertAt == 'eol') {
  1556. var cursor = cm.getCursor();
  1557. cursor = { line: cursor.line, ch: lineLength(cm, cursor.line) };
  1558. cm.setCursor(cursor);
  1559. } else if (insertAt == 'charAfter') {
  1560. cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
  1561. } else if (insertAt == 'firstNonBlank') {
  1562. cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
  1563. }
  1564. cm.setOption('keyMap', 'vim-insert');
  1565. },
  1566. toggleVisualMode: function(cm, actionArgs, vim) {
  1567. var repeat = actionArgs.repeat;
  1568. var curStart = cm.getCursor();
  1569. var curEnd;
  1570. // TODO: The repeat should actually select number of characters/lines
  1571. // equal to the repeat times the size of the previous visual
  1572. // operation.
  1573. if (!vim.visualMode) {
  1574. vim.visualMode = true;
  1575. vim.visualLine = !!actionArgs.linewise;
  1576. if (vim.visualLine) {
  1577. curStart.ch = 0;
  1578. curEnd = clipCursorToContent(cm, {
  1579. line: curStart.line + repeat - 1,
  1580. ch: lineLength(cm, curStart.line)
  1581. }, true /** includeLineBreak */);
  1582. } else {
  1583. curEnd = clipCursorToContent(cm, {
  1584. line: curStart.line,
  1585. ch: curStart.ch + repeat
  1586. }, true /** includeLineBreak */);
  1587. }
  1588. // Make the initial selection.
  1589. if (!actionArgs.repeatIsExplicit && !vim.visualLine) {
  1590. // This is a strange case. Here the implicit repeat is 1. The
  1591. // following commands lets the cursor hover over the 1 character
  1592. // selection.
  1593. cm.setCursor(curEnd);
  1594. cm.setSelection(curEnd, curStart);
  1595. } else {
  1596. cm.setSelection(curStart, curEnd);
  1597. }
  1598. } else {
  1599. curStart = cm.getCursor('anchor');
  1600. curEnd = cm.getCursor('head');
  1601. if (!vim.visualLine && actionArgs.linewise) {
  1602. // Shift-V pressed in characterwise visual mode. Switch to linewise
  1603. // visual mode instead of exiting visual mode.
  1604. vim.visualLine = true;
  1605. curStart.ch = cursorIsBefore(curStart, curEnd) ? 0 :
  1606. lineLength(cm, curStart.line);
  1607. curEnd.ch = cursorIsBefore(curStart, curEnd) ?
  1608. lineLength(cm, curEnd.line) : 0;
  1609. cm.setSelection(curStart, curEnd);
  1610. } else if (vim.visualLine && !actionArgs.linewise) {
  1611. // v pressed in linewise visual mode. Switch to characterwise visual
  1612. // mode instead of exiting visual mode.
  1613. vim.visualLine = false;
  1614. } else {
  1615. exitVisualMode(cm, vim);
  1616. }
  1617. }
  1618. updateMark(cm, vim, '<', cursorIsBefore(curStart, curEnd) ? curStart
  1619. : curEnd);
  1620. updateMark(cm, vim, '>', cursorIsBefore(curStart, curEnd) ? curEnd
  1621. : curStart);
  1622. },
  1623. joinLines: function(cm, actionArgs, vim) {
  1624. var curStart, curEnd;
  1625. if (vim.visualMode) {
  1626. curStart = cm.getCursor('anchor');
  1627. curEnd = cm.getCursor('head');
  1628. curEnd.ch = lineLength(cm, curEnd.line) - 1;
  1629. } else {
  1630. // Repeat is the number of lines to join. Minimum 2 lines.
  1631. var repeat = Math.max(actionArgs.repeat, 2);
  1632. curStart = cm.getCursor();
  1633. curEnd = clipCursorToContent(cm, { line: curStart.line + repeat - 1,
  1634. ch: Infinity });
  1635. }
  1636. var finalCh = 0;
  1637. cm.operation(function() {
  1638. for (var i = curStart.line; i < curEnd.line; i++) {
  1639. finalCh = lineLength(cm, curStart.line);
  1640. var tmp = { line: curStart.line + 1,
  1641. ch: lineLength(cm, curStart.line + 1) };
  1642. var text = cm.getRange(curStart, tmp);
  1643. text = text.replace(/\n\s*/g, ' ');
  1644. cm.replaceRange(text, curStart, tmp);
  1645. }
  1646. var curFinalPos = { line: curStart.line, ch: finalCh };
  1647. cm.setCursor(curFinalPos);
  1648. });
  1649. },
  1650. newLineAndEnterInsertMode: function(cm, actionArgs) {
  1651. var insertAt = cm.getCursor();
  1652. if (insertAt.line === cm.firstLine() && !actionArgs.after) {
  1653. // Special case for inserting newline before start of document.
  1654. cm.replaceRange('\n', { line: cm.firstLine(), ch: 0 });
  1655. cm.setCursor(cm.firstLine(), 0);
  1656. } else {
  1657. insertAt.line = (actionArgs.after) ? insertAt.line :
  1658. insertAt.line - 1;
  1659. insertAt.ch = lineLength(cm, insertAt.line);
  1660. cm.setCursor(insertAt);
  1661. var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||
  1662. CodeMirror.commands.newlineAndIndent;
  1663. newlineFn(cm);
  1664. }
  1665. this.enterInsertMode(cm);
  1666. },
  1667. paste: function(cm, actionArgs, vim) {
  1668. var cur = cm.getCursor();
  1669. var register = getVimGlobalState().registerController.getRegister(
  1670. actionArgs.registerName);
  1671. if (!register.text) {
  1672. return;
  1673. }
  1674. for (var text = '', i = 0; i < actionArgs.repeat; i++) {
  1675. text += register.text;
  1676. }
  1677. var linewise = register.linewise;
  1678. if (linewise) {
  1679. if (actionArgs.after) {
  1680. // Move the newline at the end to the start instead, and paste just
  1681. // before the newline character of the line we are on right now.
  1682. text = '\n' + text.slice(0, text.length - 1);
  1683. cur.ch = lineLength(cm, cur.line);
  1684. } else {
  1685. cur.ch = 0;
  1686. }
  1687. } else {
  1688. cur.ch += actionArgs.after ? 1 : 0;
  1689. }
  1690. cm.replaceRange(text, cur);
  1691. // Now fine tune the cursor to where we want it.
  1692. var curPosFinal;
  1693. var idx;
  1694. if (linewise && actionArgs.after) {
  1695. curPosFinal = { line: cur.line + 1,
  1696. ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1)) };
  1697. } else if (linewise && !actionArgs.after) {
  1698. curPosFinal = { line: cur.line,
  1699. ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line)) };
  1700. } else if (!linewise && actionArgs.after) {
  1701. idx = cm.indexFromPos(cur);
  1702. curPosFinal = cm.posFromIndex(idx + text.length - 1);
  1703. } else {
  1704. idx = cm.indexFromPos(cur);
  1705. curPosFinal = cm.posFromIndex(idx + text.length);
  1706. }
  1707. cm.setCursor(curPosFinal);
  1708. },
  1709. undo: function(cm, actionArgs) {
  1710. repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();
  1711. },
  1712. redo: function(cm, actionArgs) {
  1713. repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();
  1714. },
  1715. setRegister: function(cm, actionArgs, vim) {
  1716. vim.inputState.registerName = actionArgs.selectedCharacter;
  1717. },
  1718. setMark: function(cm, actionArgs, vim) {
  1719. var markName = actionArgs.selectedCharacter;
  1720. updateMark(cm, vim, markName, cm.getCursor());
  1721. },
  1722. replace: function(cm, actionArgs, vim) {
  1723. var replaceWith = actionArgs.selectedCharacter;
  1724. var curStart = cm.getCursor();
  1725. var replaceTo;
  1726. var curEnd;
  1727. if(vim.visualMode){
  1728. curStart=cm.getCursor('start');
  1729. curEnd=cm.getCursor('end');
  1730. // workaround to catch the character under the cursor
  1731. // existing workaround doesn't cover actions
  1732. curEnd=cm.clipPos({line: curEnd.line, ch: curEnd.ch+1});
  1733. }else{
  1734. var line = cm.getLine(curStart.line);
  1735. replaceTo = curStart.ch + actionArgs.repeat;
  1736. if (replaceTo > line.length) {
  1737. replaceTo=line.length;
  1738. }
  1739. curEnd = { line: curStart.line, ch: replaceTo };
  1740. }
  1741. if(replaceWith=='\n'){
  1742. if(!vim.visualMode) cm.replaceRange('', curStart, curEnd);
  1743. // special case, where vim help says to replace by just one line-break
  1744. (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm);
  1745. }else {
  1746. var replaceWithStr=cm.getRange(curStart, curEnd);
  1747. //replace all characters in range by selected, but keep linebreaks
  1748. replaceWithStr=replaceWithStr.replace(/[^\n]/g,replaceWith);
  1749. cm.replaceRange(replaceWithStr, curStart, curEnd);
  1750. if(vim.visualMode){
  1751. cm.setCursor(curStart);
  1752. exitVisualMode(cm,vim);
  1753. }else{
  1754. cm.setCursor(offsetCursor(curEnd, 0, -1));
  1755. }
  1756. }
  1757. },
  1758. enterReplaceMode: function(cm, actionArgs) {
  1759. cm.setOption('keyMap', 'vim-replace');
  1760. cm.toggleOverwrite();
  1761. },
  1762. incrementNumberToken: function(cm, actionArgs, vim) {
  1763. var cur = cm.getCursor();
  1764. var lineStr = cm.getLine(cur.line);
  1765. var re = /-?\d+/g;
  1766. var match;
  1767. var start;
  1768. var end;
  1769. var numberStr;
  1770. var token;
  1771. while ((match = re.exec(lineStr)) !== null) {
  1772. token = match[0];
  1773. start = match.index;
  1774. end = start + token.length;
  1775. if(cur.ch < end)break;
  1776. }
  1777. if(!actionArgs.backtrack && (end <= cur.ch))return;
  1778. if (token) {
  1779. var increment = actionArgs.increase ? 1 : -1;
  1780. var number = parseInt(token) + (increment * actionArgs.repeat);
  1781. var from = {ch:start, line:cur.line};
  1782. var to = {ch:end, line:cur.line};
  1783. numberStr = number.toString();
  1784. cm.replaceRange(numberStr, from, to);
  1785. } else {
  1786. return;
  1787. }
  1788. cm.setCursor({line: cur.line, ch: start + numberStr.length - 1});
  1789. },
  1790. repeatLastEdit: function(cm, actionArgs, vim) {
  1791. // TODO: Make this repeat insert mode changes.
  1792. var lastEdit = vim.lastEdit;
  1793. if (lastEdit) {
  1794. if (actionArgs.repeat && actionArgs.repeatIsExplicit) {
  1795. vim.lastEdit.repeatOverride = actionArgs.repeat;
  1796. }
  1797. var currentInputState = vim.inputState;
  1798. vim.inputState = vim.lastEdit;
  1799. commandDispatcher.evalInput(cm, vim);
  1800. vim.inputState = currentInputState;
  1801. }
  1802. }
  1803. };
  1804. var textObjects = {
  1805. // TODO: lots of possible exceptions that can be thrown here. Try da(
  1806. // outside of a () block.
  1807. // TODO: implement text objects for the reverse like }. Should just be
  1808. // an additional mapping after moving to the defaultKeyMap.
  1809. 'w': function(cm, inclusive) {
  1810. return expandWordUnderCursor(cm, inclusive, true /** forward */,
  1811. false /** bigWord */);
  1812. },
  1813. 'W': function(cm, inclusive) {
  1814. return expandWordUnderCursor(cm, inclusive,
  1815. true /** forward */, true /** bigWord */);
  1816. },
  1817. '{': function(cm, inclusive) {
  1818. return selectCompanionObject(cm, '}', inclusive);
  1819. },
  1820. '(': function(cm, inclusive) {
  1821. return selectCompanionObject(cm, ')', inclusive);
  1822. },
  1823. '[': function(cm, inclusive) {
  1824. return selectCompanionObject(cm, ']', inclusive);
  1825. },
  1826. '\'': function(cm, inclusive) {
  1827. return findBeginningAndEnd(cm, "'", inclusive);
  1828. },
  1829. '\"': function(cm, inclusive) {
  1830. return findBeginningAndEnd(cm, '"', inclusive);
  1831. }
  1832. };
  1833. /*
  1834. * Below are miscellaneous utility functions used by vim.js
  1835. */
  1836. /**
  1837. * Clips cursor to ensure that line is within the buffer's range
  1838. * If includeLineBreak is true, then allow cur.ch == lineLength.
  1839. */
  1840. function clipCursorToContent(cm, cur, includeLineBreak) {
  1841. var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() );
  1842. var maxCh = lineLength(cm, line) - 1;
  1843. maxCh = (includeLineBreak) ? maxCh + 1 : maxCh;
  1844. var ch = Math.min(Math.max(0, cur.ch), maxCh);
  1845. return { line: line, ch: ch };
  1846. }
  1847. // Merge arguments in place, for overriding arguments.
  1848. function mergeArgs(to, from) {
  1849. for (var prop in from) {
  1850. if (from.hasOwnProperty(prop)) {
  1851. to[prop] = from[prop];
  1852. }
  1853. }
  1854. }
  1855. function copyArgs(args) {
  1856. var ret = {};
  1857. for (var prop in args) {
  1858. if (args.hasOwnProperty(prop)) {
  1859. ret[prop] = args[prop];
  1860. }
  1861. }
  1862. return ret;
  1863. }
  1864. function offsetCursor(cur, offsetLine, offsetCh) {
  1865. return { line: cur.line + offsetLine, ch: cur.ch + offsetCh };
  1866. }
  1867. function arrayEq(a1, a2) {
  1868. if (a1.length != a2.length) {
  1869. return false;
  1870. }
  1871. for (var i = 0; i < a1.length; i++) {
  1872. if (a1[i] != a2[i]) {
  1873. return false;
  1874. }
  1875. }
  1876. return true;
  1877. }
  1878. function matchKeysPartial(pressed, mapped) {
  1879. for (var i = 0; i < pressed.length; i++) {
  1880. // 'character' means any character. For mark, register commads, etc.
  1881. if (pressed[i] != mapped[i] && mapped[i] != 'character') {
  1882. return false;
  1883. }
  1884. }
  1885. return true;
  1886. }
  1887. function arrayIsSubsetFromBeginning(small, big) {
  1888. for (var i = 0; i < small.length; i++) {
  1889. if (small[i] != big[i]) {
  1890. return false;
  1891. }
  1892. }
  1893. return true;
  1894. }
  1895. function repeatFn(cm, fn, repeat) {
  1896. return function() {
  1897. for (var i = 0; i < repeat; i++) {
  1898. fn(cm);
  1899. }
  1900. };
  1901. }
  1902. function copyCursor(cur) {
  1903. return { line: cur.line, ch: cur.ch };
  1904. }
  1905. function cursorEqual(cur1, cur2) {
  1906. return cur1.ch == cur2.ch && cur1.line == cur2.line;
  1907. }
  1908. function cursorIsBefore(cur1, cur2) {
  1909. if (cur1.line < cur2.line) {
  1910. return true;
  1911. } else if (cur1.line == cur2.line && cur1.ch < cur2.ch) {
  1912. return true;
  1913. }
  1914. return false;
  1915. }
  1916. function cusrorIsBetween(cur1, cur2, cur3) {
  1917. // returns true if cur2 is between cur1 and cur3.
  1918. var cur1before2 = cursorIsBefore(cur1, cur2);
  1919. var cur2before3 = cursorIsBefore(cur2, cur3);
  1920. return cur1before2 && cur2before3;
  1921. }
  1922. function lineLength(cm, lineNum) {
  1923. return cm.getLine(lineNum).length;
  1924. }
  1925. function reverse(s){
  1926. return s.split("").reverse().join("");
  1927. }
  1928. function trim(s) {
  1929. if (s.trim) {
  1930. return s.trim();
  1931. } else {
  1932. return s.replace(/^\s+|\s+$/g, '');
  1933. }
  1934. }
  1935. function escapeRegex(s) {
  1936. return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, "\\$1");
  1937. }
  1938. function exitVisualMode(cm, vim) {
  1939. vim.visualMode = false;
  1940. vim.visualLine = false;
  1941. var selectionStart = cm.getCursor('anchor');
  1942. var selectionEnd = cm.getCursor('head');
  1943. if (!cursorEqual(selectionStart, selectionEnd)) {
  1944. // Clear the selection and set the cursor only if the selection has not
  1945. // already been cleared. Otherwise we risk moving the cursor somewhere
  1946. // it's not supposed to be.
  1947. cm.setCursor(clipCursorToContent(cm, selectionEnd));
  1948. }
  1949. }
  1950. // Remove any trailing newlines from the selection. For
  1951. // example, with the caret at the start of the last word on the line,
  1952. // 'dw' should word, but not the newline, while 'w' should advance the
  1953. // caret to the first character of the next line.
  1954. function clipToLine(cm, curStart, curEnd) {
  1955. var selection = cm.getRange(curStart, curEnd);
  1956. // Only clip if the selection ends with trailing newline + whitespace
  1957. if (/\n\s*$/.test(selection)) {
  1958. var lines = selection.split('\n');
  1959. // We know this is all whitepsace.
  1960. lines.pop();
  1961. // Cases:
  1962. // 1. Last word is an empty line - do not clip the trailing '\n'
  1963. // 2. Last word is not an empty line - clip the trailing '\n'
  1964. var line;
  1965. // Find the line containing the last word, and clip all whitespace up
  1966. // to it.
  1967. for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {
  1968. var clipped = false;
  1969. curEnd.line--;
  1970. curEnd.ch = 0;
  1971. }
  1972. // If the last word is not an empty line, clip an additional newline
  1973. if (line) {
  1974. curEnd.line--;
  1975. curEnd.ch = lineLength(cm, curEnd.line);
  1976. } else {
  1977. curEnd.ch = 0;
  1978. }
  1979. }
  1980. }
  1981. // Expand the selection to line ends.
  1982. function expandSelectionToLine(cm, curStart, curEnd) {
  1983. curStart.ch = 0;
  1984. curEnd.ch = 0;
  1985. curEnd.line++;
  1986. }
  1987. function findFirstNonWhiteSpaceCharacter(text) {
  1988. if (!text) {
  1989. return 0;
  1990. }
  1991. var firstNonWS = text.search(/\S/);
  1992. return firstNonWS == -1 ? text.length : firstNonWS;
  1993. }
  1994. function expandWordUnderCursor(cm, inclusive, forward, bigWord, noSymbol) {
  1995. var cur = cm.getCursor();
  1996. var line = cm.getLine(cur.line);
  1997. var idx = cur.ch;
  1998. // Seek to first word or non-whitespace character, depending on if
  1999. // noSymbol is true.
  2000. var textAfterIdx = line.substring(idx);
  2001. var firstMatchedChar;
  2002. if (noSymbol) {
  2003. firstMatchedChar = textAfterIdx.search(/\w/);
  2004. } else {
  2005. firstMatchedChar = textAfterIdx.search(/\S/);
  2006. }
  2007. if (firstMatchedChar == -1) {
  2008. return null;
  2009. }
  2010. idx += firstMatchedChar;
  2011. textAfterIdx = line.substring(idx);
  2012. var textBeforeIdx = line.substring(0, idx);
  2013. var matchRegex;
  2014. // Greedy matchers for the "word" we are trying to expand.
  2015. if (bigWord) {
  2016. matchRegex = /^\S+/;
  2017. } else {
  2018. if ((/\w/).test(line.charAt(idx))) {
  2019. matchRegex = /^\w+/;
  2020. } else {
  2021. matchRegex = /^[^\w\s]+/;
  2022. }
  2023. }
  2024. var wordAfterRegex = matchRegex.exec(textAfterIdx);
  2025. var wordStart = idx;
  2026. var wordEnd = idx + wordAfterRegex[0].length;
  2027. // TODO: Find a better way to do this. It will be slow on very long lines.
  2028. var revTextBeforeIdx = reverse(textBeforeIdx);
  2029. var wordBeforeRegex = matchRegex.exec(revTextBeforeIdx);
  2030. if (wordBeforeRegex) {
  2031. wordStart -= wordBeforeRegex[0].length;
  2032. }
  2033. if (inclusive) {
  2034. // If present, trim all whitespace after word.
  2035. // Otherwise, trim all whitespace before word.
  2036. var textAfterWordEnd = line.substring(wordEnd);
  2037. var whitespacesAfterWord = textAfterWordEnd.match(/^\s*/)[0].length;
  2038. if (whitespacesAfterWord > 0) {
  2039. wordEnd += whitespacesAfterWord;
  2040. } else {
  2041. var revTrim = revTextBeforeIdx.length - wordStart;
  2042. var textBeforeWordStart = revTextBeforeIdx.substring(revTrim);
  2043. var whitespacesBeforeWord = textBeforeWordStart.match(/^\s*/)[0].length;
  2044. wordStart -= whitespacesBeforeWord;
  2045. }
  2046. }
  2047. return { start: { line: cur.line, ch: wordStart },
  2048. end: { line: cur.line, ch: wordEnd }};
  2049. }
  2050. function recordJumpPosition(cm, oldCur, newCur) {
  2051. if(!cursorEqual(oldCur, newCur)) {
  2052. getVimGlobalState().jumpList.add(cm, oldCur, newCur);
  2053. }
  2054. }
  2055. function recordLastCharacterSearch(increment, args) {
  2056. var vimGlobalState = getVimGlobalState();
  2057. vimGlobalState.lastChararacterSearch.increment = increment;
  2058. vimGlobalState.lastChararacterSearch.forward = args.forward;
  2059. vimGlobalState.lastChararacterSearch.selectedCharacter = args.selectedCharacter;
  2060. }
  2061. var symbolToMode = {
  2062. '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',
  2063. '[': 'section', ']': 'section',
  2064. '*': 'comment', '/': 'comment',
  2065. 'm': 'method', 'M': 'method',
  2066. '#': 'preprocess'
  2067. };
  2068. var findSymbolModes = {
  2069. bracket: {
  2070. isComplete: function(state) {
  2071. if (state.nextCh === state.symb) {
  2072. state.depth++;
  2073. if(state.depth >= 1)return true;
  2074. } else if (state.nextCh === state.reverseSymb) {
  2075. state.depth--;
  2076. }
  2077. return false;
  2078. }
  2079. },
  2080. section: {
  2081. init: function(state) {
  2082. state.curMoveThrough = true;
  2083. state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';
  2084. },
  2085. isComplete: function(state) {
  2086. return state.index === 0 && state.nextCh === state.symb;
  2087. }
  2088. },
  2089. comment: {
  2090. isComplete: function(state) {
  2091. var found = state.lastCh === '*' && state.nextCh === '/';
  2092. state.lastCh = state.nextCh;
  2093. return found;
  2094. }
  2095. },
  2096. // TODO: The original Vim implementation only operates on level 1 and 2.
  2097. // The current implementation doesn't check for code block level and
  2098. // therefore it operates on any levels.
  2099. method: {
  2100. init: function(state) {
  2101. state.symb = (state.symb === 'm' ? '{' : '}');
  2102. state.reverseSymb = state.symb === '{' ? '}' : '{';
  2103. },
  2104. isComplete: function(state) {
  2105. if(state.nextCh === state.symb)return true;
  2106. return false;
  2107. }
  2108. },
  2109. preprocess: {
  2110. init: function(state) {
  2111. state.index = 0;
  2112. },
  2113. isComplete: function(state) {
  2114. if (state.nextCh === '#') {
  2115. var token = state.lineText.match(/#(\w+)/)[1];
  2116. if (token === 'endif') {
  2117. if (state.forward && state.depth === 0) {
  2118. return true;
  2119. }
  2120. state.depth++;
  2121. } else if (token === 'if') {
  2122. if (!state.forward && state.depth === 0) {
  2123. return true;
  2124. }
  2125. state.depth--;
  2126. }
  2127. if(token === 'else' && state.depth === 0)return true;
  2128. }
  2129. return false;
  2130. }
  2131. }
  2132. };
  2133. function findSymbol(cm, repeat, forward, symb) {
  2134. var cur = cm.getCursor();
  2135. var increment = forward ? 1 : -1;
  2136. var endLine = forward ? cm.lineCount() : -1;
  2137. var curCh = cur.ch;
  2138. var line = cur.line;
  2139. var lineText = cm.getLine(line);
  2140. var state = {
  2141. lineText: lineText,
  2142. nextCh: lineText.charAt(curCh),
  2143. lastCh: null,
  2144. index: curCh,
  2145. symb: symb,
  2146. reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],
  2147. forward: forward,
  2148. depth: 0,
  2149. curMoveThrough: false
  2150. };
  2151. var mode = symbolToMode[symb];
  2152. if(!mode)return cur;
  2153. var init = findSymbolModes[mode].init;
  2154. var isComplete = findSymbolModes[mode].isComplete;
  2155. if(init)init(state);
  2156. while (line !== endLine && repeat) {
  2157. state.index += increment;
  2158. state.nextCh = state.lineText.charAt(state.index);
  2159. if (!state.nextCh) {
  2160. line += increment;
  2161. state.lineText = cm.getLine(line) || '';
  2162. if (increment > 0) {
  2163. state.index = 0;
  2164. } else {
  2165. var lineLen = state.lineText.length;
  2166. state.index = (lineLen > 0) ? (lineLen-1) : 0;
  2167. }
  2168. state.nextCh = state.lineText.charAt(state.index);
  2169. }
  2170. if (isComplete(state)) {
  2171. cur.line = line;
  2172. cur.ch = state.index;
  2173. repeat--;
  2174. }
  2175. }
  2176. if (state.nextCh || state.curMoveThrough) {
  2177. return { line: line, ch: state.index };
  2178. }
  2179. return cur;
  2180. }
  2181. /*
  2182. * Returns the boundaries of the next word. If the cursor in the middle of
  2183. * the word, then returns the boundaries of the current word, starting at
  2184. * the cursor. If the cursor is at the start/end of a word, and we are going
  2185. * forward/backward, respectively, find the boundaries of the next word.
  2186. *
  2187. * @param {CodeMirror} cm CodeMirror object.
  2188. * @param {Cursor} cur The cursor position.
  2189. * @param {boolean} forward True to search forward. False to search
  2190. * backward.
  2191. * @param {boolean} bigWord True if punctuation count as part of the word.
  2192. * False if only [a-zA-Z0-9] characters count as part of the word.
  2193. * @param {boolean} emptyLineIsWord True if empty lines should be treated
  2194. * as words.
  2195. * @return {Object{from:number, to:number, line: number}} The boundaries of
  2196. * the word, or null if there are no more words.
  2197. */
  2198. function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {
  2199. var lineNum = cur.line;
  2200. var pos = cur.ch;
  2201. var line = cm.getLine(lineNum);
  2202. var dir = forward ? 1 : -1;
  2203. var regexps = bigWord ? bigWordRegexp : wordRegexp;
  2204. if (emptyLineIsWord && line == '') {
  2205. lineNum += dir;
  2206. line = cm.getLine(lineNum);
  2207. if (!isLine(cm, lineNum)) {
  2208. return null;
  2209. }
  2210. pos = (forward) ? 0 : line.length;
  2211. }
  2212. while (true) {
  2213. if (emptyLineIsWord && line == '') {
  2214. return { from: 0, to: 0, line: lineNum };
  2215. }
  2216. var stop = (dir > 0) ? line.length : -1;
  2217. var wordStart = stop, wordEnd = stop;
  2218. // Find bounds of next word.
  2219. while (pos != stop) {
  2220. var foundWord = false;
  2221. for (var i = 0; i < regexps.length && !foundWord; ++i) {
  2222. if (regexps[i].test(line.charAt(pos))) {
  2223. wordStart = pos;
  2224. // Advance to end of word.
  2225. while (pos != stop && regexps[i].test(line.charAt(pos))) {
  2226. pos += dir;
  2227. }
  2228. wordEnd = pos;
  2229. foundWord = wordStart != wordEnd;
  2230. if (wordStart == cur.ch && lineNum == cur.line &&
  2231. wordEnd == wordStart + dir) {
  2232. // We started at the end of a word. Find the next one.
  2233. continue;
  2234. } else {
  2235. return {
  2236. from: Math.min(wordStart, wordEnd + 1),
  2237. to: Math.max(wordStart, wordEnd),
  2238. line: lineNum };
  2239. }
  2240. }
  2241. }
  2242. if (!foundWord) {
  2243. pos += dir;
  2244. }
  2245. }
  2246. // Advance to next/prev line.
  2247. lineNum += dir;
  2248. if (!isLine(cm, lineNum)) {
  2249. return null;
  2250. }
  2251. line = cm.getLine(lineNum);
  2252. pos = (dir > 0) ? 0 : line.length;
  2253. }
  2254. // Should never get here.
  2255. throw 'The impossible happened.';
  2256. }
  2257. /**
  2258. * @param {CodeMirror} cm CodeMirror object.
  2259. * @param {int} repeat Number of words to move past.
  2260. * @param {boolean} forward True to search forward. False to search
  2261. * backward.
  2262. * @param {boolean} wordEnd True to move to end of word. False to move to
  2263. * beginning of word.
  2264. * @param {boolean} bigWord True if punctuation count as part of the word.
  2265. * False if only alphabet characters count as part of the word.
  2266. * @return {Cursor} The position the cursor should move to.
  2267. */
  2268. function moveToWord(cm, repeat, forward, wordEnd, bigWord) {
  2269. var cur = cm.getCursor();
  2270. var curStart = copyCursor(cur);
  2271. var words = [];
  2272. if (forward && !wordEnd || !forward && wordEnd) {
  2273. repeat++;
  2274. }
  2275. // For 'e', empty lines are not considered words, go figure.
  2276. var emptyLineIsWord = !(forward && wordEnd);
  2277. for (var i = 0; i < repeat; i++) {
  2278. var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord);
  2279. if (!word) {
  2280. var eodCh = lineLength(cm, cm.lastLine());
  2281. words.push(forward
  2282. ? {line: cm.lastLine(), from: eodCh, to: eodCh}
  2283. : {line: 0, from: 0, to: 0});
  2284. break;
  2285. }
  2286. words.push(word);
  2287. cur = {line: word.line, ch: forward ? (word.to - 1) : word.from};
  2288. }
  2289. var shortCircuit = words.length != repeat;
  2290. var firstWord = words[0];
  2291. var lastWord = words.pop();
  2292. if (forward && !wordEnd) {
  2293. // w
  2294. if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) {
  2295. // We did not start in the middle of a word. Discard the extra word at the end.
  2296. lastWord = words.pop();
  2297. }
  2298. return {line: lastWord.line, ch: lastWord.from};
  2299. } else if (forward && wordEnd) {
  2300. return {line: lastWord.line, ch: lastWord.to - 1};
  2301. } else if (!forward && wordEnd) {
  2302. // ge
  2303. if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) {
  2304. // We did not start in the middle of a word. Discard the extra word at the end.
  2305. lastWord = words.pop();
  2306. }
  2307. return {line: lastWord.line, ch: lastWord.to};
  2308. } else {
  2309. // b
  2310. return {line: lastWord.line, ch: lastWord.from};
  2311. }
  2312. }
  2313. function moveToCharacter(cm, repeat, forward, character) {
  2314. var cur = cm.getCursor();
  2315. var start = cur.ch;
  2316. var idx;
  2317. for (var i = 0; i < repeat; i ++) {
  2318. var line = cm.getLine(cur.line);
  2319. idx = charIdxInLine(start, line, character, forward, true);
  2320. if (idx == -1) {
  2321. return null;
  2322. }
  2323. start = idx;
  2324. }
  2325. return { line: cm.getCursor().line, ch: idx };
  2326. }
  2327. function moveToColumn(cm, repeat) {
  2328. // repeat is always >= 1, so repeat - 1 always corresponds
  2329. // to the column we want to go to.
  2330. var line = cm.getCursor().line;
  2331. return clipCursorToContent(cm, { line: line, ch: repeat - 1 });
  2332. }
  2333. function updateMark(cm, vim, markName, pos) {
  2334. if (!inArray(markName, validMarks)) {
  2335. return;
  2336. }
  2337. if (vim.marks[markName]) {
  2338. vim.marks[markName].clear();
  2339. }
  2340. vim.marks[markName] = cm.setBookmark(pos);
  2341. }
  2342. function charIdxInLine(start, line, character, forward, includeChar) {
  2343. // Search for char in line.
  2344. // motion_options: {forward, includeChar}
  2345. // If includeChar = true, include it too.
  2346. // If forward = true, search forward, else search backwards.
  2347. // If char is not found on this line, do nothing
  2348. var idx;
  2349. if (forward) {
  2350. idx = line.indexOf(character, start + 1);
  2351. if (idx != -1 && !includeChar) {
  2352. idx -= 1;
  2353. }
  2354. } else {
  2355. idx = line.lastIndexOf(character, start - 1);
  2356. if (idx != -1 && !includeChar) {
  2357. idx += 1;
  2358. }
  2359. }
  2360. return idx;
  2361. }
  2362. function getContextLevel(ctx) {
  2363. return (ctx === 'string' || ctx === 'comment') ? 1 : 0;
  2364. }
  2365. function findMatchedSymbol(cm, cur, symb) {
  2366. var line = cur.line;
  2367. var ch = cur.ch;
  2368. symb = symb ? symb : cm.getLine(line).charAt(ch);
  2369. var symbContext = cm.getTokenAt({line:line, ch:ch+1}).type;
  2370. var symbCtxLevel = getContextLevel(symbContext);
  2371. var reverseSymb = ({
  2372. '(': ')', ')': '(',
  2373. '[': ']', ']': '[',
  2374. '{': '}', '}': '{'})[symb];
  2375. // Couldn't find a matching symbol, abort
  2376. if (!reverseSymb) {
  2377. return cur;
  2378. }
  2379. // set our increment to move forward (+1) or backwards (-1)
  2380. // depending on which bracket we're matching
  2381. var increment = ({'(': 1, '{': 1, '[': 1})[symb] || -1;
  2382. var endLine = increment === 1 ? cm.lineCount() : -1;
  2383. var depth = 1, nextCh = symb, index = ch, lineText = cm.getLine(line);
  2384. // Simple search for closing paren--just count openings and closings till
  2385. // we find our match
  2386. // TODO: use info from CodeMirror to ignore closing brackets in comments
  2387. // and quotes, etc.
  2388. while (line !== endLine && depth > 0) {
  2389. index += increment;
  2390. nextCh = lineText.charAt(index);
  2391. if (!nextCh) {
  2392. line += increment;
  2393. lineText = cm.getLine(line) || '';
  2394. if (increment > 0) {
  2395. index = 0;
  2396. } else {
  2397. var lineLen = lineText.length;
  2398. index = (lineLen > 0) ? (lineLen-1) : 0;
  2399. }
  2400. nextCh = lineText.charAt(index);
  2401. }
  2402. var revSymbContext = cm.getTokenAt({line:line, ch:index+1}).type;
  2403. var revSymbCtxLevel = getContextLevel(revSymbContext);
  2404. if (symbCtxLevel >= revSymbCtxLevel) {
  2405. if (nextCh === symb) {
  2406. depth++;
  2407. } else if (nextCh === reverseSymb) {
  2408. depth--;
  2409. }
  2410. }
  2411. }
  2412. if (nextCh) {
  2413. return { line: line, ch: index };
  2414. }
  2415. return cur;
  2416. }
  2417. function selectCompanionObject(cm, revSymb, inclusive) {
  2418. var cur = cm.getCursor();
  2419. var end = findMatchedSymbol(cm, cur, revSymb);
  2420. var start = findMatchedSymbol(cm, end);
  2421. start.ch += inclusive ? 1 : 0;
  2422. end.ch += inclusive ? 0 : 1;
  2423. return { start: start, end: end };
  2424. }
  2425. function regexLastIndexOf(string, pattern, startIndex) {
  2426. for (var i = !startIndex ? string.length : startIndex;
  2427. i >= 0; --i) {
  2428. if (pattern.test(string.charAt(i))) {
  2429. return i;
  2430. }
  2431. }
  2432. return -1;
  2433. }
  2434. // Takes in a symbol and a cursor and tries to simulate text objects that
  2435. // have identical opening and closing symbols
  2436. // TODO support across multiple lines
  2437. function findBeginningAndEnd(cm, symb, inclusive) {
  2438. var cur = cm.getCursor();
  2439. var line = cm.getLine(cur.line);
  2440. var chars = line.split('');
  2441. var start, end, i, len;
  2442. var firstIndex = chars.indexOf(symb);
  2443. // the decision tree is to always look backwards for the beginning first,
  2444. // but if the cursor is in front of the first instance of the symb,
  2445. // then move the cursor forward
  2446. if (cur.ch < firstIndex) {
  2447. cur.ch = firstIndex;
  2448. // Why is this line even here???
  2449. // cm.setCursor(cur.line, firstIndex+1);
  2450. }
  2451. // otherwise if the cursor is currently on the closing symbol
  2452. else if (firstIndex < cur.ch && chars[cur.ch] == symb) {
  2453. end = cur.ch; // assign end to the current cursor
  2454. --cur.ch; // make sure to look backwards
  2455. }
  2456. // if we're currently on the symbol, we've got a start
  2457. if (chars[cur.ch] == symb && !end) {
  2458. start = cur.ch + 1; // assign start to ahead of the cursor
  2459. } else {
  2460. // go backwards to find the start
  2461. for (i = cur.ch; i > -1 && !start; i--) {
  2462. if (chars[i] == symb) {
  2463. start = i + 1;
  2464. }
  2465. }
  2466. }
  2467. // look forwards for the end symbol
  2468. if (start && !end) {
  2469. for (i = start, len = chars.length; i < len && !end; i++) {
  2470. if (chars[i] == symb) {
  2471. end = i;
  2472. }
  2473. }
  2474. }
  2475. // nothing found
  2476. if (!start || !end) {
  2477. return { start: cur, end: cur };
  2478. }
  2479. // include the symbols
  2480. if (inclusive) {
  2481. --start; ++end;
  2482. }
  2483. return {
  2484. start: { line: cur.line, ch: start },
  2485. end: { line: cur.line, ch: end }
  2486. };
  2487. }
  2488. // Search functions
  2489. function SearchState() {}
  2490. SearchState.prototype = {
  2491. getQuery: function() {
  2492. return getVimGlobalState().query;
  2493. },
  2494. setQuery: function(query) {
  2495. getVimGlobalState().query = query;
  2496. },
  2497. getOverlay: function() {
  2498. return this.searchOverlay;
  2499. },
  2500. setOverlay: function(overlay) {
  2501. this.searchOverlay = overlay;
  2502. },
  2503. isReversed: function() {
  2504. return getVimGlobalState().isReversed;
  2505. },
  2506. setReversed: function(reversed) {
  2507. getVimGlobalState().isReversed = reversed;
  2508. }
  2509. };
  2510. function getSearchState(cm) {
  2511. var vim = getVimState(cm);
  2512. return vim.searchState_ || (vim.searchState_ = new SearchState());
  2513. }
  2514. function dialog(cm, template, shortText, onClose, options) {
  2515. if (cm.openDialog) {
  2516. cm.openDialog(template, onClose, { bottom: true, value: options.value,
  2517. onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp });
  2518. }
  2519. else {
  2520. onClose(prompt(shortText, ""));
  2521. }
  2522. }
  2523. function findUnescapedSlashes(str) {
  2524. var escapeNextChar = false;
  2525. var slashes = [];
  2526. for (var i = 0; i < str.length; i++) {
  2527. var c = str.charAt(i);
  2528. if (!escapeNextChar && c == '/') {
  2529. slashes.push(i);
  2530. }
  2531. escapeNextChar = (c == '\\');
  2532. }
  2533. return slashes;
  2534. }
  2535. /**
  2536. * Extract the regular expression from the query and return a Regexp object.
  2537. * Returns null if the query is blank.
  2538. * If ignoreCase is passed in, the Regexp object will have the 'i' flag set.
  2539. * If smartCase is passed in, and the query contains upper case letters,
  2540. * then ignoreCase is overridden, and the 'i' flag will not be set.
  2541. * If the query contains the /i in the flag part of the regular expression,
  2542. * then both ignoreCase and smartCase are ignored, and 'i' will be passed
  2543. * through to the Regex object.
  2544. */
  2545. function parseQuery(cm, query, ignoreCase, smartCase) {
  2546. // Check if the query is already a regex.
  2547. if (query instanceof RegExp) { return query; }
  2548. // First try to extract regex + flags from the input. If no flags found,
  2549. // extract just the regex. IE does not accept flags directly defined in
  2550. // the regex string in the form /regex/flags
  2551. var slashes = findUnescapedSlashes(query);
  2552. var regexPart;
  2553. var forceIgnoreCase;
  2554. if (!slashes.length) {
  2555. // Query looks like 'regexp'
  2556. regexPart = query;
  2557. } else {
  2558. // Query looks like 'regexp/...'
  2559. regexPart = query.substring(0, slashes[0]);
  2560. var flagsPart = query.substring(slashes[0]);
  2561. forceIgnoreCase = (flagsPart.indexOf('i') != -1);
  2562. }
  2563. if (!regexPart) {
  2564. return null;
  2565. }
  2566. if (smartCase) {
  2567. ignoreCase = (/^[^A-Z]*$/).test(regexPart);
  2568. }
  2569. var regexp = new RegExp(regexPart,
  2570. (ignoreCase || forceIgnoreCase) ? 'i' : undefined);
  2571. return regexp;
  2572. }
  2573. function showConfirm(cm, text) {
  2574. if (cm.openConfirm) {
  2575. cm.openConfirm('<span style="color: red">' + text +
  2576. '</span> <button type="button">OK</button>', function() {},
  2577. {bottom: true});
  2578. } else {
  2579. alert(text);
  2580. }
  2581. }
  2582. function makePrompt(prefix, desc) {
  2583. var raw = '';
  2584. if (prefix) {
  2585. raw += '<span style="font-family: monospace">' + prefix + '</span>';
  2586. }
  2587. raw += '<input type="text"/> ' +
  2588. '<span style="color: #888">';
  2589. if (desc) {
  2590. raw += '<span style="color: #888">';
  2591. raw += desc;
  2592. raw += '</span>';
  2593. }
  2594. return raw;
  2595. }
  2596. var searchPromptDesc = '(Javascript regexp)';
  2597. function showPrompt(cm, options) {
  2598. var shortText = (options.prefix || '') + ' ' + (options.desc || '');
  2599. var prompt = makePrompt(options.prefix, options.desc);
  2600. dialog(cm, prompt, shortText, options.onClose, options);
  2601. }
  2602. function regexEqual(r1, r2) {
  2603. if (r1 instanceof RegExp && r2 instanceof RegExp) {
  2604. var props = ["global", "multiline", "ignoreCase", "source"];
  2605. for (var i = 0; i < props.length; i++) {
  2606. var prop = props[i];
  2607. if (r1[prop] !== r2[prop]) {
  2608. return(false);
  2609. }
  2610. }
  2611. return(true);
  2612. }
  2613. return(false);
  2614. }
  2615. // Returns true if the query is valid.
  2616. function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {
  2617. if (!rawQuery) {
  2618. return;
  2619. }
  2620. var state = getSearchState(cm);
  2621. var query = parseQuery(cm, rawQuery, !!ignoreCase, !!smartCase);
  2622. if (!query) {
  2623. return;
  2624. }
  2625. highlightSearchMatches(cm, query);
  2626. if (regexEqual(query, state.getQuery())) {
  2627. return query;
  2628. }
  2629. state.setQuery(query);
  2630. return query;
  2631. }
  2632. function searchOverlay(query) {
  2633. if (query.source.charAt(0) == '^') {
  2634. var matchSol = true;
  2635. }
  2636. return {
  2637. token: function(stream) {
  2638. if (matchSol && !stream.sol()) {
  2639. stream.skipToEnd();
  2640. return;
  2641. }
  2642. var match = stream.match(query, false);
  2643. if (match) {
  2644. if (match[0].length == 0) {
  2645. // Matched empty string, skip to next.
  2646. stream.next();
  2647. return "searching";
  2648. }
  2649. if (!stream.sol()) {
  2650. // Backtrack 1 to match \b
  2651. stream.backUp(1);
  2652. if (!query.exec(stream.next() + match[0])) {
  2653. stream.next();
  2654. return null;
  2655. }
  2656. }
  2657. stream.match(query);
  2658. return "searching";
  2659. }
  2660. while (!stream.eol()) {
  2661. stream.next();
  2662. if (stream.match(query, false)) break;
  2663. }
  2664. },
  2665. query: query
  2666. };
  2667. }
  2668. function highlightSearchMatches(cm, query) {
  2669. var overlay = getSearchState(cm).getOverlay();
  2670. if (!overlay || query != overlay.query) {
  2671. if (overlay) {
  2672. cm.removeOverlay(overlay);
  2673. }
  2674. overlay = searchOverlay(query);
  2675. cm.addOverlay(overlay);
  2676. getSearchState(cm).setOverlay(overlay);
  2677. }
  2678. }
  2679. function findNext(cm, prev, query, repeat) {
  2680. if (repeat === undefined) { repeat = 1; }
  2681. return cm.operation(function() {
  2682. var pos = cm.getCursor();
  2683. var cursor = cm.getSearchCursor(query, pos);
  2684. for (var i = 0; i < repeat; i++) {
  2685. var found = cursor.find(prev);
  2686. if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); }
  2687. if (!found) {
  2688. // SearchCursor may have returned null because it hit EOF, wrap
  2689. // around and try again.
  2690. cursor = cm.getSearchCursor(query,
  2691. (prev) ? { line: cm.lastLine() } : {line: cm.firstLine(), ch: 0} );
  2692. if (!cursor.find(prev)) {
  2693. return;
  2694. }
  2695. }
  2696. }
  2697. return cursor.from();
  2698. });}
  2699. function clearSearchHighlight(cm) {
  2700. cm.removeOverlay(getSearchState(cm).getOverlay());
  2701. getSearchState(cm).setOverlay(null);
  2702. }
  2703. /**
  2704. * Check if pos is in the specified range, INCLUSIVE.
  2705. * Range can be specified with 1 or 2 arguments.
  2706. * If the first range argument is an array, treat it as an array of line
  2707. * numbers. Match pos against any of the lines.
  2708. * If the first range argument is a number,
  2709. * if there is only 1 range argument, check if pos has the same line
  2710. * number
  2711. * if there are 2 range arguments, then check if pos is in between the two
  2712. * range arguments.
  2713. */
  2714. function isInRange(pos, start, end) {
  2715. if (typeof pos != 'number') {
  2716. // Assume it is a cursor position. Get the line number.
  2717. pos = pos.line;
  2718. }
  2719. if (start instanceof Array) {
  2720. return inArray(pos, start);
  2721. } else {
  2722. if (end) {
  2723. return (pos >= start && pos <= end);
  2724. } else {
  2725. return pos == start;
  2726. }
  2727. }
  2728. }
  2729. function getUserVisibleLines(cm) {
  2730. var scrollInfo = cm.getScrollInfo();
  2731. var occludeTorleranceTop = 6;
  2732. var occludeTorleranceBottom = 10;
  2733. var from = cm.coordsChar({left:0, top: occludeTorleranceTop}, 'local');
  2734. var bottomY = scrollInfo.clientHeight - occludeTorleranceBottom;
  2735. var to = cm.coordsChar({left:0, top: bottomY}, 'local');
  2736. return {top: from.line, bottom: to.line};
  2737. }
  2738. // Ex command handling
  2739. // Care must be taken when adding to the default Ex command map. For any
  2740. // pair of commands that have a shared prefix, at least one of their
  2741. // shortNames must not match the prefix of the other command.
  2742. var defaultExCommandMap = [
  2743. { name: 'map', type: 'builtIn' },
  2744. { name: 'write', shortName: 'w', type: 'builtIn' },
  2745. { name: 'undo', shortName: 'u', type: 'builtIn' },
  2746. { name: 'redo', shortName: 'red', type: 'builtIn' },
  2747. { name: 'substitute', shortName: 's', type: 'builtIn'},
  2748. { name: 'nohlsearch', shortName: 'noh', type: 'builtIn'},
  2749. { name: 'delmarks', shortName: 'delm', type: 'builtin'}
  2750. ];
  2751. Vim.ExCommandDispatcher = function() {
  2752. this.buildCommandMap_();
  2753. };
  2754. Vim.ExCommandDispatcher.prototype = {
  2755. processCommand: function(cm, input) {
  2756. var inputStream = new CodeMirror.StringStream(input);
  2757. var params = {};
  2758. params.input = input;
  2759. try {
  2760. this.parseInput_(cm, inputStream, params);
  2761. } catch(e) {
  2762. showConfirm(cm, e);
  2763. return;
  2764. }
  2765. var commandName;
  2766. if (!params.commandName) {
  2767. // If only a line range is defined, move to the line.
  2768. if (params.line !== undefined) {
  2769. commandName = 'move';
  2770. }
  2771. } else {
  2772. var command = this.matchCommand_(params.commandName);
  2773. if (command) {
  2774. commandName = command.name;
  2775. this.parseCommandArgs_(inputStream, params, command);
  2776. if (command.type == 'exToKey') {
  2777. // Handle Ex to Key mapping.
  2778. for (var i = 0; i < command.toKeys.length; i++) {
  2779. vim.handleKey(cm, command.toKeys[i]);
  2780. }
  2781. return;
  2782. } else if (command.type == 'exToEx') {
  2783. // Handle Ex to Ex mapping.
  2784. this.processCommand(cm, command.toInput);
  2785. return;
  2786. }
  2787. }
  2788. }
  2789. if (!commandName) {
  2790. showConfirm(cm, 'Not an editor command ":' + input + '"');
  2791. return;
  2792. }
  2793. exCommands[commandName](cm, params);
  2794. },
  2795. parseInput_: function(cm, inputStream, result) {
  2796. inputStream.eatWhile(':');
  2797. // Parse range.
  2798. if (inputStream.eat('%')) {
  2799. result.line = cm.firstLine();
  2800. result.lineEnd = cm.lastLine();
  2801. } else {
  2802. result.line = this.parseLineSpec_(cm, inputStream);
  2803. if (result.line !== undefined && inputStream.eat(',')) {
  2804. result.lineEnd = this.parseLineSpec_(cm, inputStream);
  2805. }
  2806. }
  2807. // Parse command name.
  2808. var commandMatch = inputStream.match(/^(\w+)/);
  2809. if (commandMatch) {
  2810. result.commandName = commandMatch[1];
  2811. } else {
  2812. result.commandName = inputStream.match(/.*/)[0];
  2813. }
  2814. return result;
  2815. },
  2816. parseLineSpec_: function(cm, inputStream) {
  2817. var numberMatch = inputStream.match(/^(\d+)/);
  2818. if (numberMatch) {
  2819. return parseInt(numberMatch[1], 10) - 1;
  2820. }
  2821. switch (inputStream.next()) {
  2822. case '.':
  2823. return cm.getCursor().line;
  2824. case '$':
  2825. return cm.lastLine();
  2826. case '\'':
  2827. var mark = getVimState(cm).marks[inputStream.next()];
  2828. if (mark && mark.find()) {
  2829. return mark.find().line;
  2830. } else {
  2831. throw "Mark not set";
  2832. }
  2833. break;
  2834. default:
  2835. inputStream.backUp(1);
  2836. return cm.getCursor().line;
  2837. }
  2838. },
  2839. parseCommandArgs_: function(inputStream, params, command) {
  2840. if (inputStream.eol()) {
  2841. return;
  2842. }
  2843. params.argString = inputStream.match(/.*/)[0];
  2844. // Parse command-line arguments
  2845. var delim = command.argDelimiter || /\s+/;
  2846. var args = trim(params.argString).split(delim);
  2847. if (args.length && args[0]) {
  2848. params.args = args;
  2849. }
  2850. },
  2851. matchCommand_: function(commandName) {
  2852. // Return the command in the command map that matches the shortest
  2853. // prefix of the passed in command name. The match is guaranteed to be
  2854. // unambiguous if the defaultExCommandMap's shortNames are set up
  2855. // correctly. (see @code{defaultExCommandMap}).
  2856. for (var i = commandName.length; i > 0; i--) {
  2857. var prefix = commandName.substring(0, i);
  2858. if (this.commandMap_[prefix]) {
  2859. var command = this.commandMap_[prefix];
  2860. if (command.name.indexOf(commandName) === 0) {
  2861. return command;
  2862. }
  2863. }
  2864. }
  2865. return null;
  2866. },
  2867. buildCommandMap_: function() {
  2868. this.commandMap_ = {};
  2869. for (var i = 0; i < defaultExCommandMap.length; i++) {
  2870. var command = defaultExCommandMap[i];
  2871. var key = command.shortName || command.name;
  2872. this.commandMap_[key] = command;
  2873. }
  2874. },
  2875. map: function(lhs, rhs) {
  2876. if (lhs != ':' && lhs.charAt(0) == ':') {
  2877. var commandName = lhs.substring(1);
  2878. if (rhs != ':' && rhs.charAt(0) == ':') {
  2879. // Ex to Ex mapping
  2880. this.commandMap_[commandName] = {
  2881. name: commandName,
  2882. type: 'exToEx',
  2883. toInput: rhs.substring(1)
  2884. };
  2885. } else {
  2886. // Ex to key mapping
  2887. this.commandMap_[commandName] = {
  2888. name: commandName,
  2889. type: 'exToKey',
  2890. toKeys: parseKeyString(rhs)
  2891. };
  2892. }
  2893. } else {
  2894. if (rhs != ':' && rhs.charAt(0) == ':') {
  2895. // Key to Ex mapping.
  2896. defaultKeymap.unshift({
  2897. keys: parseKeyString(lhs),
  2898. type: 'keyToEx',
  2899. exArgs: { input: rhs.substring(1) }});
  2900. } else {
  2901. // Key to key mapping
  2902. defaultKeymap.unshift({
  2903. keys: parseKeyString(lhs),
  2904. type: 'keyToKey',
  2905. toKeys: parseKeyString(rhs)
  2906. });
  2907. }
  2908. }
  2909. }
  2910. };
  2911. // Converts a key string sequence of the form a<C-w>bd<Left> into Vim's
  2912. // keymap representation.
  2913. function parseKeyString(str) {
  2914. var key, match;
  2915. var keys = [];
  2916. while (str) {
  2917. match = (/<\w+-.+?>|<\w+>|./).exec(str);
  2918. if(match === null)break;
  2919. key = match[0];
  2920. str = str.substring(match.index + key.length);
  2921. keys.push(key);
  2922. }
  2923. return keys;
  2924. }
  2925. var exCommands = {
  2926. map: function(cm, params) {
  2927. var mapArgs = params.args;
  2928. if (!mapArgs || mapArgs.length < 2) {
  2929. if (cm) {
  2930. showConfirm(cm, 'Invalid mapping: ' + params.input);
  2931. }
  2932. return;
  2933. }
  2934. exCommandDispatcher.map(mapArgs[0], mapArgs[1], cm);
  2935. },
  2936. move: function(cm, params) {
  2937. commandDispatcher.processCommand(cm, getVimState(cm), {
  2938. type: 'motion',
  2939. motion: 'moveToLineOrEdgeOfDocument',
  2940. motionArgs: { forward: false, explicitRepeat: true,
  2941. linewise: true },
  2942. repeatOverride: params.line+1});
  2943. },
  2944. substitute: function(cm, params) {
  2945. var argString = params.argString;
  2946. var slashes = findUnescapedSlashes(argString);
  2947. if (slashes[0] !== 0) {
  2948. showConfirm(cm, 'Substitutions should be of the form ' +
  2949. ':s/pattern/replace/');
  2950. return;
  2951. }
  2952. var regexPart = argString.substring(slashes[0] + 1, slashes[1]);
  2953. var replacePart = '';
  2954. var flagsPart;
  2955. var count;
  2956. if (slashes[1]) {
  2957. replacePart = argString.substring(slashes[1] + 1, slashes[2]);
  2958. }
  2959. if (slashes[2]) {
  2960. // After the 3rd slash, we can have flags followed by a space followed
  2961. // by count.
  2962. var trailing = argString.substring(slashes[2] + 1).split(' ');
  2963. flagsPart = trailing[0];
  2964. count = parseInt(trailing[1]);
  2965. }
  2966. if (flagsPart) {
  2967. regexPart = regexPart + '/' + flagsPart;
  2968. }
  2969. if (regexPart) {
  2970. // If regex part is empty, then use the previous query. Otherwise use
  2971. // the regex part as the new query.
  2972. try {
  2973. updateSearchQuery(cm, regexPart, true /** ignoreCase */,
  2974. true /** smartCase */);
  2975. } catch (e) {
  2976. showConfirm(cm, 'Invalid regex: ' + regexPart);
  2977. return;
  2978. }
  2979. }
  2980. var state = getSearchState(cm);
  2981. var query = state.getQuery();
  2982. var lineStart = params.line || cm.firstLine();
  2983. var lineEnd = params.lineEnd || lineStart;
  2984. if (count) {
  2985. lineStart = lineEnd;
  2986. lineEnd = lineStart + count - 1;
  2987. }
  2988. var startPos = clipCursorToContent(cm, { line: lineStart, ch: 0 });
  2989. function doReplace() {
  2990. for (var cursor = cm.getSearchCursor(query, startPos);
  2991. cursor.findNext() &&
  2992. isInRange(cursor.from(), lineStart, lineEnd);) {
  2993. var text = cm.getRange(cursor.from(), cursor.to());
  2994. var newText = text.replace(query, replacePart);
  2995. cursor.replace(newText);
  2996. }
  2997. var vim = getVimState(cm);
  2998. if (vim.visualMode) {
  2999. exitVisualMode(cm, vim);
  3000. }
  3001. }
  3002. cm.operation(doReplace);
  3003. },
  3004. redo: CodeMirror.commands.redo,
  3005. undo: CodeMirror.commands.undo,
  3006. write: function(cm) {
  3007. if (CodeMirror.commands.save) {
  3008. // If a save command is defined, call it.
  3009. CodeMirror.commands.save(cm);
  3010. } else {
  3011. // Saves to text area if no save command is defined.
  3012. cm.save();
  3013. }
  3014. },
  3015. nohlsearch: function(cm) {
  3016. clearSearchHighlight(cm);
  3017. },
  3018. delmarks: function(cm, params) {
  3019. if (!params.argString || !params.argString.trim()) {
  3020. showConfirm(cm, 'Argument required');
  3021. return;
  3022. }
  3023. var state = getVimState(cm);
  3024. var stream = new CodeMirror.StringStream(params.argString.trim());
  3025. while (!stream.eol()) {
  3026. stream.eatSpace();
  3027. // Record the streams position at the beginning of the loop for use
  3028. // in error messages.
  3029. var count = stream.pos;
  3030. if (!stream.match(/[a-zA-Z]/, false)) {
  3031. showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
  3032. return;
  3033. }
  3034. var sym = stream.next();
  3035. // Check if this symbol is part of a range
  3036. if (stream.match('-', true)) {
  3037. // This symbol is part of a range.
  3038. // The range must terminate at an alphabetic character.
  3039. if (!stream.match(/[a-zA-Z]/, false)) {
  3040. showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
  3041. return;
  3042. }
  3043. var startMark = sym;
  3044. var finishMark = stream.next();
  3045. // The range must terminate at an alphabetic character which
  3046. // shares the same case as the start of the range.
  3047. if (isLowerCase(startMark) && isLowerCase(finishMark) ||
  3048. isUpperCase(startMark) && isUpperCase(finishMark)) {
  3049. var start = startMark.charCodeAt(0);
  3050. var finish = finishMark.charCodeAt(0);
  3051. if (start >= finish) {
  3052. showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
  3053. return;
  3054. }
  3055. // Because marks are always ASCII values, and we have
  3056. // determined that they are the same case, we can use
  3057. // their char codes to iterate through the defined range.
  3058. for (var j = 0; j <= finish - start; j++) {
  3059. var mark = String.fromCharCode(start + j);
  3060. delete state.marks[mark];
  3061. }
  3062. } else {
  3063. showConfirm(cm, 'Invalid argument: ' + startMark + "-");
  3064. return;
  3065. }
  3066. } else {
  3067. // This symbol is a valid mark, and is not part of a range.
  3068. delete state.marks[sym];
  3069. }
  3070. }
  3071. }
  3072. };
  3073. var exCommandDispatcher = new Vim.ExCommandDispatcher();
  3074. // Register Vim with CodeMirror
  3075. function buildVimKeyMap() {
  3076. /**
  3077. * Handle the raw key event from CodeMirror. Translate the
  3078. * Shift + key modifier to the resulting letter, while preserving other
  3079. * modifers.
  3080. */
  3081. // TODO: Figure out a way to catch capslock.
  3082. function cmKeyToVimKey(key, modifier) {
  3083. var vimKey = key;
  3084. if (isUpperCase(vimKey)) {
  3085. // Convert to lower case if shift is not the modifier since the key
  3086. // we get from CodeMirror is always upper case.
  3087. if (modifier == 'Shift') {
  3088. modifier = null;
  3089. }
  3090. else {
  3091. vimKey = vimKey.toLowerCase();
  3092. }
  3093. }
  3094. if (modifier) {
  3095. // Vim will parse modifier+key combination as a single key.
  3096. vimKey = modifier.charAt(0) + '-' + vimKey;
  3097. }
  3098. var specialKey = ({Enter:'CR',Backspace:'BS',Delete:'Del'})[vimKey];
  3099. vimKey = specialKey ? specialKey : vimKey;
  3100. vimKey = vimKey.length > 1 ? '<'+ vimKey + '>' : vimKey;
  3101. return vimKey;
  3102. }
  3103. // Closure to bind CodeMirror, key, modifier.
  3104. function keyMapper(vimKey) {
  3105. return function(cm) {
  3106. vim.handleKey(cm, vimKey);
  3107. };
  3108. }
  3109. var modifiers = ['Shift', 'Ctrl'];
  3110. var cmToVimKeymap = {
  3111. 'nofallthrough': true,
  3112. 'style': 'fat-cursor'
  3113. };
  3114. function bindKeys(keys, modifier) {
  3115. for (var i = 0; i < keys.length; i++) {
  3116. var key = keys[i];
  3117. if (!modifier && inArray(key, specialSymbols)) {
  3118. // Wrap special symbols with '' because that's how CodeMirror binds
  3119. // them.
  3120. key = "'" + key + "'";
  3121. }
  3122. var vimKey = cmKeyToVimKey(keys[i], modifier);
  3123. var cmKey = modifier ? modifier + '-' + key : key;
  3124. cmToVimKeymap[cmKey] = keyMapper(vimKey);
  3125. }
  3126. }
  3127. bindKeys(upperCaseAlphabet);
  3128. bindKeys(upperCaseAlphabet, 'Shift');
  3129. bindKeys(upperCaseAlphabet, 'Ctrl');
  3130. bindKeys(specialSymbols);
  3131. bindKeys(specialSymbols, 'Ctrl');
  3132. bindKeys(numbers);
  3133. bindKeys(numbers, 'Ctrl');
  3134. bindKeys(specialKeys);
  3135. bindKeys(specialKeys, 'Ctrl');
  3136. return cmToVimKeymap;
  3137. }
  3138. CodeMirror.keyMap.vim = buildVimKeyMap();
  3139. function exitInsertMode(cm) {
  3140. cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1, true);
  3141. cm.setOption('keyMap', 'vim');
  3142. }
  3143. CodeMirror.keyMap['vim-insert'] = {
  3144. // TODO: override navigation keys so that Esc will cancel automatic
  3145. // indentation from o, O, i_<CR>
  3146. 'Esc': exitInsertMode,
  3147. 'Ctrl-[': exitInsertMode,
  3148. 'Ctrl-C': exitInsertMode,
  3149. 'Ctrl-N': 'autocomplete',
  3150. 'Ctrl-P': 'autocomplete',
  3151. 'Enter': function(cm) {
  3152. var fn = CodeMirror.commands.newlineAndIndentContinueComment ||
  3153. CodeMirror.commands.newlineAndIndent;
  3154. fn(cm);
  3155. },
  3156. fallthrough: ['default']
  3157. };
  3158. function parseRegisterToKeyBuffer(macroModeState, registerName) {
  3159. var match, key;
  3160. var register = getVimGlobalState().registerController.getRegister(registerName);
  3161. var text = register.toString();
  3162. var macroKeyBuffer = macroModeState.macroKeyBuffer;
  3163. emptyMacroKeyBuffer(macroModeState);
  3164. do {
  3165. match = text.match(/<\w+-.+>|<\w+>|.|\n/);
  3166. if(match === null)break;
  3167. key = match[0];
  3168. text = text.substring(match.index + key.length);
  3169. macroKeyBuffer.push(key);
  3170. } while (text);
  3171. return macroKeyBuffer;
  3172. }
  3173. function parseKeyBufferToRegister(registerName, keyBuffer) {
  3174. var text = keyBuffer.join('');
  3175. getVimGlobalState().registerController.setRegisterText(registerName, text);
  3176. }
  3177. function emptyMacroKeyBuffer(macroModeState) {
  3178. if(macroModeState.isMacroPlaying)return;
  3179. var macroKeyBuffer = macroModeState.macroKeyBuffer;
  3180. macroKeyBuffer.length = 0;
  3181. }
  3182. function executeMacroKeyBuffer(cm, macroModeState, keyBuffer) {
  3183. macroModeState.isMacroPlaying = true;
  3184. for (var i = 0, len = keyBuffer.length; i < len; i++) {
  3185. CodeMirror.Vim.handleKey(cm, keyBuffer[i]);
  3186. };
  3187. macroModeState.isMacroPlaying = false;
  3188. }
  3189. function logKey(macroModeState, key) {
  3190. if(macroModeState.isMacroPlaying)return;
  3191. var macroKeyBuffer = macroModeState.macroKeyBuffer;
  3192. macroKeyBuffer.push(key);
  3193. }
  3194. function exitReplaceMode(cm) {
  3195. cm.toggleOverwrite();
  3196. cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1, true);
  3197. cm.setOption('keyMap', 'vim');
  3198. }
  3199. CodeMirror.keyMap['vim-replace'] = {
  3200. 'Esc': exitReplaceMode,
  3201. 'Ctrl-[': exitReplaceMode,
  3202. 'Ctrl-C': exitReplaceMode,
  3203. 'Backspace': 'goCharLeft',
  3204. fallthrough: ['default']
  3205. };
  3206. return vimApi;
  3207. };
  3208. // Initialize Vim and make it available as an API.
  3209. var vim = Vim();
  3210. CodeMirror.Vim = vim;
  3211. }
  3212. )();