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

5546 lines
212 KiB

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