Vimify Glitch.com

vim keybindings for Glitch.com

当前为 2018-09-19 提交的版本,查看 最新版本

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