diff --git a/media/editors/codemirror/addon/comment/comment.js b/media/editors/codemirror/addon/comment/comment.js
index d7f569cc00534..2dd114d332dc9 100644
--- a/media/editors/codemirror/addon/comment/comment.js
+++ b/media/editors/codemirror/addon/comment/comment.js
@@ -109,7 +109,7 @@
CodeMirror.defineExtension("uncomment", function(from, to, options) {
if (!options) options = noOptions;
var self = this, mode = self.getModeAt(from);
- var end = Math.min(to.line, self.lastLine()), start = Math.min(from.line, end);
+ var end = Math.min(to.ch != 0 || to.line == from.line ? to.line : to.line - 1, self.lastLine()), start = Math.min(from.line, end);
// Try finding line comments
var lineString = options.lineComment || mode.lineComment, lines = [];
diff --git a/media/editors/codemirror/addon/comment/index.html b/media/editors/codemirror/addon/comment/index.html
new file mode 100644
index 0000000000000..2efb97f319a35
--- /dev/null
+++ b/media/editors/codemirror/addon/comment/index.html
@@ -0,0 +1 @@
+
diff --git a/media/editors/codemirror/addon/dialog/dialog.js b/media/editors/codemirror/addon/dialog/dialog.js
index 35a6103c2d786..5a88d99e64f8d 100644
--- a/media/editors/codemirror/addon/dialog/dialog.js
+++ b/media/editors/codemirror/addon/dialog/dialog.js
@@ -56,7 +56,10 @@
var inp = dialog.getElementsByTagName("input")[0], button;
if (inp) {
- if (options.value) inp.value = options.value;
+ if (options.value) {
+ inp.value = options.value;
+ inp.select();
+ }
if (options.onInput)
CodeMirror.on(inp, "input", function(e) { options.onInput(e, inp.value, close);});
diff --git a/media/editors/codemirror/addon/dialog/index.html b/media/editors/codemirror/addon/dialog/index.html
new file mode 100644
index 0000000000000..2efb97f319a35
--- /dev/null
+++ b/media/editors/codemirror/addon/dialog/index.html
@@ -0,0 +1 @@
+
diff --git a/media/editors/codemirror/addon/display/index.html b/media/editors/codemirror/addon/display/index.html
new file mode 100644
index 0000000000000..2efb97f319a35
--- /dev/null
+++ b/media/editors/codemirror/addon/display/index.html
@@ -0,0 +1 @@
+
diff --git a/media/editors/codemirror/addon/edit/closebrackets.js b/media/editors/codemirror/addon/edit/closebrackets.js
index 1a04f3664ef07..f6b42f02d3b34 100644
--- a/media/editors/codemirror/addon/edit/closebrackets.js
+++ b/media/editors/codemirror/addon/edit/closebrackets.js
@@ -71,31 +71,32 @@
};
var closingBrackets = "";
for (var i = 0; i < pairs.length; i += 2) (function(left, right) {
- if (left != right) closingBrackets += right;
+ closingBrackets += right;
map["'" + left + "'"] = function(cm) {
if (cm.getOption("disableInput")) return CodeMirror.Pass;
var ranges = cm.listSelections(), type, next;
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i], cur = range.head, curType;
var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1));
- if (!range.empty())
+ if (!range.empty()) {
curType = "surround";
- else if (left == right && next == right) {
+ } else if (left == right && next == right) {
if (cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == left + left + left)
curType = "skipThree";
else
curType = "skip";
} else if (left == right && cur.ch > 1 &&
cm.getRange(Pos(cur.line, cur.ch - 2), cur) == left + left &&
- (cur.ch <= 2 || cm.getRange(Pos(cur.line, cur.ch - 3), Pos(cur.line, cur.ch - 2)) != left))
+ (cur.ch <= 2 || cm.getRange(Pos(cur.line, cur.ch - 3), Pos(cur.line, cur.ch - 2)) != left)) {
curType = "addFour";
- else if (left == '"' || left == "'") {
+ } else if (left == '"' || left == "'") {
if (!CodeMirror.isWordChar(next) && enteringString(cm, cur, left)) curType = "both";
else return CodeMirror.Pass;
- } else if (cm.getLine(cur.line).length == cur.ch || closingBrackets.indexOf(next) >= 0 || SPACE_CHAR_REGEX.test(next))
+ } else if (cm.getLine(cur.line).length == cur.ch || closingBrackets.indexOf(next) >= 0 || SPACE_CHAR_REGEX.test(next)) {
curType = "both";
- else
+ } else {
return CodeMirror.Pass;
+ }
if (!type) type = curType;
else if (type != curType) return CodeMirror.Pass;
}
diff --git a/media/editors/codemirror/addon/edit/continuelist.js b/media/editors/codemirror/addon/edit/continuelist.js
index 8cee761aeeae9..9ad0a98fa097e 100644
--- a/media/editors/codemirror/addon/edit/continuelist.js
+++ b/media/editors/codemirror/addon/edit/continuelist.js
@@ -11,7 +11,8 @@
})(function(CodeMirror) {
"use strict";
- var listRE = /^(\s*)([*+-]|(\d+)\.)(\s+)/,
+ var listRE = /^(\s*)([> ]+|[*+-]|(\d+)\.)(\s+)/,
+ emptyListRE = /^(\s*)([> ]+|[*+-]|(\d+)\.)(\s*)$/,
unorderedBullets = "*+-";
CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) {
@@ -19,18 +20,30 @@
var ranges = cm.listSelections(), replacements = [];
for (var i = 0; i < ranges.length; i++) {
var pos = ranges[i].head, match;
- var inList = cm.getStateAfter(pos.line).list !== false;
+ var eolState = cm.getStateAfter(pos.line);
+ var inList = eolState.list !== false;
+ var inQuote = eolState.quote !== false;
- if (!ranges[i].empty() || !inList || !(match = cm.getLine(pos.line).match(listRE))) {
+ if (!ranges[i].empty() || (!inList && !inQuote) || !(match = cm.getLine(pos.line).match(listRE))) {
cm.execCommand("newlineAndIndent");
return;
}
- var indent = match[1], after = match[4];
- var bullet = unorderedBullets.indexOf(match[2]) >= 0
- ? match[2]
- : (parseInt(match[3], 10) + 1) + ".";
+ if (cm.getLine(pos.line).match(emptyListRE)) {
+ cm.replaceRange("", {
+ line: pos.line, ch: 0
+ }, {
+ line: pos.line, ch: pos.ch + 1
+ });
+ replacements[i] = "\n";
- replacements[i] = "\n" + indent + bullet + after;
+ } else {
+ var indent = match[1], after = match[4];
+ var bullet = unorderedBullets.indexOf(match[2]) >= 0 || match[2].indexOf(">") >= 0
+ ? match[2]
+ : (parseInt(match[3], 10) + 1) + ".";
+
+ replacements[i] = "\n" + indent + bullet + after;
+ }
}
cm.replaceSelections(replacements);
diff --git a/media/editors/codemirror/addon/edit/index.html b/media/editors/codemirror/addon/edit/index.html
new file mode 100644
index 0000000000000..2efb97f319a35
--- /dev/null
+++ b/media/editors/codemirror/addon/edit/index.html
@@ -0,0 +1 @@
+
diff --git a/media/editors/codemirror/addon/fold/index.html b/media/editors/codemirror/addon/fold/index.html
new file mode 100644
index 0000000000000..2efb97f319a35
--- /dev/null
+++ b/media/editors/codemirror/addon/fold/index.html
@@ -0,0 +1 @@
+
diff --git a/media/editors/codemirror/addon/hint/index.html b/media/editors/codemirror/addon/hint/index.html
new file mode 100644
index 0000000000000..2efb97f319a35
--- /dev/null
+++ b/media/editors/codemirror/addon/hint/index.html
@@ -0,0 +1 @@
+
diff --git a/media/editors/codemirror/addon/hint/javascript-hint.js b/media/editors/codemirror/addon/hint/javascript-hint.js
index c7292468a0094..f6c2440062289 100644
--- a/media/editors/codemirror/addon/hint/javascript-hint.js
+++ b/media/editors/codemirror/addon/hint/javascript-hint.js
@@ -93,7 +93,7 @@
"if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes").split(" ");
function getCompletions(token, context, keywords, options) {
- var found = [], start = token.string;
+ var found = [], start = token.string, global = options && options.globalScope || window;
function maybeAdd(str) {
if (str.lastIndexOf(start, 0) == 0 && !arrayContains(found, str)) found.push(str);
}
@@ -112,28 +112,28 @@
if (options && options.additionalContext)
base = options.additionalContext[obj.string];
if (!options || options.useGlobalScope !== false)
- base = base || window[obj.string];
+ base = base || global[obj.string];
} else if (obj.type == "string") {
base = "";
} else if (obj.type == "atom") {
base = 1;
} else if (obj.type == "function") {
- if (window.jQuery != null && (obj.string == '$' || obj.string == 'jQuery') &&
- (typeof window.jQuery == 'function'))
- base = window.jQuery();
- else if (window._ != null && (obj.string == '_') && (typeof window._ == 'function'))
- base = window._();
+ if (global.jQuery != null && (obj.string == '$' || obj.string == 'jQuery') &&
+ (typeof global.jQuery == 'function'))
+ base = global.jQuery();
+ else if (global._ != null && (obj.string == '_') && (typeof global._ == 'function'))
+ base = global._();
}
while (base != null && context.length)
base = base[context.pop().string];
if (base != null) gatherCompletions(base);
} else {
- // If not, just look in the window object and any local scope
+ // If not, just look in the global object and any local scope
// (reading into JS mode internals to get at the local and global variables)
for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);
for (var v = token.state.globalVars; v; v = v.next) maybeAdd(v.name);
if (!options || options.useGlobalScope !== false)
- gatherCompletions(window);
+ gatherCompletions(global);
forEach(keywords, maybeAdd);
}
return found;
diff --git a/media/editors/codemirror/addon/hint/sql-hint.js b/media/editors/codemirror/addon/hint/sql-hint.js
index 20653b5318f28..c2b511fa2fc5e 100644
--- a/media/editors/codemirror/addon/hint/sql-hint.js
+++ b/media/editors/codemirror/addon/hint/sql-hint.js
@@ -12,6 +12,7 @@
"use strict";
var tables;
+ var defaultTable;
var keywords;
var CONS = {
QUERY_DIV: ";",
@@ -43,18 +44,55 @@
}
}
- function columnCompletion(result, editor) {
+ function nameCompletion(result, editor) {
var cur = editor.getCursor();
var token = editor.getTokenAt(cur);
+ var useBacktick = (token.string.charAt(0) == "`");
var string = token.string.substr(1);
- var prevCur = Pos(cur.line, token.start);
- var table = editor.getTokenAt(prevCur).string;
- if (!tables.hasOwnProperty(table))
- table = findTableByAlias(table, editor);
- var columns = tables[table];
- if (!columns) return;
-
- addMatches(result, string, columns, function(w) {return "." + w;});
+ var prevToken = editor.getTokenAt(Pos(cur.line, token.start));
+ if (token.string.charAt(0) == "." || prevToken.string == "."){
+ //Suggest colunm names
+ if (prevToken.string == ".") {
+ var prevToken = editor.getTokenAt(Pos(cur.line, token.start - 1));
+ }
+ var table = prevToken.string;
+ //Check if backtick is used in table name. If yes, use it for columns too.
+ var useBacktickTable = false;
+ if (table.match(/`/g)) {
+ useBacktickTable = true;
+ table = table.replace(/`/g, "");
+ }
+ //Check if table is available. If not, find table by Alias
+ if (!tables.hasOwnProperty(table))
+ table = findTableByAlias(table, editor);
+ var columns = tables[table];
+ if (!columns) return;
+
+ if (useBacktick) {
+ addMatches(result, string, columns, function(w) {return "`" + w + "`";});
+ }
+ else if(useBacktickTable) {
+ addMatches(result, string, columns, function(w) {return ".`" + w + "`";});
+ }
+ else {
+ addMatches(result, string, columns, function(w) {return "." + w;});
+ }
+ }
+ else {
+ //Suggest table names or colums in defaultTable
+ while (token.start && string.charAt(0) == ".") {
+ token = editor.getTokenAt(Pos(cur.line, token.start - 1));
+ string = token.string + string;
+ }
+ if (useBacktick) {
+ addMatches(result, string, tables, function(w) {return "`" + w + "`";});
+ addMatches(result, string, defaultTable, function(w) {return "`" + w + "`";});
+ }
+ else {
+ addMatches(result, string, tables, function(w) {return w;});
+ addMatches(result, string, defaultTable, function(w) {return w;});
+ }
+ }
}
function eachWord(lineText, f) {
@@ -128,11 +166,14 @@
CodeMirror.registerHelper("hint", "sql", function(editor, options) {
tables = (options && options.tables) || {};
+ var defaultTableName = options && options.defaultTable;
+ defaultTable = (defaultTableName && tables[defaultTableName] || []);
keywords = keywords || getKeywords(editor);
+
var cur = editor.getCursor();
var result = [];
var token = editor.getTokenAt(cur), start, end, search;
- if (token.string.match(/^[.\w@]\w*$/)) {
+ if (token.string.match(/^[.`\w@]\w*$/)) {
search = token.string;
start = token.start;
end = token.end;
@@ -140,18 +181,11 @@
start = end = cur.ch;
search = "";
}
- if (search.charAt(0) == ".") {
- columnCompletion(result, editor);
- if (!result.length) {
- while (start && search.charAt(0) == ".") {
- token = editor.getTokenAt(Pos(cur.line, token.start - 1));
- start = token.start;
- search = token.string + search;
- }
- addMatches(result, search, tables, function(w) {return w;});
- }
+ if (search.charAt(0) == "." || search.charAt(0) == "`") {
+ nameCompletion(result, editor);
} else {
addMatches(result, search, tables, function(w) {return w;});
+ addMatches(result, search, defaultTable, function(w) {return w;});
addMatches(result, search, keywords, function(w) {return w.toUpperCase();});
}
diff --git a/media/editors/codemirror/addon/hint/xml-hint.js b/media/editors/codemirror/addon/hint/xml-hint.js
index e31b09b5fc8ec..cc95b20f34452 100644
--- a/media/editors/codemirror/addon/hint/xml-hint.js
+++ b/media/editors/codemirror/addon/hint/xml-hint.js
@@ -18,10 +18,17 @@
var quote = (options && options.quoteChar) || '"';
if (!tags) return;
var cur = cm.getCursor(), token = cm.getTokenAt(cur);
+ if (/^<\/?$/.test(token.string) && token.end == cur.ch) {
+ var nextToken = cm.getTokenAt(Pos(cur.line, cur.ch + 1));
+ if (nextToken.start == cur.ch && /\btag\b/.test(nextToken.type))
+ token = nextToken;
+ }
var inner = CodeMirror.innerMode(cm.getMode(), token.state);
if (inner.mode.name != "xml") return;
var result = [], replaceToken = false, prefix;
- var tag = /\btag\b/.test(token.type), tagName = tag && /^\w/.test(token.string), tagStart;
+ var tag = /\btag\b/.test(token.type) && !/>$/.test(token.string);
+ var tagName = tag && /^\w/.test(token.string), tagStart;
+
if (tagName) {
var before = cm.getLine(cur.line).slice(Math.max(0, token.start - 2), token.start);
var tagType = /<\/$/.test(before) ? "close" : /<$/.test(before) ? "open" : null;
@@ -31,6 +38,7 @@
} else if (tag && token.string == "") {
tagType = "close";
}
+
if (!tag && !inner.state.tagName || tagType) {
if (tagName)
prefix = token.string;
diff --git a/media/editors/codemirror/addon/index.html b/media/editors/codemirror/addon/index.html
new file mode 100644
index 0000000000000..2efb97f319a35
--- /dev/null
+++ b/media/editors/codemirror/addon/index.html
@@ -0,0 +1 @@
+
diff --git a/media/editors/codemirror/addon/lint/index.html b/media/editors/codemirror/addon/lint/index.html
new file mode 100644
index 0000000000000..2efb97f319a35
--- /dev/null
+++ b/media/editors/codemirror/addon/lint/index.html
@@ -0,0 +1 @@
+
diff --git a/media/editors/codemirror/addon/lint/lint.js b/media/editors/codemirror/addon/lint/lint.js
index a87e70c09eae2..66f187e22eac8 100644
--- a/media/editors/codemirror/addon/lint/lint.js
+++ b/media/editors/codemirror/addon/lint/lint.js
@@ -118,10 +118,11 @@
function startLinting(cm) {
var state = cm.state.lint, options = state.options;
+ var passOptions = options.options || options; // Support deprecated passing of `options` property in options
if (options.async)
- options.getAnnotations(cm, updateLinting, options);
+ options.getAnnotations(cm.getValue(), updateLinting, passOptions, cm);
else
- updateLinting(cm, options.getAnnotations(cm.getValue(), options.options));
+ updateLinting(cm, options.getAnnotations(cm.getValue(), passOptions, cm));
}
function updateLinting(cm, annotationsNotSorted) {
@@ -170,20 +171,14 @@
showTooltipFor(e, annotationTooltip(ann), target);
}
- // When the mouseover fires, the cursor might not actually be over
- // the character itself yet. These pairs of x,y offsets are used to
- // probe a few nearby points when no suitable marked range is found.
- var nearby = [0, 0, 0, 5, 0, -5, 5, 0, -5, 0];
-
function onMouseOver(cm, e) {
- if (!/\bCodeMirror-lint-mark-/.test((e.target || e.srcElement).className)) return;
- for (var i = 0; i < nearby.length; i += 2) {
- var spans = cm.findMarksAt(cm.coordsChar({left: e.clientX + nearby[i],
- top: e.clientY + nearby[i + 1]}, "client"));
- for (var j = 0; j < spans.length; ++j) {
- var span = spans[j], ann = span.__annotation;
- if (ann) return popupSpanTooltip(ann, e);
- }
+ var target = e.target || e.srcElement;
+ if (!/\bCodeMirror-lint-mark-/.test(target.className)) return;
+ var box = target.getBoundingClientRect(), x = (box.left + box.right) / 2, y = (box.top + box.bottom) / 2;
+ var spans = cm.findMarksAt(cm.coordsChar({left: x, top: y}, "client"));
+ for (var i = 0; i < spans.length; ++i) {
+ var ann = spans[i].__annotation;
+ if (ann) return popupSpanTooltip(ann, e);
}
}
diff --git a/media/editors/codemirror/addon/merge/index.html b/media/editors/codemirror/addon/merge/index.html
new file mode 100644
index 0000000000000..2efb97f319a35
--- /dev/null
+++ b/media/editors/codemirror/addon/merge/index.html
@@ -0,0 +1 @@
+
diff --git a/media/editors/codemirror/addon/mode/index.html b/media/editors/codemirror/addon/mode/index.html
new file mode 100644
index 0000000000000..2efb97f319a35
--- /dev/null
+++ b/media/editors/codemirror/addon/mode/index.html
@@ -0,0 +1 @@
+
diff --git a/media/editors/codemirror/addon/mode/loadmode.js b/media/editors/codemirror/addon/mode/loadmode.js
index 804215877fd0e..10117ec22f250 100644
--- a/media/editors/codemirror/addon/mode/loadmode.js
+++ b/media/editors/codemirror/addon/mode/loadmode.js
@@ -3,12 +3,12 @@
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
- mod(require("../../lib/codemirror"));
+ mod(require("../../lib/codemirror"), "cjs");
else if (typeof define == "function" && define.amd) // AMD
- define(["../../lib/codemirror"], mod);
+ define(["../../lib/codemirror"], function(CM) { mod(CM, "amd"); });
else // Plain browser env
- mod(CodeMirror);
-})(function(CodeMirror) {
+ mod(CodeMirror, "plain");
+})(function(CodeMirror, env) {
if (!CodeMirror.modeURL) CodeMirror.modeURL = "../mode/%N/%N.js";
var loading = {};
@@ -35,21 +35,24 @@
if (CodeMirror.modes.hasOwnProperty(mode)) return ensureDeps(mode, cont);
if (loading.hasOwnProperty(mode)) return loading[mode].push(cont);
- var script = document.createElement("script");
- script.src = CodeMirror.modeURL.replace(/%N/g, mode);
- var others = document.getElementsByTagName("script")[0];
- others.parentNode.insertBefore(script, others);
- var list = loading[mode] = [cont];
- var count = 0, poll = setInterval(function() {
- if (++count > 100) return clearInterval(poll);
- if (CodeMirror.modes.hasOwnProperty(mode)) {
- clearInterval(poll);
- loading[mode] = null;
+ var file = CodeMirror.modeURL.replace(/%N/g, mode);
+ if (env == "plain") {
+ var script = document.createElement("script");
+ script.src = file;
+ var others = document.getElementsByTagName("script")[0];
+ var list = loading[mode] = [cont];
+ CodeMirror.on(script, "load", function() {
ensureDeps(mode, function() {
for (var i = 0; i < list.length; ++i) list[i]();
});
- }
- }, 200);
+ });
+ others.parentNode.insertBefore(script, others);
+ } else if (env == "cjs") {
+ require(file);
+ cont();
+ } else if (env == "amd") {
+ requirejs([file], cont);
+ }
};
CodeMirror.autoLoadMode = function(instance, mode) {
diff --git a/media/editors/codemirror/addon/mode/overlay.js b/media/editors/codemirror/addon/mode/overlay.js
index 393054dfa4417..e1b9ed37530ad 100644
--- a/media/editors/codemirror/addon/mode/overlay.js
+++ b/media/editors/codemirror/addon/mode/overlay.js
@@ -28,7 +28,7 @@ CodeMirror.overlayMode = function(base, overlay, combine) {
overlay: CodeMirror.startState(overlay),
basePos: 0, baseCur: null,
overlayPos: 0, overlayCur: null,
- lineSeen: null
+ streamSeen: null
};
},
copyState: function(state) {
@@ -41,9 +41,9 @@ CodeMirror.overlayMode = function(base, overlay, combine) {
},
token: function(stream, state) {
- if (stream.sol() || stream.string != state.lineSeen ||
+ if (stream != state.streamSeen ||
Math.min(state.basePos, state.overlayPos) < stream.start) {
- state.lineSeen = stream.string;
+ state.streamSeen = stream;
state.basePos = state.overlayPos = stream.start;
}
diff --git a/media/editors/codemirror/addon/mode/simple.js b/media/editors/codemirror/addon/mode/simple.js
new file mode 100644
index 0000000000000..a4a86b9a657d2
--- /dev/null
+++ b/media/editors/codemirror/addon/mode/simple.js
@@ -0,0 +1,210 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("../../lib/codemirror"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ CodeMirror.defineSimpleMode = function(name, states, props) {
+ CodeMirror.defineMode(name, function(config) {
+ return CodeMirror.simpleMode(config, states, props);
+ });
+ };
+
+ CodeMirror.simpleMode = function(config, states) {
+ ensureState(states, "start");
+ var states_ = {}, meta = states.meta || {}, hasIndentation = false;
+ for (var state in states) if (state != meta && states.hasOwnProperty(state)) {
+ var list = states_[state] = [], orig = states[state];
+ for (var i = 0; i < orig.length; i++) {
+ var data = orig[i];
+ list.push(new Rule(data, states));
+ if (data.indent || data.dedent) hasIndentation = true;
+ }
+ }
+ var mode = {
+ startState: function() {
+ return {state: "start", pending: null,
+ local: null, localState: null,
+ indent: hasIndentation ? [] : null};
+ },
+ copyState: function(state) {
+ var s = {state: state.state, pending: state.pending,
+ local: state.local, localState: null,
+ indent: state.indent && state.indent.slice(0)};
+ if (state.localState)
+ s.localState = CodeMirror.copyState(state.local.mode, state.localState);
+ if (state.stack)
+ s.stack = state.stack.slice(0);
+ for (var pers = state.persistentStates; pers; pers = pers.next)
+ s.persistentStates = {mode: pers.mode,
+ spec: pers.spec,
+ state: pers.state == state.localState ? s.localState : CodeMirror.copyState(pers.mode, pers.state),
+ next: s.persistentStates};
+ return s;
+ },
+ token: tokenFunction(states_, config),
+ innerMode: function(state) { return state.local && {mode: state.local.mode, state: state.localState}; },
+ indent: indentFunction(states_, meta)
+ };
+ if (meta) for (var prop in meta) if (meta.hasOwnProperty(prop))
+ mode[prop] = meta[prop];
+ return mode;
+ };
+
+ function ensureState(states, name) {
+ if (!states.hasOwnProperty(name))
+ throw new Error("Undefined state " + name + "in simple mode");
+ }
+
+ function toRegex(val, caret) {
+ if (!val) return /(?:)/;
+ var flags = "";
+ if (val instanceof RegExp) {
+ if (val.ignoreCase) flags = "i";
+ val = val.source;
+ } else {
+ val = String(val);
+ }
+ return new RegExp((caret === false ? "" : "^") + "(?:" + val + ")", flags);
+ }
+
+ function asToken(val) {
+ if (!val) return null;
+ if (typeof val == "string") return val.replace(/\./g, " ");
+ var result = [];
+ for (var i = 0; i < val.length; i++)
+ result.push(val[i] && val[i].replace(/\./g, " "));
+ return result;
+ }
+
+ function Rule(data, states) {
+ if (data.next || data.push) ensureState(states, data.next || data.push);
+ this.regex = toRegex(data.regex);
+ this.token = asToken(data.token);
+ this.data = data;
+ }
+
+ function tokenFunction(states, config) {
+ return function(stream, state) {
+ if (state.pending) {
+ var pend = state.pending.shift();
+ if (state.pending.length == 0) state.pending = null;
+ stream.pos += pend.text.length;
+ return pend.token;
+ }
+
+ if (state.local) {
+ if (state.local.end && stream.match(state.local.end)) {
+ var tok = state.local.endToken || null;
+ state.local = state.localState = null;
+ return tok;
+ } else {
+ var tok = state.local.mode.token(stream, state.localState), m;
+ if (state.local.endScan && (m = state.local.endScan.exec(stream.current())))
+ stream.pos = stream.start + m.index;
+ return tok;
+ }
+ }
+
+ var curState = states[state.state];
+ for (var i = 0; i < curState.length; i++) {
+ var rule = curState[i];
+ var matches = stream.match(rule.regex);
+ if (matches) {
+ if (rule.data.next) {
+ state.state = rule.data.next;
+ } else if (rule.data.push) {
+ (state.stack || (state.stack = [])).push(state.state);
+ state.state = rule.data.push;
+ } else if (rule.data.pop && state.stack && state.stack.length) {
+ state.state = state.stack.pop();
+ }
+
+ if (rule.data.mode)
+ enterLocalMode(config, state, rule.data.mode, rule.token);
+ if (rule.data.indent)
+ state.indent.push(stream.indentation() + config.indentUnit);
+ if (rule.data.dedent)
+ state.indent.pop();
+ if (matches.length > 2) {
+ state.pending = [];
+ for (var j = 2; j < matches.length; j++)
+ if (matches[j])
+ state.pending.push({text: matches[j], token: rule.token[j - 1]});
+ stream.backUp(matches[0].length - (matches[1] ? matches[1].length : 0));
+ return rule.token[0];
+ } else if (rule.token && rule.token.join) {
+ return rule.token[0];
+ } else {
+ return rule.token;
+ }
+ }
+ }
+ stream.next();
+ return null;
+ };
+ }
+
+ function cmp(a, b) {
+ if (a === b) return true;
+ if (!a || typeof a != "object" || !b || typeof b != "object") return false;
+ var props = 0;
+ for (var prop in a) if (a.hasOwnProperty(prop)) {
+ if (!b.hasOwnProperty(prop) || !cmp(a[prop], b[prop])) return false;
+ props++;
+ }
+ for (var prop in b) if (b.hasOwnProperty(prop)) props--;
+ return props == 0;
+ }
+
+ function enterLocalMode(config, state, spec, token) {
+ var pers;
+ if (spec.persistent) for (var p = state.persistentStates; p && !pers; p = p.next)
+ if (spec.spec ? cmp(spec.spec, p.spec) : spec.mode == p.mode) pers = p;
+ var mode = pers ? pers.mode : spec.mode || CodeMirror.getMode(config, spec.spec);
+ var lState = pers ? pers.state : CodeMirror.startState(mode);
+ if (spec.persistent && !pers)
+ state.persistentStates = {mode: mode, spec: spec.spec, state: lState, next: state.persistentStates};
+
+ state.localState = lState;
+ state.local = {mode: mode,
+ end: spec.end && toRegex(spec.end),
+ endScan: spec.end && spec.forceEnd !== false && toRegex(spec.end, false),
+ endToken: token && token.join ? token[token.length - 1] : token};
+ }
+
+ function indexOf(val, arr) {
+ for (var i = 0; i < arr.length; i++) if (arr[i] === val) return true;
+ }
+
+ function indentFunction(states, meta) {
+ return function(state, textAfter, line) {
+ if (state.local && state.local.mode.indent)
+ return state.local.mode.indent(state.localState, textAfter, line);
+ if (state.indent == null || state.local || meta.dontIndentStates && indexOf(state.state, meta.dontIndentStates) > -1)
+ return CodeMirror.Pass;
+
+ var pos = state.indent.length - 1, rules = states[state.state];
+ scan: for (;;) {
+ for (var i = 0; i < rules.length; i++) {
+ var rule = rules[i], m = rule.regex.exec(textAfter);
+ if (m && m[0]) {
+ if (rule.data.dedent && rule.data.dedentIfLineStart !== false) pos--;
+ if (rule.next || rule.push) rules = states[rule.next || rule.push];
+ textAfter = textAfter.slice(m[0].length);
+ continue scan;
+ }
+ }
+ break;
+ }
+ return pos < 0 ? 0 : state.indent[pos];
+ };
+ }
+});
diff --git a/media/editors/codemirror/addon/runmode/index.html b/media/editors/codemirror/addon/runmode/index.html
new file mode 100644
index 0000000000000..2efb97f319a35
--- /dev/null
+++ b/media/editors/codemirror/addon/runmode/index.html
@@ -0,0 +1 @@
+
diff --git a/media/editors/codemirror/addon/runmode/runmode-standalone.js b/media/editors/codemirror/addon/runmode/runmode-standalone.js
index 0dd0c289b058c..f4f352c803524 100644
--- a/media/editors/codemirror/addon/runmode/runmode-standalone.js
+++ b/media/editors/codemirror/addon/runmode/runmode-standalone.js
@@ -74,7 +74,11 @@ CodeMirror.startState = function (mode, a1, a2) {
};
var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
-CodeMirror.defineMode = function (name, mode) { modes[name] = mode; };
+CodeMirror.defineMode = function (name, mode) {
+ if (arguments.length > 2)
+ mode.dependencies = Array.prototype.slice.call(arguments, 2);
+ modes[name] = mode;
+};
CodeMirror.defineMIME = function (mime, spec) { mimeModes[mime] = spec; };
CodeMirror.resolveMode = function(spec) {
if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
diff --git a/media/editors/codemirror/addon/runmode/runmode.node.js b/media/editors/codemirror/addon/runmode/runmode.node.js
index f64b8a152d3d0..8b8140b4c1ae4 100644
--- a/media/editors/codemirror/addon/runmode/runmode.node.js
+++ b/media/editors/codemirror/addon/runmode/runmode.node.js
@@ -74,10 +74,8 @@ exports.startState = function(mode, a1, a2) {
var modes = exports.modes = {}, mimeModes = exports.mimeModes = {};
exports.defineMode = function(name, mode) {
- if (arguments.length > 2) {
- mode.dependencies = [];
- for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
- }
+ if (arguments.length > 2)
+ mode.dependencies = Array.prototype.slice.call(arguments, 2);
modes[name] = mode;
};
exports.defineMIME = function(mime, spec) { mimeModes[mime] = spec; };
diff --git a/media/editors/codemirror/addon/scroll/index.html b/media/editors/codemirror/addon/scroll/index.html
new file mode 100644
index 0000000000000..2efb97f319a35
--- /dev/null
+++ b/media/editors/codemirror/addon/scroll/index.html
@@ -0,0 +1 @@
+
diff --git a/media/editors/codemirror/addon/search/index.html b/media/editors/codemirror/addon/search/index.html
new file mode 100644
index 0000000000000..2efb97f319a35
--- /dev/null
+++ b/media/editors/codemirror/addon/search/index.html
@@ -0,0 +1 @@
+
diff --git a/media/editors/codemirror/addon/selection/index.html b/media/editors/codemirror/addon/selection/index.html
new file mode 100644
index 0000000000000..2efb97f319a35
--- /dev/null
+++ b/media/editors/codemirror/addon/selection/index.html
@@ -0,0 +1 @@
+
diff --git a/media/editors/codemirror/addon/tern/index.html b/media/editors/codemirror/addon/tern/index.html
new file mode 100644
index 0000000000000..2efb97f319a35
--- /dev/null
+++ b/media/editors/codemirror/addon/tern/index.html
@@ -0,0 +1 @@
+
diff --git a/media/editors/codemirror/addon/tern/tern.js b/media/editors/codemirror/addon/tern/tern.js
index 4ec976db12df0..9bd69446a2e4a 100644
Binary files a/media/editors/codemirror/addon/tern/tern.js and b/media/editors/codemirror/addon/tern/tern.js differ
diff --git a/media/editors/codemirror/addon/wrap/index.html b/media/editors/codemirror/addon/wrap/index.html
new file mode 100644
index 0000000000000..2efb97f319a35
--- /dev/null
+++ b/media/editors/codemirror/addon/wrap/index.html
@@ -0,0 +1 @@
+
diff --git a/media/editors/codemirror/keymap/emacs.js b/media/editors/codemirror/keymap/emacs.js
index ba8149c70ecd8..4acfd601a0fd9 100644
--- a/media/editors/codemirror/keymap/emacs.js
+++ b/media/editors/codemirror/keymap/emacs.js
@@ -256,7 +256,7 @@
// Actual keymap
- var keyMap = CodeMirror.keyMap.emacs = {
+ var keyMap = CodeMirror.keyMap.emacs = CodeMirror.normalizeKeyMap({
"Ctrl-W": function(cm) {kill(cm, cm.getCursor("start"), cm.getCursor("end"));},
"Ctrl-K": repeated(function(cm) {
var start = cm.getCursor(), end = cm.clipPos(Pos(start.line));
@@ -353,27 +353,7 @@
"Alt-/": "autocomplete",
"Ctrl-J": "newlineAndIndent", "Enter": false, "Tab": "indentAuto",
- "Alt-G": function(cm) {cm.setOption("keyMap", "emacs-Alt-G");},
- "Ctrl-X": function(cm) {cm.setOption("keyMap", "emacs-Ctrl-X");},
- "Ctrl-Q": function(cm) {cm.setOption("keyMap", "emacs-Ctrl-Q");},
- "Ctrl-U": addPrefixMap
- };
-
- CodeMirror.keyMap["emacs-Ctrl-X"] = {
- "Tab": function(cm) {
- cm.indentSelection(getPrefix(cm, true) || cm.getOption("indentUnit"));
- },
- "Ctrl-X": function(cm) {
- cm.setSelection(cm.getCursor("head"), cm.getCursor("anchor"));
- },
-
- "Ctrl-S": "save", "Ctrl-W": "save", "S": "saveAll", "F": "open", "U": repeated("undo"), "K": "close",
- "Delete": function(cm) { kill(cm, cm.getCursor(), bySentence(cm, cm.getCursor(), 1), true); },
- auto: "emacs", nofallthrough: true, disableInput: true
- };
-
- CodeMirror.keyMap["emacs-Alt-G"] = {
- "G": function(cm) {
+ "Alt-G G": function(cm) {
var prefix = getPrefix(cm, true);
if (prefix != null && prefix > 0) return cm.setCursor(prefix - 1);
@@ -383,13 +363,24 @@
cm.setCursor(num - 1);
});
},
- auto: "emacs", nofallthrough: true, disableInput: true
- };
- CodeMirror.keyMap["emacs-Ctrl-Q"] = {
- "Tab": repeated("insertTab"),
- auto: "emacs", nofallthrough: true
- };
+ "Ctrl-X Tab": function(cm) {
+ cm.indentSelection(getPrefix(cm, true) || cm.getOption("indentUnit"));
+ },
+ "Ctrl-X Ctrl-X": function(cm) {
+ cm.setSelection(cm.getCursor("head"), cm.getCursor("anchor"));
+ },
+ "Ctrl-X Ctrl-S": "save",
+ "Ctrl-X Ctrl-W": "save",
+ "Ctrl-X S": "saveAll",
+ "Ctrl-X F": "open",
+ "Ctrl-X U": repeated("undo"),
+ "Ctrl-X K": "close",
+ "Ctrl-X Delete": function(cm) { kill(cm, cm.getCursor(), bySentence(cm, cm.getCursor(), 1), true); },
+
+ "Ctrl-Q Tab": repeated("insertTab"),
+ "Ctrl-U": addPrefixMap
+ });
var prefixMap = {"Ctrl-G": clearPrefix};
function regPrefix(d) {
diff --git a/media/editors/codemirror/keymap/index.html b/media/editors/codemirror/keymap/index.html
new file mode 100644
index 0000000000000..2efb97f319a35
--- /dev/null
+++ b/media/editors/codemirror/keymap/index.html
@@ -0,0 +1 @@
+
diff --git a/media/editors/codemirror/keymap/sublime.js b/media/editors/codemirror/keymap/sublime.js
index f70a1f98f293b..45936c362892e 100644
--- a/media/editors/codemirror/keymap/sublime.js
+++ b/media/editors/codemirror/keymap/sublime.js
@@ -386,9 +386,7 @@
map["Alt-Q"] = "wrapLines";
- var mapK = CodeMirror.keyMap["sublime-Ctrl-K"] = {auto: "sublime", nofallthrough: true};
-
- map[ctrl + "K"] = function(cm) {cm.setOption("keyMap", "sublime-Ctrl-K");};
+ var cK = ctrl + "K ";
function modifyWordOrSelection(cm, mod) {
cm.operation(function() {
@@ -409,9 +407,9 @@
});
}
- mapK[ctrl + "Backspace"] = "delLineLeft";
+ map[cK + ctrl + "Backspace"] = "delLineLeft";
- cmds[mapK[ctrl + "K"] = "delLineRight"] = function(cm) {
+ cmds[map[cK + ctrl + "K"] = "delLineRight"] = function(cm) {
cm.operation(function() {
var ranges = cm.listSelections();
for (var i = ranges.length - 1; i >= 0; i--)
@@ -420,22 +418,22 @@
});
};
- cmds[mapK[ctrl + "U"] = "upcaseAtCursor"] = function(cm) {
+ cmds[map[cK + ctrl + "U"] = "upcaseAtCursor"] = function(cm) {
modifyWordOrSelection(cm, function(str) { return str.toUpperCase(); });
};
- cmds[mapK[ctrl + "L"] = "downcaseAtCursor"] = function(cm) {
+ cmds[map[cK + ctrl + "L"] = "downcaseAtCursor"] = function(cm) {
modifyWordOrSelection(cm, function(str) { return str.toLowerCase(); });
};
- cmds[mapK[ctrl + "Space"] = "setSublimeMark"] = function(cm) {
+ cmds[map[cK + ctrl + "Space"] = "setSublimeMark"] = function(cm) {
if (cm.state.sublimeMark) cm.state.sublimeMark.clear();
cm.state.sublimeMark = cm.setBookmark(cm.getCursor());
};
- cmds[mapK[ctrl + "A"] = "selectToSublimeMark"] = function(cm) {
+ cmds[map[cK + ctrl + "A"] = "selectToSublimeMark"] = function(cm) {
var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
if (found) cm.setSelection(cm.getCursor(), found);
};
- cmds[mapK[ctrl + "W"] = "deleteToSublimeMark"] = function(cm) {
+ cmds[map[cK + ctrl + "W"] = "deleteToSublimeMark"] = function(cm) {
var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
if (found) {
var from = cm.getCursor(), to = found;
@@ -444,7 +442,7 @@
cm.replaceRange("", from, to);
}
};
- cmds[mapK[ctrl + "X"] = "swapWithSublimeMark"] = function(cm) {
+ cmds[map[cK + ctrl + "X"] = "swapWithSublimeMark"] = function(cm) {
var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
if (found) {
cm.state.sublimeMark.clear();
@@ -452,13 +450,13 @@
cm.setCursor(found);
}
};
- cmds[mapK[ctrl + "Y"] = "sublimeYank"] = function(cm) {
+ cmds[map[cK + ctrl + "Y"] = "sublimeYank"] = function(cm) {
if (cm.state.sublimeKilled != null)
cm.replaceSelection(cm.state.sublimeKilled, null, "paste");
};
- mapK[ctrl + "G"] = "clearBookmarks";
- cmds[mapK[ctrl + "C"] = "showInCenter"] = function(cm) {
+ map[cK + ctrl + "G"] = "clearBookmarks";
+ cmds[map[cK + ctrl + "C"] = "showInCenter"] = function(cm) {
var pos = cm.cursorCoords(null, "local");
cm.scrollTo(null, (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2);
};
@@ -530,7 +528,7 @@
map["Shift-" + ctrl + "["] = "fold";
map["Shift-" + ctrl + "]"] = "unfold";
- mapK[ctrl + "0"] = mapK[ctrl + "j"] = "unfoldAll";
+ map[cK + ctrl + "0"] = map[cK + ctrl + "j"] = "unfoldAll";
map[ctrl + "I"] = "findIncremental";
map["Shift-" + ctrl + "I"] = "findIncrementalReverse";
@@ -538,4 +536,5 @@
map["F3"] = "findNext";
map["Shift-F3"] = "findPrev";
+ CodeMirror.normalizeKeyMap(map);
});
diff --git a/media/editors/codemirror/keymap/vim.js b/media/editors/codemirror/keymap/vim.js
index 0bf2c78248891..c5b945cd67520 100644
--- a/media/editors/codemirror/keymap/vim.js
+++ b/media/editors/codemirror/keymap/vim.js
@@ -72,305 +72,253 @@
var defaultKeymap = [
// Key to key mapping. This goes first to make it possible to override
// existing mappings.
- { keys: [''], type: 'keyToKey', toKeys: ['h'] },
- { keys: [''], type: 'keyToKey', toKeys: ['l'] },
- { keys: [''], type: 'keyToKey', toKeys: ['k'] },
- { keys: [''], type: 'keyToKey', toKeys: ['j'] },
- { keys: [''], type: 'keyToKey', toKeys: ['l'] },
- { keys: [''], type: 'keyToKey', toKeys: ['h'] },
- { keys: [''], type: 'keyToKey', toKeys: ['W'] },
- { keys: [''], type: 'keyToKey', toKeys: ['B'] },
- { keys: [''], type: 'keyToKey', toKeys: ['w'] },
- { keys: [''], type: 'keyToKey', toKeys: ['b'] },
- { keys: [''], type: 'keyToKey', toKeys: ['j'] },
- { keys: [''], type: 'keyToKey', toKeys: ['k'] },
- { keys: [''], type: 'keyToKey', toKeys: [''] },
- { keys: [''], type: 'keyToKey', toKeys: [''] },
- { keys: ['s'], type: 'keyToKey', toKeys: ['c', 'l'], context: 'normal' },
- { keys: ['s'], type: 'keyToKey', toKeys: ['x', 'i'], context: 'visual'},
- { keys: ['S'], type: 'keyToKey', toKeys: ['c', 'c'], context: 'normal' },
- { keys: ['S'], type: 'keyToKey', toKeys: ['d', 'c', 'c'], context: 'visual' },
- { keys: [''], type: 'keyToKey', toKeys: ['0'] },
- { keys: [''], type: 'keyToKey', toKeys: ['$'] },
- { keys: [''], type: 'keyToKey', toKeys: [''] },
- { keys: [''], type: 'keyToKey', toKeys: [''] },
- { keys: [''], type: 'keyToKey', toKeys: ['j', '^'], context: 'normal' },
+ { keys: '', type: 'keyToKey', toKeys: 'h' },
+ { keys: '', type: 'keyToKey', toKeys: 'l' },
+ { keys: '', type: 'keyToKey', toKeys: 'k' },
+ { keys: '', type: 'keyToKey', toKeys: 'j' },
+ { keys: '', type: 'keyToKey', toKeys: 'l' },
+ { keys: '', type: 'keyToKey', toKeys: 'h' },
+ { keys: '', type: 'keyToKey', toKeys: 'W' },
+ { keys: '', type: 'keyToKey', toKeys: 'B' },
+ { keys: '', type: 'keyToKey', toKeys: 'w' },
+ { keys: '', type: 'keyToKey', toKeys: 'b' },
+ { keys: '', type: 'keyToKey', toKeys: 'j' },
+ { keys: '', type: 'keyToKey', toKeys: 'k' },
+ { keys: '', type: 'keyToKey', toKeys: '' },
+ { keys: '', type: 'keyToKey', toKeys: '' },
+ { keys: '', type: 'keyToKey', toKeys: '', context: 'insert' },
+ { keys: '', type: 'keyToKey', toKeys: '', context: 'insert' },
+ { keys: 's', type: 'keyToKey', toKeys: 'cl', context: 'normal' },
+ { keys: 's', type: 'keyToKey', toKeys: 'xi', context: 'visual'},
+ { keys: 'S', type: 'keyToKey', toKeys: 'cc', context: 'normal' },
+ { keys: 'S', type: 'keyToKey', toKeys: 'dcc', context: 'visual' },
+ { keys: '', type: 'keyToKey', toKeys: '0' },
+ { keys: '', type: 'keyToKey', toKeys: '$' },
+ { keys: '', type: 'keyToKey', toKeys: '' },
+ { keys: '', type: 'keyToKey', toKeys: '' },
+ { keys: '', type: 'keyToKey', toKeys: 'j^', context: 'normal' },
// Motions
- { keys: ['H'], type: 'motion',
- motion: 'moveToTopLine',
- motionArgs: { linewise: true, toJumplist: true }},
- { keys: ['M'], type: 'motion',
- motion: 'moveToMiddleLine',
- motionArgs: { linewise: true, toJumplist: true }},
- { keys: ['L'], type: 'motion',
- motion: 'moveToBottomLine',
- motionArgs: { linewise: true, toJumplist: true }},
- { keys: ['h'], type: 'motion',
- motion: 'moveByCharacters',
- motionArgs: { forward: false }},
- { keys: ['l'], type: 'motion',
- motion: 'moveByCharacters',
- motionArgs: { forward: true }},
- { keys: ['j'], type: 'motion',
- motion: 'moveByLines',
- motionArgs: { forward: true, linewise: true }},
- { keys: ['k'], type: 'motion',
- motion: 'moveByLines',
- motionArgs: { forward: false, linewise: true }},
- { keys: ['g','j'], type: 'motion',
- motion: 'moveByDisplayLines',
- motionArgs: { forward: true }},
- { keys: ['g','k'], type: 'motion',
- motion: 'moveByDisplayLines',
- motionArgs: { forward: false }},
- { keys: ['w'], type: 'motion',
- motion: 'moveByWords',
- motionArgs: { forward: true, wordEnd: false }},
- { keys: ['W'], type: 'motion',
- motion: 'moveByWords',
- motionArgs: { forward: true, wordEnd: false, bigWord: true }},
- { keys: ['e'], type: 'motion',
- motion: 'moveByWords',
- motionArgs: { forward: true, wordEnd: true, inclusive: true }},
- { keys: ['E'], type: 'motion',
- motion: 'moveByWords',
- motionArgs: { forward: true, wordEnd: true, bigWord: true,
- inclusive: true }},
- { keys: ['b'], type: 'motion',
- motion: 'moveByWords',
- motionArgs: { forward: false, wordEnd: false }},
- { keys: ['B'], type: 'motion',
- motion: 'moveByWords',
- motionArgs: { forward: false, wordEnd: false, bigWord: true }},
- { keys: ['g', 'e'], type: 'motion',
- motion: 'moveByWords',
- motionArgs: { forward: false, wordEnd: true, inclusive: true }},
- { keys: ['g', 'E'], type: 'motion',
- motion: 'moveByWords',
- motionArgs: { forward: false, wordEnd: true, bigWord: true,
- inclusive: true }},
- { keys: ['{'], type: 'motion', motion: 'moveByParagraph',
- motionArgs: { forward: false, toJumplist: true }},
- { keys: ['}'], type: 'motion', motion: 'moveByParagraph',
- motionArgs: { forward: true, toJumplist: true }},
- { keys: [''], type: 'motion',
- motion: 'moveByPage', motionArgs: { forward: true }},
- { keys: [''], type: 'motion',
- motion: 'moveByPage', motionArgs: { forward: false }},
- { keys: [''], type: 'motion',
- motion: 'moveByScroll',
- motionArgs: { forward: true, explicitRepeat: true }},
- { keys: [''], type: 'motion',
- motion: 'moveByScroll',
- motionArgs: { forward: false, explicitRepeat: true }},
- { keys: ['g', 'g'], type: 'motion',
- motion: 'moveToLineOrEdgeOfDocument',
- motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},
- { keys: ['G'], type: 'motion',
- motion: 'moveToLineOrEdgeOfDocument',
- motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},
- { keys: ['0'], type: 'motion', motion: 'moveToStartOfLine' },
- { keys: ['^'], type: 'motion',
- motion: 'moveToFirstNonWhiteSpaceCharacter' },
- { keys: ['+'], type: 'motion',
- motion: 'moveByLines',
- motionArgs: { forward: true, toFirstChar:true }},
- { keys: ['-'], type: 'motion',
- motion: 'moveByLines',
- motionArgs: { forward: false, toFirstChar:true }},
- { keys: ['_'], type: 'motion',
- motion: 'moveByLines',
- motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},
- { keys: ['$'], type: 'motion',
- motion: 'moveToEol',
- motionArgs: { inclusive: true }},
- { keys: ['%'], type: 'motion',
- motion: 'moveToMatchedSymbol',
- motionArgs: { inclusive: true, toJumplist: true }},
- { keys: ['f', 'character'], type: 'motion',
- motion: 'moveToCharacter',
- motionArgs: { forward: true , inclusive: true }},
- { keys: ['F', 'character'], type: 'motion',
- motion: 'moveToCharacter',
- motionArgs: { forward: false }},
- { keys: ['t', 'character'], type: 'motion',
- motion: 'moveTillCharacter',
- motionArgs: { forward: true, inclusive: true }},
- { keys: ['T', 'character'], type: 'motion',
- motion: 'moveTillCharacter',
- motionArgs: { forward: false }},
- { keys: [';'], type: 'motion', motion: 'repeatLastCharacterSearch',
- motionArgs: { forward: true }},
- { keys: [','], type: 'motion', motion: 'repeatLastCharacterSearch',
- motionArgs: { forward: false }},
- { keys: ['\'', 'character'], type: 'motion', motion: 'goToMark',
- motionArgs: {toJumplist: true, linewise: true}},
- { keys: ['`', 'character'], type: 'motion', motion: 'goToMark',
- motionArgs: {toJumplist: true}},
- { keys: [']', '`'], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
- { keys: ['[', '`'], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
- { keys: [']', '\''], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
- { keys: ['[', '\''], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
+ { keys: 'H', type: 'motion', motion: 'moveToTopLine', motionArgs: { linewise: true, toJumplist: true }},
+ { keys: 'M', type: 'motion', motion: 'moveToMiddleLine', motionArgs: { linewise: true, toJumplist: true }},
+ { keys: 'L', type: 'motion', motion: 'moveToBottomLine', motionArgs: { linewise: true, toJumplist: true }},
+ { keys: 'h', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: false }},
+ { keys: 'l', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: true }},
+ { keys: 'j', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, linewise: true }},
+ { keys: 'k', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, linewise: true }},
+ { keys: 'gj', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: true }},
+ { keys: 'gk', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: false }},
+ { keys: 'w', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false }},
+ { keys: 'W', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false, bigWord: true }},
+ { keys: 'e', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, inclusive: true }},
+ { keys: 'E', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, bigWord: true, inclusive: true }},
+ { keys: 'b', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }},
+ { keys: 'B', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false, bigWord: true }},
+ { keys: 'ge', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, inclusive: true }},
+ { keys: 'gE', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, bigWord: true, inclusive: true }},
+ { keys: '{', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: false, toJumplist: true }},
+ { keys: '}', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: true, toJumplist: true }},
+ { keys: '', type: 'motion', motion: 'moveByPage', motionArgs: { forward: true }},
+ { keys: '', type: 'motion', motion: 'moveByPage', motionArgs: { forward: false }},
+ { keys: '', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: true, explicitRepeat: true }},
+ { keys: '', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: false, explicitRepeat: true }},
+ { keys: 'gg', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},
+ { keys: 'G', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},
+ { keys: '0', type: 'motion', motion: 'moveToStartOfLine' },
+ { keys: '^', type: 'motion', motion: 'moveToFirstNonWhiteSpaceCharacter' },
+ { keys: '+', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true }},
+ { keys: '-', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, toFirstChar:true }},
+ { keys: '_', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},
+ { keys: '$', type: 'motion', motion: 'moveToEol', motionArgs: { inclusive: true }},
+ { keys: '%', type: 'motion', motion: 'moveToMatchedSymbol', motionArgs: { inclusive: true, toJumplist: true }},
+ { keys: 'f', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: true , inclusive: true }},
+ { keys: 'F', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: false }},
+ { keys: 't', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: true, inclusive: true }},
+ { keys: 'T', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: false }},
+ { keys: ';', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: true }},
+ { keys: ',', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: false }},
+ { keys: '\'', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true, linewise: true}},
+ { keys: '`', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true}},
+ { keys: ']`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
+ { keys: '[`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
+ { keys: ']\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
+ { keys: '[\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
// the next two aren't motions but must come before more general motion declarations
- { keys: [']', 'p'], type: 'action', action: 'paste', isEdit: true,
- actionArgs: { after: true, isEdit: true, matchIndent: true}},
- { keys: ['[', 'p'], type: 'action', action: 'paste', isEdit: true,
- actionArgs: { after: false, isEdit: true, matchIndent: true}},
- { keys: [']', 'character'], type: 'motion',
- motion: 'moveToSymbol',
- motionArgs: { forward: true, toJumplist: true}},
- { keys: ['[', 'character'], type: 'motion',
- motion: 'moveToSymbol',
- motionArgs: { forward: false, toJumplist: true}},
- { keys: ['|'], type: 'motion',
- motion: 'moveToColumn',
- motionArgs: { }},
- { keys: ['o'], type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: { }, context:'visual'},
- { keys: ['O'], type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: {sameLine: true}, context:'visual'},
+ { keys: ']p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true, matchIndent: true}},
+ { keys: '[p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true, matchIndent: true}},
+ { keys: ']', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: true, toJumplist: true}},
+ { keys: '[', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: false, toJumplist: true}},
+ { keys: '|', type: 'motion', motion: 'moveToColumn'},
+ { keys: 'o', type: 'motion', motion: 'moveToOtherHighlightedEnd', context:'visual'},
+ { keys: 'O', type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: {sameLine: true}, context:'visual'},
// Operators
- { keys: ['d'], type: 'operator', operator: 'delete' },
- { keys: ['y'], type: 'operator', operator: 'yank' },
- { keys: ['c'], type: 'operator', operator: 'change' },
- { keys: ['>'], type: 'operator', operator: 'indent',
- operatorArgs: { indentRight: true }},
- { keys: ['<'], type: 'operator', operator: 'indent',
- operatorArgs: { indentRight: false }},
- { keys: ['g', '~'], type: 'operator', operator: 'swapcase' },
- { keys: ['n'], type: 'motion', motion: 'findNext',
- motionArgs: { forward: true, toJumplist: true }},
- { keys: ['N'], type: 'motion', motion: 'findNext',
- motionArgs: { forward: false, toJumplist: true }},
+ { keys: 'd', type: 'operator', operator: 'delete' },
+ { keys: 'y', type: 'operator', operator: 'yank' },
+ { keys: 'c', type: 'operator', operator: 'change' },
+ { keys: '>', type: 'operator', operator: 'indent', operatorArgs: { indentRight: true }},
+ { keys: '<', type: 'operator', operator: 'indent', operatorArgs: { indentRight: false }},
+ { keys: 'g~', type: 'operator', operator: 'changeCase' },
+ { keys: 'gu', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, isEdit: true },
+ { keys: 'gU', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, isEdit: true },
+ { keys: 'n', type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: true }},
+ { keys: 'N', type: 'motion', motion: 'findNext', motionArgs: { forward: false, toJumplist: true }},
// Operator-Motion dual commands
- { keys: ['x'], type: 'operatorMotion', operator: 'delete',
- motion: 'moveByCharacters', motionArgs: { forward: true },
- operatorMotionArgs: { visualLine: false }},
- { keys: ['X'], type: 'operatorMotion', operator: 'delete',
- motion: 'moveByCharacters', motionArgs: { forward: false },
- operatorMotionArgs: { visualLine: true }},
- { keys: ['D'], type: 'operatorMotion', operator: 'delete',
- motion: 'moveToEol', motionArgs: { inclusive: true },
- operatorMotionArgs: { visualLine: true }},
- { keys: ['Y'], type: 'operatorMotion', operator: 'yank',
- motion: 'moveToEol', motionArgs: { inclusive: true },
- operatorMotionArgs: { visualLine: true }},
- { keys: ['C'], type: 'operatorMotion',
- operator: 'change',
- motion: 'moveToEol', motionArgs: { inclusive: true },
- operatorMotionArgs: { visualLine: true }},
- { keys: ['~'], type: 'operatorMotion',
- operator: 'swapcase', operatorArgs: { shouldMoveCursor: true },
- motion: 'moveByCharacters', motionArgs: { forward: true }},
+ { keys: 'x', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorMotionArgs: { visualLine: false }},
+ { keys: 'X', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: false }, operatorMotionArgs: { visualLine: true }},
+ { keys: 'D', type: 'operatorMotion', operator: 'delete', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
+ { keys: 'D', type: 'operator', operator: 'delete', operatorArgs: { linewise: true }, context: 'visual'},
+ { keys: 'Y', type: 'operatorMotion', operator: 'yank', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
+ { keys: 'Y', type: 'operator', operator: 'yank', operatorArgs: { linewise: true }, context: 'visual'},
+ { keys: 'C', type: 'operatorMotion', operator: 'change', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
+ { keys: 'C', type: 'operator', operator: 'change', operatorArgs: { linewise: true }, context: 'visual'},
+ { keys: '~', type: 'operatorMotion', operator: 'changeCase', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorArgs: { shouldMoveCursor: true }, context: 'normal'},
+ { keys: '~', type: 'operator', operator: 'changeCase', context: 'visual'},
+ { keys: '', type: 'operatorMotion', operator: 'delete', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }, context: 'insert' },
// Actions
- { keys: [''], type: 'action', action: 'jumpListWalk',
- actionArgs: { forward: true }},
- { keys: [''], type: 'action', action: 'jumpListWalk',
- actionArgs: { forward: false }},
- { keys: [''], type: 'action',
- action: 'scroll',
- actionArgs: { forward: true, linewise: true }},
- { keys: [''], type: 'action',
- action: 'scroll',
- actionArgs: { forward: false, linewise: true }},
- { keys: ['a'], type: 'action', action: 'enterInsertMode', isEdit: true,
- actionArgs: { insertAt: 'charAfter' }},
- { keys: ['A'], type: 'action', action: 'enterInsertMode', isEdit: true,
- actionArgs: { insertAt: 'eol' }},
- { keys: ['A'], type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' },
- { keys: ['i'], type: 'action', action: 'enterInsertMode', isEdit: true,
- actionArgs: { insertAt: 'inplace' }},
- { keys: ['I'], type: 'action', action: 'enterInsertMode', isEdit: true,
- actionArgs: { insertAt: 'firstNonBlank' }},
- { keys: ['o'], type: 'action', action: 'newLineAndEnterInsertMode',
- isEdit: true, interlaceInsertRepeat: true,
- actionArgs: { after: true }},
- { keys: ['O'], type: 'action', action: 'newLineAndEnterInsertMode',
- isEdit: true, interlaceInsertRepeat: true,
- actionArgs: { after: false }},
- { keys: ['v'], type: 'action', action: 'toggleVisualMode' },
- { keys: ['V'], type: 'action', action: 'toggleVisualMode',
- actionArgs: { linewise: true }},
- { keys: [''], type: 'action', action: 'toggleVisualMode',
- actionArgs: { blockwise: true }},
- { keys: ['g', 'v'], type: 'action', action: 'reselectLastSelection' },
- { keys: ['J'], type: 'action', action: 'joinLines', isEdit: true },
- { keys: ['p'], type: 'action', action: 'paste', isEdit: true,
- actionArgs: { after: true, isEdit: true }},
- { keys: ['P'], type: 'action', action: 'paste', isEdit: true,
- actionArgs: { after: false, isEdit: true }},
- { keys: ['r', 'character'], type: 'action', action: 'replace', isEdit: true },
- { keys: ['@', 'character'], type: 'action', action: 'replayMacro' },
- { keys: ['q', 'character'], type: 'action', action: 'enterMacroRecordMode' },
+ { keys: '', type: 'action', action: 'jumpListWalk', actionArgs: { forward: true }},
+ { keys: '', type: 'action', action: 'jumpListWalk', actionArgs: { forward: false }},
+ { keys: '', type: 'action', action: 'scroll', actionArgs: { forward: true, linewise: true }},
+ { keys: '', type: 'action', action: 'scroll', actionArgs: { forward: false, linewise: true }},
+ { keys: 'a', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'charAfter' }, context: 'normal' },
+ { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'eol' }, context: 'normal' },
+ { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' },
+ { keys: 'i', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'inplace' }, context: 'normal' },
+ { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'firstNonBlank'}, context: 'normal' },
+ { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'startOfSelectedArea' }, context: 'visual' },
+ { keys: 'o', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: true }, context: 'normal' },
+ { keys: 'O', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: false }, context: 'normal' },
+ { keys: 'v', type: 'action', action: 'toggleVisualMode' },
+ { keys: 'V', type: 'action', action: 'toggleVisualMode', actionArgs: { linewise: true }},
+ { keys: '', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }},
+ { keys: 'gv', type: 'action', action: 'reselectLastSelection' },
+ { keys: 'J', type: 'action', action: 'joinLines', isEdit: true },
+ { keys: 'p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true }},
+ { keys: 'P', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true }},
+ { keys: 'r', type: 'action', action: 'replace', isEdit: true },
+ { keys: '@', type: 'action', action: 'replayMacro' },
+ { keys: 'q', type: 'action', action: 'enterMacroRecordMode' },
// Handle Replace-mode as a special case of insert mode.
- { keys: ['R'], type: 'action', action: 'enterInsertMode', isEdit: true,
- actionArgs: { replace: true }},
- { keys: ['u'], type: 'action', action: 'undo' },
- { keys: ['u'], type: 'action', action: 'changeCase', actionArgs: {toLower: true}, context: 'visual', isEdit: true },
- { keys: ['U'],type: 'action', action: 'changeCase', actionArgs: {toLower: false}, context: 'visual', isEdit: true },
- { keys: [''], type: 'action', action: 'redo' },
- { keys: ['m', 'character'], type: 'action', action: 'setMark' },
- { keys: ['"', 'character'], type: 'action', action: 'setRegister' },
- { keys: ['z', 'z'], type: 'action', action: 'scrollToCursor',
- actionArgs: { position: 'center' }},
- { keys: ['z', '.'], type: 'action', action: 'scrollToCursor',
- actionArgs: { position: 'center' },
- motion: 'moveToFirstNonWhiteSpaceCharacter' },
- { keys: ['z', 't'], type: 'action', action: 'scrollToCursor',
- actionArgs: { position: 'top' }},
- { keys: ['z', ''], type: 'action', action: 'scrollToCursor',
- actionArgs: { position: 'top' },
- motion: 'moveToFirstNonWhiteSpaceCharacter' },
- { keys: ['z', '-'], type: 'action', action: 'scrollToCursor',
- actionArgs: { position: 'bottom' }},
- { keys: ['z', 'b'], type: 'action', action: 'scrollToCursor',
- actionArgs: { position: 'bottom' },
- motion: 'moveToFirstNonWhiteSpaceCharacter' },
- { keys: ['.'], type: 'action', action: 'repeatLastEdit' },
- { keys: [''], type: 'action', action: 'incrementNumberToken',
- isEdit: true,
- actionArgs: {increase: true, backtrack: false}},
- { keys: [''], type: 'action', action: 'incrementNumberToken',
- isEdit: true,
- actionArgs: {increase: false, backtrack: false}},
+ { keys: 'R', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { replace: true }},
+ { keys: 'u', type: 'action', action: 'undo', context: 'normal' },
+ { keys: 'u', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, context: 'visual', isEdit: true },
+ { keys: 'U', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, context: 'visual', isEdit: true },
+ { keys: '', type: 'action', action: 'redo' },
+ { keys: 'm', type: 'action', action: 'setMark' },
+ { keys: '"', type: 'action', action: 'setRegister' },
+ { keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }},
+ { keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
+ { keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }},
+ { keys: 'z', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
+ { keys: 'z-', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }},
+ { keys: 'zb', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
+ { keys: '.', type: 'action', action: 'repeatLastEdit' },
+ { keys: '', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: true, backtrack: false}},
+ { keys: '', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: false, backtrack: false}},
// Text object motions
- { keys: ['a', 'character'], type: 'motion',
- motion: 'textObjectManipulation' },
- { keys: ['i', 'character'], type: 'motion',
- motion: 'textObjectManipulation',
- motionArgs: { textObjectInner: true }},
+ { keys: 'a', type: 'motion', motion: 'textObjectManipulation' },
+ { keys: 'i', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }},
// Search
- { keys: ['/'], type: 'search',
- searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},
- { keys: ['?'], type: 'search',
- searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},
- { keys: ['*'], type: 'search',
- searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
- { keys: ['#'], type: 'search',
- searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
- { keys: ['g', '*'], type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},
- { keys: ['g', '#'], type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},
+ { keys: '/', type: 'search', searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},
+ { keys: '?', type: 'search', searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},
+ { keys: '*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
+ { keys: '#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
+ { keys: 'g*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},
+ { keys: 'g#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},
// Ex command
- { keys: [':'], type: 'ex' }
+ { keys: ':', type: 'ex' }
];
var Pos = CodeMirror.Pos;
+ var modifierCodes = [16, 17, 18, 91];
+ var specialKey = {Enter:'CR',Backspace:'BS',Delete:'Del'};
+ var mac = /Mac/.test(navigator.platform);
var Vim = function() {
- CodeMirror.defineOption('vimMode', false, function(cm, val) {
- if (val) {
- cm.setOption('keyMap', 'vim');
- cm.setOption('disableInput', true);
- cm.setOption('showCursorWhenSelecting', false);
- CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
- cm.on('cursorActivity', onCursorActivity);
- maybeInitVimState(cm);
- CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm));
- } else if (cm.state.vim) {
- cm.setOption('keyMap', 'default');
- cm.setOption('disableInput', false);
- cm.off('cursorActivity', onCursorActivity);
- CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm));
- cm.state.vim = null;
+ function lookupKey(e) {
+ var keyCode = e.keyCode;
+ if (modifierCodes.indexOf(keyCode) != -1) { return; }
+ var hasModifier = e.ctrlKey || e.metaKey;
+ var key = CodeMirror.keyNames[keyCode];
+ key = specialKey[key] || key;
+ var name = '';
+ if (e.ctrlKey) { name += 'C-'; }
+ if (e.altKey) { name += 'A-'; }
+ if (mac && e.metaKey || (!hasModifier && e.shiftKey) && key.length < 2) {
+ // Shift key bindings can only specified for special characters.
+ return;
+ } else if (e.shiftKey && !/^[A-Za-z]$/.test(key)) {
+ name += 'S-';
+ }
+ if (key.length == 1) { key = key.toLowerCase(); }
+ name += key;
+ if (name.length > 1) { name = '<' + name + '>'; }
+ return name;
+ }
+ // Keys with modifiers are handled using keydown due to limitations of
+ // keypress event.
+ function handleKeyDown(cm, e) {
+ var name = lookupKey(e);
+ if (!name) { return; }
+
+ CodeMirror.signal(cm, 'vim-keypress', name);
+ if (CodeMirror.Vim.handleKey(cm, name, 'user')) {
+ CodeMirror.e_stop(e);
}
+ }
+ // Keys without modifiers are handled using keypress to work best with
+ // non-standard keyboard layouts.
+ function handleKeyPress(cm, e) {
+ var code = e.charCode || e.keyCode;
+ if (e.ctrlKey || e.metaKey || e.altKey ||
+ e.shiftKey && code < 32) { return; }
+ var name = String.fromCharCode(code);
+
+ CodeMirror.signal(cm, 'vim-keypress', name);
+ if (CodeMirror.Vim.handleKey(cm, name, 'user')) {
+ CodeMirror.e_stop(e);
+ }
+ }
+
+ function enterVimMode(cm) {
+ cm.setOption('disableInput', true);
+ cm.setOption('showCursorWhenSelecting', false);
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
+ cm.on('cursorActivity', onCursorActivity);
+ maybeInitVimState(cm);
+ CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm));
+ cm.on('keypress', handleKeyPress);
+ cm.on('keydown', handleKeyDown);
+ }
+
+ function leaveVimMode(cm) {
+ cm.setOption('disableInput', false);
+ cm.off('cursorActivity', onCursorActivity);
+ CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm));
+ cm.state.vim = null;
+ cm.off('keypress', handleKeyPress);
+ cm.off('keydown', handleKeyDown);
+ }
+
+ function detachVimMap(cm, next) {
+ if (this == CodeMirror.keyMap.vim)
+ CodeMirror.rmClass(cm.getWrapperElement(), "cm-fat-cursor");
+
+ if (!next || next.attach != attachVimMap)
+ leaveVimMode(cm, false);
+ }
+ function attachVimMap(cm, prev) {
+ if (this == CodeMirror.keyMap.vim)
+ CodeMirror.addClass(cm.getWrapperElement(), "cm-fat-cursor");
+
+ if (!prev || prev.attach != attachVimMap)
+ enterVimMode(cm);
+ }
+
+ // Deprecated, simply setting the keymap works again.
+ CodeMirror.defineOption('vimMode', false, function(cm, val, prev) {
+ if (val && cm.getOption("keyMap") != "vim")
+ cm.setOption("keyMap", "vim");
+ else if (!val && prev != CodeMirror.Init && /^vim/.test(cm.getOption("keyMap")))
+ cm.setOption("keyMap", "default");
});
function getOnPasteFn(cm) {
var vim = cm.state.vim;
@@ -397,9 +345,6 @@
var upperCaseAlphabet = makeKeyRange(65, 26);
var lowerCaseAlphabet = makeKeyRange(97, 26);
var numbers = makeKeyRange(48, 10);
- var specialSymbols = '~`!@#$%^&*()_-+=[{}]\\|/?.,<>:;"\''.split('');
- var specialKeys = ['Left', 'Right', 'Up', 'Down', 'Space', 'Backspace',
- 'Esc', 'Home', 'End', 'PageUp', 'PageDown', 'Enter'];
var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']);
var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"', '.', ':', '/']);
@@ -617,8 +562,8 @@
visualBlock: false,
lastSelection: null,
lastPastedText: null,
- // Used by two-character ESC keymap routines. Should not be changed from false here.
- awaitingEscapeSecondCharacter: false
+ sel: {
+ }
};
}
return cm.state.vim;
@@ -648,6 +593,7 @@
}
}
+ var lastInsertModeKeyTimer;
var vimApi= {
buildKeyMap: function() {
// TODO: Convert keymap into dictionary format for fast lookup.
@@ -685,58 +631,121 @@
},
// This is the outermost function called by CodeMirror, after keys have
// been mapped to their Vim equivalents.
- handleKey: function(cm, key) {
- var command;
+ handleKey: function(cm, key, origin) {
var vim = maybeInitVimState(cm);
- var macroModeState = vimGlobalState.macroModeState;
- if (macroModeState.isRecording) {
- if (key == 'q') {
- macroModeState.exitMacroRecordMode();
+ function handleMacroRecording() {
+ var macroModeState = vimGlobalState.macroModeState;
+ if (macroModeState.isRecording) {
+ if (key == 'q') {
+ macroModeState.exitMacroRecordMode();
+ clearInputState(cm);
+ return true;
+ }
+ if (origin != 'mapping') {
+ logKey(macroModeState, key);
+ }
+ }
+ }
+ function handleEsc() {
+ if (key == '') {
+ // Clear input state and get back to normal mode.
clearInputState(cm);
- return;
+ if (vim.visualMode) {
+ exitVisualMode(cm);
+ } else if (vim.insertMode) {
+ exitInsertMode(cm);
+ }
+ return true;
}
}
- if (key == '') {
- // Clear input state and get back to normal mode.
- clearInputState(cm);
- if (vim.visualMode) {
- exitVisualMode(cm);
+ function doKeyToKey(keys) {
+ // TODO: prevent infinite recursion.
+ var match;
+ while (keys) {
+ // Pull off one command key, which is either a single character
+ // or a special sequence wrapped in '<' and '>', e.g. ''.
+ match = (/<\w+-.+?>|<\w+>|./).exec(keys);
+ key = match[0];
+ keys = keys.substring(match.index + key.length);
+ CodeMirror.Vim.handleKey(cm, key, 'mapping');
}
- return;
}
- // Enter visual mode when the mouse selects text.
- if (!vim.visualMode &&
- !cursorEqual(cm.getCursor('head'), cm.getCursor('anchor'))) {
- vim.visualMode = true;
- vim.visualLine = false;
- CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
- cm.on('mousedown', exitVisualMode);
- }
- if (key != '0' || (key == '0' && vim.inputState.getRepeat() === 0)) {
- // Have to special case 0 since it's both a motion and a number.
- command = commandDispatcher.matchCommand(key, defaultKeymap, vim);
- }
- if (!command) {
- if (isNumber(key)) {
- // Increment count unless count is 0 and key is 0.
- vim.inputState.pushRepeatDigit(key);
+
+ function handleKeyInsertMode() {
+ if (handleEsc()) { return true; }
+ var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
+ var keysAreChars = key.length == 1;
+ var match = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
+ // Need to check all key substrings in insert mode.
+ while (keys.length > 1 && match.type != 'full') {
+ var keys = vim.inputState.keyBuffer = keys.slice(1);
+ var thisMatch = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
+ if (thisMatch.type != 'none') { match = thisMatch; }
}
- if (macroModeState.isRecording) {
- logKey(macroModeState, key);
+ if (match.type == 'none') { clearInputState(cm); return false; }
+ else if (match.type == 'partial') {
+ if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
+ lastInsertModeKeyTimer = window.setTimeout(
+ function() { if (vim.insertMode && vim.inputState.keyBuffer) { clearInputState(cm); } },
+ getOption('insertModeEscKeysTimeout'));
+ return !keysAreChars;
}
- return;
+
+ if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
+ if (keysAreChars) {
+ var here = cm.getCursor();
+ cm.replaceRange('', offsetCursor(here, 0, -(keys.length - 1)), here, '+input');
+ }
+ clearInputState(cm);
+ var command = match.command;
+ if (command.type == 'keyToKey') {
+ doKeyToKey(command.toKeys);
+ } else {
+ commandDispatcher.processCommand(cm, vim, command);
+ }
+ return true;
}
- if (command.type == 'keyToKey') {
- // TODO: prevent infinite recursion.
- for (var i = 0; i < command.toKeys.length; i++) {
- this.handleKey(cm, command.toKeys[i]);
+
+ function handleKeyNonInsertMode() {
+ if (handleMacroRecording() || handleEsc()) { return true; };
+
+ var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
+ if (/^[1-9]\d*$/.test(keys)) { return true; }
+
+ var keysMatcher = /^(\d*)(.*)$/.exec(keys);
+ if (!keysMatcher) { clearInputState(cm); return false; }
+ var context = vim.visualMode ? 'visual' :
+ 'normal';
+ var match = commandDispatcher.matchCommand(keysMatcher[2] || keysMatcher[1], defaultKeymap, vim.inputState, context);
+ if (match.type == 'none') { clearInputState(cm); return false; }
+ else if (match.type == 'partial') { return true; }
+
+ vim.inputState.keyBuffer = '';
+ var command = match.command;
+ var keysMatcher = /^(\d*)(.*)$/.exec(keys);
+ if (keysMatcher[1] && keysMatcher[1] != '0') {
+ vim.inputState.pushRepeatDigit(keysMatcher[1]);
}
- } else {
- if (macroModeState.isRecording) {
- logKey(macroModeState, key);
+ if (command.type == 'keyToKey') {
+ doKeyToKey(command.toKeys);
+ } else {
+ commandDispatcher.processCommand(cm, vim, command);
}
- commandDispatcher.processCommand(cm, vim, command);
+ return true;
}
+
+ return cm.operation(function() {
+ cm.curOp.isVimOp = true;
+ try {
+ if (vim.insertMode) { return handleKeyInsertMode(); }
+ else { return handleKeyNonInsertMode(); }
+ } catch (e) {
+ // clear VIM state in case it's in a bad state.
+ cm.state.vim = undefined;
+ maybeInitVimState(cm);
+ throw e;
+ }
+ });
},
handleEx: function(cm, input) {
exCommandDispatcher.processCommand(cm, input);
@@ -953,83 +962,25 @@
}
};
var commandDispatcher = {
- matchCommand: function(key, keyMap, vim) {
- var inputState = vim.inputState;
- var keys = inputState.keyBuffer.concat(key);
- var matchedCommands = [];
- var selectedCharacter;
- for (var i = 0; i < keyMap.length; i++) {
- var command = keyMap[i];
- if (matchKeysPartial(keys, command.keys)) {
- if (inputState.operator && command.type == 'action') {
- // Ignore matched action commands after an operator. Operators
- // only operate on motions. This check is really for text
- // objects since aW, a[ etcs conflicts with a.
- continue;
- }
- // Match commands that take as an argument.
- if (command.keys[keys.length - 1] == 'character') {
- selectedCharacter = keys[keys.length - 1];
- if (selectedCharacter.length>1){
- switch(selectedCharacter){
- case '':
- selectedCharacter='\n';
- break;
- case '':
- selectedCharacter=' ';
- break;
- default:
- continue;
- }
- }
- }
- // Add the command to the list of matched commands. Choose the best
- // command later.
- matchedCommands.push(command);
- }
+ matchCommand: function(keys, keyMap, inputState, context) {
+ var matches = commandMatches(keys, keyMap, context, inputState);
+ if (!matches.full && !matches.partial) {
+ return {type: 'none'};
+ } else if (!matches.full && matches.partial) {
+ return {type: 'partial'};
}
- // Returns the command if it is a full match, or null if not.
- function getFullyMatchedCommandOrNull(command) {
- if (keys.length < command.keys.length) {
- // Matches part of a multi-key command. Buffer and wait for next
- // stroke.
- inputState.keyBuffer.push(key);
- return null;
- } else {
- if (command.keys[keys.length - 1] == 'character') {
- inputState.selectedCharacter = selectedCharacter;
- }
- // Clear the buffer since a full match was found.
- inputState.keyBuffer = [];
- return command;
+ var bestMatch;
+ for (var i = 0; i < matches.full.length; i++) {
+ var match = matches.full[i];
+ if (!bestMatch) {
+ bestMatch = match;
}
}
-
- if (!matchedCommands.length) {
- // Clear the buffer since there were no matches.
- inputState.keyBuffer = [];
- return null;
- } else if (matchedCommands.length == 1) {
- return getFullyMatchedCommandOrNull(matchedCommands[0]);
- } else {
- // Find the best match in the list of matchedCommands.
- var context = vim.visualMode ? 'visual' : 'normal';
- var bestMatch; // Default to first in the list.
- for (var i = 0; i < matchedCommands.length; i++) {
- var current = matchedCommands[i];
- if (current.context == context) {
- bestMatch = current;
- break;
- } else if (!bestMatch && !current.context) {
- // Only set an imperfect match to best match if no best match is
- // set and the imperfect match is not restricted to another
- // context.
- bestMatch = current;
- }
- }
- return getFullyMatchedCommandOrNull(bestMatch);
+ if (bestMatch.keys.slice(-11) == '') {
+ inputState.selectedCharacter = lastChar(keys);
}
+ return {type: 'full', command: bestMatch};
},
processCommand: function(cm, vim, command) {
vim.inputState.repeatOverride = command.repeatOverride;
@@ -1048,10 +999,12 @@
break;
case 'search':
this.processSearch(cm, vim, command);
+ clearInputState(cm);
break;
case 'ex':
case 'keyToEx':
this.processEx(cm, vim, command);
+ clearInputState(cm);
break;
default:
break;
@@ -1293,13 +1246,13 @@
var operator = inputState.operator;
var operatorArgs = inputState.operatorArgs || {};
var registerName = inputState.registerName;
- var selectionEnd = copyCursor(cm.getCursor('head'));
- var selectionStart = copyCursor(cm.getCursor('anchor'));
- // The difference between cur and selection cursors are that cur is
- // being operated on and ignores that there is a selection.
- var curStart = copyCursor(selectionEnd);
- var curOriginal = copyCursor(curStart);
- var curEnd;
+ var sel = vim.sel;
+ // TODO: Make sure cm and vim selections are identical outside visual mode.
+ var origHead = copyCursor(vim.visualMode ? sel.head: cm.getCursor('head'));
+ var origAnchor = copyCursor(vim.visualMode ? sel.anchor : cm.getCursor('anchor'));
+ var oldHead = copyCursor(origHead);
+ var oldAnchor = copyCursor(origAnchor);
+ var newHead, newAnchor;
var repeat;
if (operator) {
this.recordLastEdit(vim, inputState);
@@ -1326,7 +1279,7 @@
motionArgs.repeat = repeat;
clearInputState(cm);
if (motion) {
- var motionResult = motions[motion](cm, motionArgs, vim);
+ var motionResult = motions[motion](cm, origHead, motionArgs, vim);
vim.lastMotion = motions[motion];
if (!motionResult) {
return;
@@ -1339,159 +1292,139 @@
recordJumpPosition(cm, cachedCursor, motionResult);
delete jumpList.cachedCursor;
} else {
- recordJumpPosition(cm, curOriginal, motionResult);
+ recordJumpPosition(cm, origHead, motionResult);
}
}
if (motionResult instanceof Array) {
- curStart = motionResult[0];
- curEnd = motionResult[1];
+ newAnchor = motionResult[0];
+ newHead = motionResult[1];
} else {
- curEnd = motionResult;
+ newHead = motionResult;
}
// TODO: Handle null returns from motion commands better.
- if (!curEnd) {
- curEnd = Pos(curStart.line, curStart.ch);
+ if (!newHead) {
+ newHead = copyCursor(origHead);
}
if (vim.visualMode) {
- // Check if the selection crossed over itself. Will need to shift
- // the start point if that happened.
- // offset is set to -1 or 1 to shift the curEnd
- // left or right
- var offset = 0;
- if (cursorIsBefore(selectionStart, selectionEnd) &&
- (cursorEqual(selectionStart, curEnd) ||
- cursorIsBefore(curEnd, selectionStart))) {
- // The end of the selection has moved from after the start to
- // before the start. We will shift the start right by 1.
- selectionStart.ch += 1;
- offset = -1;
- } else if (cursorIsBefore(selectionEnd, selectionStart) &&
- (cursorEqual(selectionStart, curEnd) ||
- cursorIsBefore(selectionStart, curEnd))) {
- // The opposite happened. We will shift the start left by 1.
- selectionStart.ch -= 1;
- offset = 1;
- }
- // in case of visual Block selectionStart and curEnd
- // may not be on the same line,
- // Also, In case of v_o this should not happen.
- if (!vim.visualBlock && !(motionResult instanceof Array)) {
- curEnd.ch += offset;
- }
- if (vim.lastHPos != Infinity) {
- vim.lastHPos = curEnd.ch;
- }
- selectionEnd = curEnd;
- selectionStart = (motionResult instanceof Array) ? curStart : selectionStart;
- if (vim.visualLine) {
- if (cursorIsBefore(selectionStart, selectionEnd)) {
- selectionStart.ch = 0;
-
- var lastLine = cm.lastLine();
- if (selectionEnd.line > lastLine) {
- selectionEnd.line = lastLine;
- }
- selectionEnd.ch = lineLength(cm, selectionEnd.line);
- } else {
- selectionEnd.ch = 0;
- selectionStart.ch = lineLength(cm, selectionStart.line);
- }
- } else if (vim.visualBlock) {
- // Select a block and
- // return the diagonally opposite end.
- selectionStart = selectBlock(cm, selectionEnd);
- }
- if (!vim.visualBlock) {
- cm.setSelection(selectionStart, selectionEnd);
+ newHead = clipCursorToContent(cm, newHead, vim.visualBlock);
+ if (newAnchor) {
+ newAnchor = clipCursorToContent(cm, newAnchor, true);
}
+ newAnchor = newAnchor || oldAnchor;
+ sel.anchor = newAnchor;
+ sel.head = newHead;
+ updateCmSelection(cm);
updateMark(cm, vim, '<',
- cursorIsBefore(selectionStart, selectionEnd) ? selectionStart
- : selectionEnd);
+ cursorIsBefore(newAnchor, newHead) ? newAnchor
+ : newHead);
updateMark(cm, vim, '>',
- cursorIsBefore(selectionStart, selectionEnd) ? selectionEnd
- : selectionStart);
+ cursorIsBefore(newAnchor, newHead) ? newHead
+ : newAnchor);
} else if (!operator) {
- curEnd = clipCursorToContent(cm, curEnd);
- cm.setCursor(curEnd.line, curEnd.ch);
+ newHead = clipCursorToContent(cm, newHead);
+ cm.setCursor(newHead.line, newHead.ch);
}
}
-
if (operator) {
- var inverted = false;
- vim.lastMotion = null;
- var lastSelection = vim.lastSelection;
- operatorArgs.repeat = repeat; // Indent in visual mode needs this.
- if (vim.visualMode) {
- curStart = selectionStart;
- curEnd = selectionEnd;
- motionArgs.inclusive = true;
- operatorArgs.shouldMoveCursor = false;
- }
- // Swap start and end if motion was backward.
- if (curEnd && cursorIsBefore(curEnd, curStart)) {
- var tmp = curStart;
- curStart = curEnd;
- curEnd = tmp;
- inverted = true;
- } else if (!curEnd) {
- curEnd = copyCursor(curStart);
- }
- if (motionArgs.inclusive && !vim.visualMode) {
- // Move the selection end one to the right to include the last
- // character.
- curEnd.ch++;
- }
- if (operatorArgs.selOffset) {
+ if (operatorArgs.lastSel) {
// Replaying a visual mode operation
- curEnd.line = curStart.line + operatorArgs.selOffset.line;
- if (operatorArgs.selOffset.line) {curEnd.ch = operatorArgs.selOffset.ch; }
- else { curEnd.ch = curStart.ch + operatorArgs.selOffset.ch; }
- // In case of blockwise visual
- if (lastSelection && lastSelection.visualBlock) {
- var block = lastSelection.visualBlock;
- var width = block.width;
- var height = block.height;
- curEnd = Pos(curStart.line + height, curStart.ch + width);
- // selectBlock creates a 'proper' rectangular block.
- // We do not want that in all cases, so we manually set selections.
- var selections = [];
- for (var i = curStart.line; i < curEnd.line; i++) {
- var anchor = Pos(i, curStart.ch);
- var head = Pos(i, curEnd.ch);
- var range = {anchor: anchor, head: head};
- selections.push(range);
- }
- cm.setSelections(selections);
- var blockSelected = true;
+ newAnchor = oldAnchor;
+ var lastSel = operatorArgs.lastSel;
+ var lineOffset = Math.abs(lastSel.head.line - lastSel.anchor.line);
+ var chOffset = Math.abs(lastSel.head.ch - lastSel.anchor.ch);
+ if (lastSel.visualLine) {
+ // Linewise Visual mode: The same number of lines.
+ newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
+ } else if (lastSel.visualBlock) {
+ // Blockwise Visual mode: The same number of lines and columns.
+ newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch + chOffset);
+ } else if (lastSel.head.line == lastSel.anchor.line) {
+ // Normal Visual mode within one line: The same number of characters.
+ newHead = Pos(oldAnchor.line, oldAnchor.ch + chOffset);
+ } else {
+ // Normal Visual mode with several lines: The same number of lines, in the
+ // last line the same number of characters as in the last line the last time.
+ newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
}
+ vim.visualMode = true;
+ vim.visualLine = lastSel.visualLine;
+ vim.visualBlock = lastSel.visualBlock;
+ sel = vim.sel = {
+ anchor: newAnchor,
+ head: newHead
+ };
+ updateCmSelection(cm);
} else if (vim.visualMode) {
- var selOffset = Pos();
- selOffset.line = curEnd.line - curStart.line;
- if (selOffset.line) { selOffset.ch = curEnd.ch; }
- else { selOffset.ch = curEnd.ch - curStart.ch; }
- operatorArgs.selOffset = selOffset;
+ operatorArgs.lastSel = {
+ anchor: copyCursor(sel.anchor),
+ head: copyCursor(sel.head),
+ visualBlock: vim.visualBlock,
+ visualLine: vim.visualLine
+ };
}
- var linewise = motionArgs.linewise ||
- (vim.visualMode && vim.visualLine) ||
- operatorArgs.linewise;
- if (linewise) {
- // Expand selection to entire line.
- expandSelectionToLine(cm, curStart, curEnd);
- } else if (motionArgs.forward) {
- // Clip to trailing newlines only if the motion goes forward.
- clipToLine(cm, curStart, curEnd);
+ var curStart, curEnd, linewise, mode;
+ var cmSel;
+ if (vim.visualMode) {
+ // Init visual op
+ curStart = cursorMin(sel.head, sel.anchor);
+ curEnd = cursorMax(sel.head, sel.anchor);
+ linewise = vim.visualLine || operatorArgs.linewise;
+ mode = vim.visualBlock ? 'block' :
+ linewise ? 'line' :
+ 'char';
+ cmSel = makeCmSelection(cm, {
+ anchor: curStart,
+ head: curEnd
+ }, mode);
+ if (linewise) {
+ var ranges = cmSel.ranges;
+ if (mode == 'block') {
+ // Linewise operators in visual block mode extend to end of line
+ for (var i = 0; i < ranges.length; i++) {
+ ranges[i].head.ch = lineLength(cm, ranges[i].head.line);
+ }
+ } else if (mode == 'line') {
+ ranges[0].head = Pos(ranges[0].head.line + 1, 0);
+ }
+ }
+ } else {
+ // Init motion op
+ curStart = copyCursor(newAnchor || oldAnchor);
+ curEnd = copyCursor(newHead || oldHead);
+ if (cursorIsBefore(curEnd, curStart)) {
+ var tmp = curStart;
+ curStart = curEnd;
+ curEnd = tmp;
+ }
+ linewise = motionArgs.linewise || operatorArgs.linewise;
+ if (linewise) {
+ // Expand selection to entire line.
+ expandSelectionToLine(cm, curStart, curEnd);
+ } else if (motionArgs.forward) {
+ // Clip to trailing newlines only if the motion goes forward.
+ clipToLine(cm, curStart, curEnd);
+ }
+ mode = 'char';
+ var exclusive = !motionArgs.inclusive || linewise;
+ cmSel = makeCmSelection(cm, {
+ anchor: curStart,
+ head: curEnd
+ }, mode, exclusive);
}
+ cm.setSelections(cmSel.ranges, cmSel.primary);
+ vim.lastMotion = null;
+ operatorArgs.repeat = repeat; // For indent in visual mode.
operatorArgs.registerName = registerName;
// Keep track of linewise as it affects how paste and change behave.
operatorArgs.linewise = linewise;
- if (!vim.visualBlock && !blockSelected) {
- cm.setSelection(curStart, curEnd);
- }
- operators[operator](cm, operatorArgs, vim, curStart,
- curEnd, curOriginal);
+ var operatorMoveTo = operators[operator](
+ cm, operatorArgs, cmSel.ranges, oldAnchor, newHead);
if (vim.visualMode) {
exitVisualMode(cm);
}
+ if (operatorMoveTo) {
+ cm.setCursor(operatorMoveTo);
+ }
}
},
recordLastEdit: function(vim, inputState, actionCommand) {
@@ -1510,7 +1443,7 @@
*/
// All of the functions below return Cursor objects.
var motions = {
- moveToTopLine: function(cm, motionArgs) {
+ moveToTopLine: function(cm, _head, motionArgs) {
var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;
return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
},
@@ -1519,17 +1452,17 @@
var line = Math.floor((range.top + range.bottom) * 0.5);
return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
},
- moveToBottomLine: function(cm, motionArgs) {
+ moveToBottomLine: function(cm, _head, motionArgs) {
var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;
return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
},
- expandToLine: function(cm, motionArgs) {
+ expandToLine: function(_cm, head, motionArgs) {
// Expands forward to end of line, and then to next line if repeat is
// >1. Does not handle backward motion!
- var cur = cm.getCursor();
+ var cur = head;
return Pos(cur.line + motionArgs.repeat - 1, Infinity);
},
- findNext: function(cm, motionArgs) {
+ findNext: function(cm, _head, motionArgs) {
var state = getSearchState(cm);
var query = state.getQuery();
if (!query) {
@@ -1541,7 +1474,7 @@
highlightSearchMatches(cm, query);
return findNext(cm, prev/** prev */, query, motionArgs.repeat);
},
- goToMark: function(cm, motionArgs, vim) {
+ goToMark: function(cm, _head, motionArgs, vim) {
var mark = vim.marks[motionArgs.selectedCharacter];
if (mark) {
var pos = mark.find();
@@ -1549,22 +1482,19 @@
}
return null;
},
- moveToOtherHighlightedEnd: function(cm, motionArgs, vim) {
- var ranges = cm.listSelections();
- var curEnd = cm.getCursor('head');
- var curStart = ranges[0].anchor;
- var curIndex = cursorEqual(ranges[0].head, curEnd) ? ranges.length-1 : 0;
- if (motionArgs.sameLine && vim.visualBlock) {
- curStart = Pos(curEnd.line, ranges[curIndex].anchor.ch);
- curEnd = Pos(ranges[curIndex].head.line, curEnd.ch);
+ moveToOtherHighlightedEnd: function(cm, _head, motionArgs, vim) {
+ if (vim.visualBlock && motionArgs.sameLine) {
+ var sel = vim.sel;
+ return [
+ clipCursorToContent(cm, Pos(sel.anchor.line, sel.head.ch)),
+ clipCursorToContent(cm, Pos(sel.head.line, sel.anchor.ch))
+ ];
} else {
- curStart = ranges[curIndex].anchor;
+ return ([vim.sel.head, vim.sel.anchor]);
}
- cm.setCursor(curEnd);
- return ([curEnd, curStart]);
},
- jumpToMark: function(cm, motionArgs, vim) {
- var best = cm.getCursor();
+ jumpToMark: function(cm, head, motionArgs, vim) {
+ var best = head;
for (var i = 0; i < motionArgs.repeat; i++) {
var cursor = best;
for (var key in vim.marks) {
@@ -1584,8 +1514,8 @@
var equal = cursorEqual(cursor, best);
var between = (motionArgs.forward) ?
- cusrorIsBetween(cursor, mark, best) :
- cusrorIsBetween(best, mark, cursor);
+ cursorIsBetween(cursor, mark, best) :
+ cursorIsBetween(best, mark, cursor);
if (equal || between) {
best = mark;
@@ -1601,14 +1531,14 @@
}
return best;
},
- moveByCharacters: function(cm, motionArgs) {
- var cur = cm.getCursor();
+ moveByCharacters: function(_cm, head, motionArgs) {
+ var cur = head;
var repeat = motionArgs.repeat;
var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;
return Pos(cur.line, ch);
},
- moveByLines: function(cm, motionArgs, vim) {
- var cur = cm.getCursor();
+ moveByLines: function(cm, head, motionArgs, vim) {
+ var cur = head;
var endCh = cur.ch;
// Depending what our last motion was, we may want to do different
// things. If our last motion was moving vertically, we want to
@@ -1643,8 +1573,8 @@
vim.lastHSPos = cm.charCoords(Pos(line, endCh),'div').left;
return Pos(line, endCh);
},
- moveByDisplayLines: function(cm, motionArgs, vim) {
- var cur = cm.getCursor();
+ moveByDisplayLines: function(cm, head, motionArgs, vim) {
+ var cur = head;
switch (vim.lastMotion) {
case this.moveByDisplayLines:
case this.moveByScroll:
@@ -1671,16 +1601,16 @@
vim.lastHPos = res.ch;
return res;
},
- moveByPage: function(cm, motionArgs) {
+ moveByPage: function(cm, head, motionArgs) {
// CodeMirror only exposes functions that move the cursor page down, so
// doing this bad hack to move the cursor and move it back. evalInput
// will move the cursor to where it should be in the end.
- var curStart = cm.getCursor();
+ var curStart = head;
var repeat = motionArgs.repeat;
return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page');
},
- moveByParagraph: function(cm, motionArgs) {
- var line = cm.getCursor().line;
+ moveByParagraph: function(cm, head, motionArgs) {
+ var line = head.line;
var repeat = motionArgs.repeat;
var inc = motionArgs.forward ? 1 : -1;
for (var i = 0; i < repeat; i++) {
@@ -1695,16 +1625,16 @@
}
return Pos(line, 0);
},
- moveByScroll: function(cm, motionArgs, vim) {
+ moveByScroll: function(cm, head, motionArgs, vim) {
var scrollbox = cm.getScrollInfo();
var curEnd = null;
var repeat = motionArgs.repeat;
if (!repeat) {
repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
}
- var orig = cm.charCoords(cm.getCursor(), 'local');
+ var orig = cm.charCoords(head, 'local');
motionArgs.repeat = repeat;
- var curEnd = motions.moveByDisplayLines(cm, motionArgs, vim);
+ var curEnd = motions.moveByDisplayLines(cm, head, motionArgs, vim);
if (!curEnd) {
return null;
}
@@ -1712,11 +1642,11 @@
cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
return curEnd;
},
- moveByWords: function(cm, motionArgs) {
- return moveToWord(cm, motionArgs.repeat, !!motionArgs.forward,
+ moveByWords: function(cm, head, motionArgs) {
+ return moveToWord(cm, head, motionArgs.repeat, !!motionArgs.forward,
!!motionArgs.wordEnd, !!motionArgs.bigWord);
},
- moveTillCharacter: function(cm, motionArgs) {
+ moveTillCharacter: function(cm, _head, motionArgs) {
var repeat = motionArgs.repeat;
var curEnd = moveToCharacter(cm, repeat, motionArgs.forward,
motionArgs.selectedCharacter);
@@ -1726,26 +1656,26 @@
curEnd.ch += increment;
return curEnd;
},
- moveToCharacter: function(cm, motionArgs) {
+ moveToCharacter: function(cm, head, motionArgs) {
var repeat = motionArgs.repeat;
recordLastCharacterSearch(0, motionArgs);
return moveToCharacter(cm, repeat, motionArgs.forward,
- motionArgs.selectedCharacter) || cm.getCursor();
+ motionArgs.selectedCharacter) || head;
},
- moveToSymbol: function(cm, motionArgs) {
+ moveToSymbol: function(cm, head, motionArgs) {
var repeat = motionArgs.repeat;
return findSymbol(cm, repeat, motionArgs.forward,
- motionArgs.selectedCharacter) || cm.getCursor();
+ motionArgs.selectedCharacter) || head;
},
- moveToColumn: function(cm, motionArgs, vim) {
+ moveToColumn: function(cm, head, motionArgs, vim) {
var repeat = motionArgs.repeat;
// repeat is equivalent to which column we want to move to!
vim.lastHPos = repeat - 1;
- vim.lastHSPos = cm.charCoords(cm.getCursor(),'div').left;
+ vim.lastHSPos = cm.charCoords(head,'div').left;
return moveToColumn(cm, repeat);
},
- moveToEol: function(cm, motionArgs, vim) {
- var cur = cm.getCursor();
+ moveToEol: function(cm, head, motionArgs, vim) {
+ var cur = head;
vim.lastHPos = Infinity;
var retval= Pos(cur.line + motionArgs.repeat - 1, Infinity);
var end=cm.clipPos(retval);
@@ -1753,15 +1683,15 @@
vim.lastHSPos = cm.charCoords(end,'div').left;
return retval;
},
- moveToFirstNonWhiteSpaceCharacter: function(cm) {
+ moveToFirstNonWhiteSpaceCharacter: function(cm, head) {
// Go to the start of the line where the text begins, or the end for
// whitespace-only lines
- var cursor = cm.getCursor();
+ var cursor = head;
return Pos(cursor.line,
findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)));
},
- moveToMatchedSymbol: function(cm) {
- var cursor = cm.getCursor();
+ moveToMatchedSymbol: function(cm, head) {
+ var cursor = head;
var line = cursor.line;
var ch = cursor.ch;
var lineText = cm.getLine(line);
@@ -1782,11 +1712,10 @@
return cursor;
}
},
- moveToStartOfLine: function(cm) {
- var cursor = cm.getCursor();
- return Pos(cursor.line, 0);
+ moveToStartOfLine: function(_cm, head) {
+ return Pos(head.line, 0);
},
- moveToLineOrEdgeOfDocument: function(cm, motionArgs) {
+ moveToLineOrEdgeOfDocument: function(cm, _head, motionArgs) {
var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine();
if (motionArgs.repeatIsExplicit) {
lineNum = motionArgs.repeat - cm.getOption('firstLineNumber');
@@ -1794,7 +1723,7 @@
return Pos(lineNum,
findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)));
},
- textObjectManipulation: function(cm, motionArgs) {
+ textObjectManipulation: function(cm, head, motionArgs) {
// TODO: lots of possible exceptions that can be thrown here. Try da(
// outside of a () block.
@@ -1823,9 +1752,9 @@
var tmp;
if (mirroredPairs[character]) {
- tmp = selectCompanionObject(cm, character, inclusive);
+ tmp = selectCompanionObject(cm, head, character, inclusive);
} else if (selfPaired[character]) {
- tmp = findBeginningAndEnd(cm, character, inclusive);
+ tmp = findBeginningAndEnd(cm, head, character, inclusive);
} else if (character === 'W') {
tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
true /** bigWord */);
@@ -1837,10 +1766,14 @@
return null;
}
- return [tmp.start, tmp.end];
+ if (!cm.state.vim.visualMode) {
+ return [tmp.start, tmp.end];
+ } else {
+ return expandSelection(cm, tmp.start, tmp.end);
+ }
},
- repeatLastCharacterSearch: function(cm, motionArgs) {
+ repeatLastCharacterSearch: function(cm, head, motionArgs) {
var lastSearch = vimGlobalState.lastChararacterSearch;
var repeat = motionArgs.repeat;
var forward = motionArgs.forward === lastSearch.forward;
@@ -1850,133 +1783,107 @@
var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);
if (!curEnd) {
cm.moveH(increment, 'char');
- return cm.getCursor();
+ return head;
}
curEnd.ch += increment;
return curEnd;
}
};
+ function fillArray(val, times) {
+ var arr = [];
+ for (var i = 0; i < times; i++) {
+ arr.push(val);
+ }
+ return arr;
+ }
+ /**
+ * An operator acts on a text selection. It receives the list of selections
+ * as input. The corresponding CodeMirror selection is guaranteed to
+ * match the input selection.
+ */
var operators = {
- change: function(cm, operatorArgs, vim) {
- var selections = cm.listSelections();
- var start = selections[0], end = selections[selections.length-1];
- var curStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head;
- var curEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor;
- var text = cm.getSelection();
- var visualBlock = vim.visualBlock;
- if (vim.lastSelection && !vim.visualMode) {
- visualBlock = vim.lastSelection.visualBlock ? true : visualBlock;
- }
- var lastInsertModeChanges = vimGlobalState.macroModeState.lastInsertModeChanges;
- lastInsertModeChanges.inVisualBlock = visualBlock;
- var replacement = new Array(selections.length).join('1').split('1');
- // save the selectionEnd mark
- var selectionEnd = vim.marks['>'] ? vim.marks['>'].find() : cm.getCursor('head');
- vimGlobalState.registerController.pushText(
- operatorArgs.registerName, 'change', text,
- operatorArgs.linewise);
- if (operatorArgs.linewise) {
- // 'C' in visual block extends the block till eol for all lines
- if (visualBlock){
- var startLine = curStart.line;
- while (startLine <= curEnd.line) {
- var endCh = lineLength(cm, startLine);
- var head = Pos(startLine, endCh);
- var anchor = Pos(startLine, curStart.ch);
- startLine++;
- cm.replaceRange('', anchor, head);
- }
- } else {
- // Push the next line back down, if there is a next line.
- replacement = '\n';
- if (curEnd.line == curStart.line && curEnd.line == cm.lastLine()) {
- replacement = '';
- }
- cm.replaceRange(replacement, curStart, curEnd);
- cm.indentLine(curStart.line, 'smart');
- // null ch so setCursor moves to end of line.
- curStart.ch = null;
- cm.setCursor(curStart);
- }
- } else {
- // Exclude trailing whitespace if the range is not all whitespace.
- var text = cm.getRange(curStart, curEnd);
+ change: function(cm, args, ranges) {
+ var finalHead, text;
+ var vim = cm.state.vim;
+ vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock = vim.visualBlock;
+ if (!vim.visualMode) {
+ var anchor = ranges[0].anchor,
+ head = ranges[0].head;
+ text = cm.getRange(anchor, head);
if (!isWhiteSpaceString(text)) {
+ // Exclude trailing whitespace if the range is not all whitespace.
var match = (/\s+$/).exec(text);
if (match) {
- curEnd = offsetCursor(curEnd, 0, - match[0].length);
+ head = offsetCursor(head, 0, - match[0].length);
+ text = text.slice(0, - match[0].length);
}
}
- if (visualBlock) {
- cm.replaceSelections(replacement);
- } else {
- cm.setCursor(curStart);
- cm.replaceRange('', curStart, curEnd);
+ var wasLastLine = head.line - 1 == cm.lastLine();
+ cm.replaceRange('', anchor, head);
+ if (args.linewise && !wasLastLine) {
+ // Push the next line back down, if there is a next line.
+ CodeMirror.commands.newlineAndIndent(cm);
+ // null ch so setCursor moves to end of line.
+ anchor.ch = null;
}
- }
- vim.marks['>'] = cm.setBookmark(selectionEnd);
- actions.enterInsertMode(cm, {}, cm.state.vim);
- },
- // delete is a javascript keyword.
- 'delete': function(cm, operatorArgs, vim) {
- var selections = cm.listSelections();
- var start = selections[0], end = selections[selections.length-1];
- var curStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head;
- var curEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor;
- // Save the '>' mark before cm.replaceRange clears it.
- var selectionEnd, selectionStart;
- var blockwise = vim.visualBlock;
- if (vim.visualMode) {
- selectionEnd = vim.marks['>'].find();
- selectionStart = vim.marks['<'].find();
- } else if (vim.lastSelection) {
- selectionEnd = vim.lastSelection.curStartMark.find();
- selectionStart = vim.lastSelection.curEndMark.find();
- blockwise = vim.lastSelection.visualBlock;
- }
- var text = cm.getSelection();
- vimGlobalState.registerController.pushText(
- operatorArgs.registerName, 'delete', text,
- operatorArgs.linewise, blockwise);
- var replacement = new Array(selections.length).join('1').split('1');
- // If the ending line is past the last line, inclusive, instead of
- // including the trailing \n, include the \n before the starting line
- if (operatorArgs.linewise &&
- curEnd.line == cm.lastLine() && curStart.line == curEnd.line) {
- var tmp = copyCursor(curEnd);
- curStart.line--;
- curStart.ch = lineLength(cm, curStart.line);
- curEnd = tmp;
- cm.replaceRange('', curStart, curEnd);
+ finalHead = anchor;
} else {
+ text = cm.getSelection();
+ var replacement = fillArray('', ranges.length);
cm.replaceSelections(replacement);
+ finalHead = cursorMin(ranges[0].head, ranges[0].anchor);
}
- // restore the saved bookmark
- if (selectionEnd) {
- var curStartMark = cm.setBookmark(selectionStart);
- var curEndMark = cm.setBookmark(selectionEnd);
- if (vim.visualMode) {
- vim.marks['<'] = curStartMark;
- vim.marks['>'] = curEndMark;
- } else {
- vim.lastSelection.curStartMark = curStartMark;
- vim.lastSelection.curEndMark = curEndMark;
+ vimGlobalState.registerController.pushText(
+ args.registerName, 'change', text,
+ args.linewise, ranges.length > 1);
+ actions.enterInsertMode(cm, {head: finalHead}, cm.state.vim);
+ },
+ // delete is a javascript keyword.
+ 'delete': function(cm, args, ranges) {
+ var finalHead, text;
+ var vim = cm.state.vim;
+ if (!vim.visualBlock) {
+ var anchor = ranges[0].anchor,
+ head = ranges[0].head;
+ if (args.linewise &&
+ head.line != cm.firstLine() &&
+ anchor.line == cm.lastLine() &&
+ anchor.line == head.line - 1) {
+ // Special case for dd on last line (and first line).
+ if (anchor.line == cm.firstLine()) {
+ anchor.ch = 0;
+ } else {
+ anchor = Pos(anchor.line - 1, lineLength(cm, anchor.line - 1));
+ }
+ }
+ text = cm.getRange(anchor, head);
+ cm.replaceRange('', anchor, head);
+ finalHead = anchor;
+ if (args.linewise) {
+ finalHead = motions.moveToFirstNonWhiteSpaceCharacter(cm, anchor);
}
- }
- if (operatorArgs.linewise) {
- cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
} else {
- cm.setCursor(curStart);
+ text = cm.getSelection();
+ var replacement = fillArray('', ranges.length);
+ cm.replaceSelections(replacement);
+ finalHead = ranges[0].anchor;
}
+ vimGlobalState.registerController.pushText(
+ args.registerName, 'delete', text,
+ args.linewise, vim.visualBlock);
+ return finalHead;
},
- indent: function(cm, operatorArgs, vim, curStart, curEnd) {
- var startLine = curStart.line;
- var endLine = curEnd.line;
+ indent: function(cm, args, ranges) {
+ var vim = cm.state.vim;
+ var startLine = ranges[0].anchor.line;
+ var endLine = vim.visualBlock ?
+ ranges[ranges.length - 1].anchor.line :
+ ranges[0].head.line;
// In visual mode, n> shifts the selection right n times, instead of
// shifting n lines right once.
- var repeat = (vim.visualMode) ? operatorArgs.repeat : 1;
- if (operatorArgs.linewise) {
+ var repeat = (vim.visualMode) ? args.repeat : 1;
+ if (args.linewise) {
// The only way to delete a newline is to delete until the start of
// the next line, so in linewise mode evalInput will include the next
// line. We don't want this in indent, so we go back a line.
@@ -1984,39 +1891,52 @@
}
for (var i = startLine; i <= endLine; i++) {
for (var j = 0; j < repeat; j++) {
- cm.indentLine(i, operatorArgs.indentRight);
+ cm.indentLine(i, args.indentRight);
}
}
- cm.setCursor(curStart);
- cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
+ return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);
},
- swapcase: function(cm, operatorArgs, _vim, _curStart, _curEnd, _curOriginal) {
+ changeCase: function(cm, args, ranges, oldAnchor, newHead) {
var selections = cm.getSelections();
- var ranges = cm.listSelections();
var swapped = [];
+ var toLower = args.toLower;
for (var j = 0; j < selections.length; j++) {
var toSwap = selections[j];
var text = '';
- for (var i = 0; i < toSwap.length; i++) {
- var character = toSwap.charAt(i);
- text += isUpperCase(character) ? character.toLowerCase() :
- character.toUpperCase();
+ if (toLower === true) {
+ text = toSwap.toLowerCase();
+ } else if (toLower === false) {
+ text = toSwap.toUpperCase();
+ } else {
+ for (var i = 0; i < toSwap.length; i++) {
+ var character = toSwap.charAt(i);
+ text += isUpperCase(character) ? character.toLowerCase() :
+ character.toUpperCase();
+ }
}
swapped.push(text);
}
cm.replaceSelections(swapped);
- var curStart = ranges[0].anchor;
- var curEnd = ranges[0].head;
- if (!operatorArgs.shouldMoveCursor) {
- cm.setCursor(cursorIsBefore(curStart, curEnd) ? curStart : curEnd);
+ if (args.shouldMoveCursor){
+ return newHead;
+ } else if (!cm.state.vim.visualMode && args.linewise && ranges[0].anchor.line + 1 == ranges[0].head.line) {
+ return motions.moveToFirstNonWhiteSpaceCharacter(cm, oldAnchor);
+ } else if (args.linewise){
+ return oldAnchor;
+ } else {
+ return cursorMin(ranges[0].anchor, ranges[0].head);
}
},
- yank: function(cm, operatorArgs, vim, _curStart, _curEnd, curOriginal) {
+ yank: function(cm, args, ranges, oldAnchor) {
+ var vim = cm.state.vim;
var text = cm.getSelection();
+ var endPos = vim.visualMode
+ ? cursorMin(vim.sel.anchor, vim.sel.head, ranges[0].head, ranges[0].anchor)
+ : oldAnchor;
vimGlobalState.registerController.pushText(
- operatorArgs.registerName, 'yank',
- text, operatorArgs.linewise, vim.visualBlock);
- cm.setCursor(curOriginal);
+ args.registerName, 'yank',
+ text, args.linewise, vim.visualBlock);
+ return endPos;
}
};
@@ -2108,41 +2028,40 @@
vim.insertMode = true;
vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1;
var insertAt = (actionArgs) ? actionArgs.insertAt : null;
- if (vim.visualMode) {
- var selections = getSelectedAreaRange(cm, vim);
- var selectionStart = selections[0];
- var selectionEnd = selections[1];
- }
+ var sel = vim.sel;
+ var head = actionArgs.head || cm.getCursor('head');
+ var height = cm.listSelections().length;
if (insertAt == 'eol') {
- var cursor = cm.getCursor();
- cursor = Pos(cursor.line, lineLength(cm, cursor.line));
- cm.setCursor(cursor);
+ head = Pos(head.line, lineLength(cm, head.line));
} else if (insertAt == 'charAfter') {
- cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
+ head = offsetCursor(head, 0, 1);
} else if (insertAt == 'firstNonBlank') {
- if (vim.visualMode && !vim.visualBlock) {
- if (selectionEnd.line < selectionStart.line) {
- cm.setCursor(selectionEnd);
+ head = motions.moveToFirstNonWhiteSpaceCharacter(cm, head);
+ } else if (insertAt == 'startOfSelectedArea') {
+ if (!vim.visualBlock) {
+ if (sel.head.line < sel.anchor.line) {
+ head = sel.head;
} else {
- selectionStart = Pos(selectionStart.line, 0);
- cm.setCursor(selectionStart);
+ head = Pos(sel.anchor.line, 0);
}
- cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
- } else if (vim.visualBlock) {
- selectionEnd = Pos(selectionEnd.line, selectionStart.ch);
- cm.setCursor(selectionStart);
- selectBlock(cm, selectionEnd);
} else {
- cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
+ head = Pos(
+ Math.min(sel.head.line, sel.anchor.line),
+ Math.min(sel.head.ch, sel.anchor.ch));
+ height = Math.abs(sel.head.line - sel.anchor.line) + 1;
}
} else if (insertAt == 'endOfSelectedArea') {
- if (vim.visualBlock) {
- selectionStart = Pos(selectionStart.line, selectionEnd.ch);
- cm.setCursor(selectionStart);
- selectBlock(cm, selectionEnd);
- } else if (selectionEnd.line < selectionStart.line) {
- selectionEnd = Pos(selectionStart.line, 0);
- cm.setCursor(selectionEnd);
+ if (!vim.visualBlock) {
+ if (sel.head.line >= sel.anchor.line) {
+ head = offsetCursor(sel.head, 0, 1);
+ } else {
+ head = Pos(sel.anchor.line, 0);
+ }
+ } else {
+ head = Pos(
+ Math.min(sel.head.line, sel.anchor.line),
+ Math.max(sel.head.ch + 1, sel.anchor.ch));
+ height = Math.abs(sel.head.line - sel.anchor.line) + 1;
}
} else if (insertAt == 'inplace') {
if (vim.visualMode){
@@ -2168,129 +2087,68 @@
if (vim.visualMode) {
exitVisualMode(cm);
}
+ selectForInsert(cm, head, height);
},
toggleVisualMode: function(cm, actionArgs, vim) {
var repeat = actionArgs.repeat;
- var curStart = cm.getCursor();
- var curEnd;
- var selections = cm.listSelections();
+ var anchor = cm.getCursor();
+ var head;
// TODO: The repeat should actually select number of characters/lines
// equal to the repeat times the size of the previous visual
// operation.
if (!vim.visualMode) {
- cm.on('mousedown', exitVisualMode);
+ // Entering visual mode
vim.visualMode = true;
vim.visualLine = !!actionArgs.linewise;
vim.visualBlock = !!actionArgs.blockwise;
- if (vim.visualLine) {
- curStart.ch = 0;
- curEnd = clipCursorToContent(
- cm, Pos(curStart.line + repeat - 1, lineLength(cm, curStart.line)),
- true /** includeLineBreak */);
- } else {
- curEnd = clipCursorToContent(
- cm, Pos(curStart.line, curStart.ch + repeat),
+ head = clipCursorToContent(
+ cm, Pos(anchor.line, anchor.ch + repeat - 1),
true /** includeLineBreak */);
- }
- cm.setSelection(curStart, curEnd);
- CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : ""});
+ vim.sel = {
+ anchor: anchor,
+ head: head
+ };
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
+ updateCmSelection(cm);
+ updateMark(cm, vim, '<', cursorMin(anchor, head));
+ updateMark(cm, vim, '>', cursorMax(anchor, head));
+ } else if (vim.visualLine ^ actionArgs.linewise ||
+ vim.visualBlock ^ actionArgs.blockwise) {
+ // Toggling between modes
+ vim.visualLine = !!actionArgs.linewise;
+ vim.visualBlock = !!actionArgs.blockwise;
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
+ updateCmSelection(cm);
} else {
- curStart = cm.getCursor('anchor');
- curEnd = cm.getCursor('head');
- if (vim.visualLine) {
- if (actionArgs.blockwise) {
- // This means Ctrl-V pressed in linewise visual
- vim.visualBlock = true;
- selectBlock(cm, curEnd);
- CodeMirror.signal(cm, 'vim-mode-change', {mode: 'visual', subMode: 'blockwise'});
- } else if (!actionArgs.linewise) {
- // v pressed in linewise, switch to characterwise visual mode
- CodeMirror.signal(cm, 'vim-mode-change', {mode: 'visual'});
- } else {
- exitVisualMode(cm);
- }
- vim.visualLine = false;
- } else if (vim.visualBlock) {
- if (actionArgs.linewise) {
- // Shift-V pressed in blockwise visual mode
- vim.visualLine = true;
- curStart = Pos(selections[0].anchor.line, 0);
- curEnd = Pos(selections[selections.length-1].anchor.line, lineLength(cm, selections[selections.length-1].anchor.line));
- cm.setSelection(curStart, curEnd);
- CodeMirror.signal(cm, 'vim-mode-change', {mode: 'visual', subMode: 'linewise'});
- } else if (!actionArgs.blockwise) {
- // v pressed in blockwise mode, Switch to characterwise
- if (curEnd != selections[0].head) {
- curStart = selections[0].anchor;
- } else {
- curStart = selections[selections.length-1].anchor;
- }
- cm.setSelection(curStart, curEnd);
- CodeMirror.signal(cm, 'vim-mode-change', {mode: 'visual'});
- } else {
- exitVisualMode(cm);
- }
- vim.visualBlock = false;
- } else if (actionArgs.linewise) {
- // Shift-V pressed in characterwise visual mode. Switch to linewise
- // visual mode instead of exiting visual mode.
- vim.visualLine = true;
- curStart.ch = cursorIsBefore(curStart, curEnd) ? 0 :
- lineLength(cm, curStart.line);
- curEnd.ch = cursorIsBefore(curStart, curEnd) ?
- lineLength(cm, curEnd.line) : 0;
- cm.setSelection(curStart, curEnd);
- CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: "linewise"});
- } else if (actionArgs.blockwise) {
- vim.visualBlock = true;
- selectBlock(cm, curEnd);
- CodeMirror.signal(cm, 'vim-mode-change', {mode: 'visual', subMode: 'blockwise'});
- } else {
- exitVisualMode(cm);
- }
+ exitVisualMode(cm);
}
- updateMark(cm, vim, '<', cursorIsBefore(curStart, curEnd) ? curStart
- : curEnd);
- updateMark(cm, vim, '>', cursorIsBefore(curStart, curEnd) ? curEnd
- : curStart);
},
reselectLastSelection: function(cm, _actionArgs, vim) {
- var curStart = vim.marks['<'].find();
- var curEnd = vim.marks['>'].find();
var lastSelection = vim.lastSelection;
+ if (vim.visualMode) {
+ updateLastSelection(cm, vim);
+ }
if (lastSelection) {
- // Set the selections as per last selection
- var selectionStart = lastSelection.curStartMark.find();
- var selectionEnd = lastSelection.curEndMark.find();
- var blockwise = lastSelection.visualBlock;
- // update last selection
- updateLastSelection(cm, vim, curStart, curEnd);
- if (blockwise) {
- cm.setCursor(selectionStart);
- selectionStart = selectBlock(cm, selectionEnd);
- } else {
- cm.setSelection(selectionStart, selectionEnd);
- selectionStart = cm.getCursor('anchor');
- selectionEnd = cm.getCursor('head');
- }
- if (vim.visualMode) {
- updateMark(cm, vim, '<', cursorIsBefore(selectionStart, selectionEnd) ? selectionStart
- : selectionEnd);
- updateMark(cm, vim, '>', cursorIsBefore(selectionStart, selectionEnd) ? selectionEnd
- : selectionStart);
+ var anchor = lastSelection.anchorMark.find();
+ var head = lastSelection.headMark.find();
+ if (!anchor || !head) {
+ // If the marks have been destroyed due to edits, do nothing.
+ return;
}
- // Last selection is updated now
+ vim.sel = {
+ anchor: anchor,
+ head: head
+ };
vim.visualMode = true;
- if (lastSelection.visualLine) {
- vim.visualLine = true;
- vim.visualBlock = false;
- } else if (lastSelection.visualBlock) {
- vim.visualLine = false;
- vim.visualBlock = true;
- } else {
- vim.visualBlock = vim.visualLine = false;
- }
- CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : ""});
+ vim.visualLine = lastSelection.visualLine;
+ vim.visualBlock = lastSelection.visualBlock;
+ updateCmSelection(cm);
+ updateMark(cm, vim, '<', cursorMin(anchor, head));
+ updateMark(cm, vim, '>', cursorMax(anchor, head));
+ CodeMirror.signal(cm, 'vim-mode-change', {
+ mode: 'visual',
+ subMode: vim.visualLine ? 'linewise' :
+ vim.visualBlock ? 'blockwise' : ''});
}
},
joinLines: function(cm, actionArgs, vim) {
@@ -2307,18 +2165,19 @@
Infinity));
}
var finalCh = 0;
- cm.operation(function() {
- for (var i = curStart.line; i < curEnd.line; i++) {
- finalCh = lineLength(cm, curStart.line);
- var tmp = Pos(curStart.line + 1,
- lineLength(cm, curStart.line + 1));
- var text = cm.getRange(curStart, tmp);
- text = text.replace(/\n\s*/g, ' ');
- cm.replaceRange(text, curStart, tmp);
- }
- var curFinalPos = Pos(curStart.line, finalCh);
- cm.setCursor(curFinalPos);
- });
+ for (var i = curStart.line; i < curEnd.line; i++) {
+ finalCh = lineLength(cm, curStart.line);
+ var tmp = Pos(curStart.line + 1,
+ lineLength(cm, curStart.line + 1));
+ var text = cm.getRange(curStart, tmp);
+ text = text.replace(/\n\s*/g, ' ');
+ cm.replaceRange(text, curStart, tmp);
+ }
+ var curFinalPos = Pos(curStart.line, finalCh);
+ cm.setCursor(curFinalPos);
+ if (vim.visualMode) {
+ exitVisualMode(cm);
+ }
},
newLineAndEnterInsertMode: function(cm, actionArgs, vim) {
vim.insertMode = true;
@@ -2347,11 +2206,12 @@
return;
}
if (actionArgs.matchIndent) {
- // length that considers tabs and cm.options.tabSize
+ var tabSize = cm.getOption("tabSize");
+ // length that considers tabs and tabSize
var whitespaceLength = function(str) {
var tabs = (str.split("\t").length - 1);
var spaces = (str.split(" ").length - 1);
- return tabs * cm.options.tabSize + spaces * 1;
+ return tabs * tabSize + spaces * 1;
};
var currentLine = cm.getLine(cm.getCursor().line);
var indent = whitespaceLength(currentLine.match(/^\s*/)[0]);
@@ -2364,8 +2224,8 @@
if (newIndent < 0) {
return "";
}
- else if (cm.options.indentWithTabs) {
- var quotient = Math.floor(newIndent / cm.options.tabSize);
+ else if (cm.getOption("indentWithTabs")) {
+ var quotient = Math.floor(newIndent / tabSize);
return Array(quotient + 1).join('\t');
}
else {
@@ -2413,7 +2273,7 @@
var emptyStrings = new Array(selections.length).join('1').split('1');
// save the curEnd marker before it get cleared due to cm.replaceRange.
if (vim.lastSelection) {
- lastSelectionCurEnd = vim.lastSelection.curEndMark.find();
+ lastSelectionCurEnd = vim.lastSelection.headMark.find();
}
// push the previously selected text to unnamed register
vimGlobalState.registerController.unnamedRegister.setText(selectedText);
@@ -2437,7 +2297,7 @@
}
// restore the the curEnd marker
if(lastSelectionCurEnd) {
- vim.lastSelection.curEndMark = cm.setBookmark(lastSelectionCurEnd);
+ vim.lastSelection.headMark = cm.setBookmark(lastSelectionCurEnd);
}
if (linewise) {
curPosFinal.ch=0;
@@ -2479,10 +2339,10 @@
}
}
}
- cm.setCursor(curPosFinal);
if (vim.visualMode) {
exitVisualMode(cm);
}
+ cm.setCursor(curPosFinal);
},
undo: function(cm, actionArgs) {
cm.operation(function() {
@@ -2527,7 +2387,7 @@
replaceWithStr = replaceWithStr.replace(/[^\n]/g, replaceWith);
if (vim.visualBlock) {
// Tabs are split in visua block before replacing
- var spaces = new Array(cm.options.tabSize+1).join(' ');
+ var spaces = new Array(cm.getOption("tabSize")+1).join(' ');
replaceWithStr = cm.getSelection();
replaceWithStr = replaceWithStr.replace(/\t/g, spaces).replace(/[^\n]/g, replaceWith).split('\n');
cm.replaceSelections(replaceWithStr);
@@ -2583,28 +2443,7 @@
}
repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);
},
- changeCase: function(cm, actionArgs, vim) {
- var selectionStart = getSelectedAreaRange(cm, vim)[0];
- var text = cm.getSelection();
- var lastSelectionCurEnd;
- var blockSelection;
- if (vim.lastSelection) {
- // save the curEnd marker to avoid its removal due to cm.replaceRange
- lastSelectionCurEnd = vim.lastSelection.curEndMark.find();
- blockSelection = vim.lastSelection.visualBlock;
- }
- var toLower = actionArgs.toLower;
- text = toLower ? text.toLowerCase() : text.toUpperCase();
- cm.replaceSelections(vim.visualBlock || blockSelection ? text.split('\n') : [text]);
- // restore the last selection curEnd marker
- if (lastSelectionCurEnd) {
- vim.lastSelection.curEndMark = cm.setBookmark(lastSelectionCurEnd);
- }
- cm.setCursor(selectionStart);
- if (vim.visualMode) {
- exitVisualMode(cm);
- }
- }
+ exitInsertMode: exitInsertMode
};
/*
@@ -2632,16 +2471,66 @@
return ret;
}
function offsetCursor(cur, offsetLine, offsetCh) {
+ if (typeof offsetLine === 'object') {
+ offsetCh = offsetLine.ch;
+ offsetLine = offsetLine.line;
+ }
return Pos(cur.line + offsetLine, cur.ch + offsetCh);
}
- function matchKeysPartial(pressed, mapped) {
- for (var i = 0; i < pressed.length; i++) {
- // 'character' means any character. For mark, register commads, etc.
- if (pressed[i] != mapped[i] && mapped[i] != 'character') {
- return false;
+ function getOffset(anchor, head) {
+ return {
+ line: head.line - anchor.line,
+ ch: head.line - anchor.line
+ };
+ }
+ function commandMatches(keys, keyMap, context, inputState) {
+ // Partial matches are not applied. They inform the key handler
+ // that the current key sequence is a subsequence of a valid key
+ // sequence, so that the key buffer is not cleared.
+ var match, partial = [], full = [];
+ for (var i = 0; i < keyMap.length; i++) {
+ var command = keyMap[i];
+ if (context == 'insert' && command.context != 'insert' ||
+ command.context && command.context != context ||
+ inputState.operator && command.type == 'action' ||
+ !(match = commandMatch(keys, command.keys))) { continue; }
+ if (match == 'partial') { partial.push(command); }
+ if (match == 'full') { full.push(command); }
+ }
+ return {
+ partial: partial.length && partial,
+ full: full.length && full
+ };
+ }
+ function commandMatch(pressed, mapped) {
+ if (mapped.slice(-11) == '') {
+ // Last character matches anything.
+ var prefixLen = mapped.length - 11;
+ var pressedPrefix = pressed.slice(0, prefixLen);
+ var mappedPrefix = mapped.slice(0, prefixLen);
+ return pressedPrefix == mappedPrefix && pressed.length > prefixLen ? 'full' :
+ mappedPrefix.indexOf(pressedPrefix) == 0 ? 'partial' : false;
+ } else {
+ return pressed == mapped ? 'full' :
+ mapped.indexOf(pressed) == 0 ? 'partial' : false;
+ }
+ }
+ function lastChar(keys) {
+ var match = /^.*(<[\w\-]+>)$/.exec(keys);
+ var selectedCharacter = match ? match[1] : keys.slice(-1);
+ if (selectedCharacter.length > 1){
+ switch(selectedCharacter){
+ case '':
+ selectedCharacter='\n';
+ break;
+ case '':
+ selectedCharacter=' ';
+ break;
+ default:
+ break;
}
}
- return true;
+ return selectedCharacter;
}
function repeatFn(cm, fn, repeat) {
return function() {
@@ -2665,7 +2554,19 @@
}
return false;
}
- function cusrorIsBetween(cur1, cur2, cur3) {
+ function cursorMin(cur1, cur2) {
+ if (arguments.length > 2) {
+ cur2 = cursorMin.apply(undefined, Array.prototype.slice.call(arguments, 1));
+ }
+ return cursorIsBefore(cur1, cur2) ? cur1 : cur2;
+ }
+ function cursorMax(cur1, cur2) {
+ if (arguments.length > 2) {
+ cur2 = cursorMax.apply(undefined, Array.prototype.slice.call(arguments, 1));
+ }
+ return cursorIsBefore(cur1, cur2) ? cur2 : cur1;
+ }
+ function cursorIsBetween(cur1, cur2, cur3) {
// returns true if cur2 is between cur1 and cur3.
var cur1before2 = cursorIsBefore(cur1, cur2);
var cur2before3 = cursorIsBefore(cur2, cur3);
@@ -2700,121 +2601,59 @@
// Distance between selectionEnd.ch and any(first considered here) selection.ch
function selectBlock(cm, selectionEnd) {
var selections = [], ranges = cm.listSelections();
- var firstRange = ranges[0].anchor, lastRange = ranges[ranges.length-1].anchor;
- var start, end, direction, selectionStart;
- var curEnd = cm.getCursor('head');
- var originalSelectionEnd = copyCursor(selectionEnd);
- start = firstRange.line;
- end = lastRange.line;
- if (selectionEnd.line < curEnd.line) {
- direction = 'up';
- } else if (selectionEnd.line > curEnd.line) {
- direction = 'down';
- } else {
- if (selectionEnd.ch != curEnd.ch) {
- direction = selectionEnd.ch > curEnd.ch ? 'right' : 'left';
- }
- selectionStart = cm.getCursor('anchor');
- }
- var primIndex = getIndex(ranges, curEnd);
- // sets to true when selectionEnd already lies inside the existing selections
- selectionEnd = cm.clipPos(selectionEnd);
- var contains = getIndex(ranges, selectionEnd) < 0 ? false : true;
- var isClipped = !cursorEqual(originalSelectionEnd, selectionEnd);
- // This function helps to check selection crossing
- // in case of short lines.
- var processSelectionCrossing = function() {
- if (isClipped) {
- if (curEnd.ch >= selectionStart.ch) {
- selectionStart.ch++;
- }
- } else if (curEnd.ch == lineLength(cm, curEnd.line)) {
- if (cursorEqual(ranges[primIndex].anchor, ranges[primIndex].head) && ranges.length>1) {
- if (direction == 'up') {
- if (contains || primIndex>0) {
- start = firstRange.line;
- end = selectionEnd.line;
- selectionStart = ranges[primIndex-1].anchor;
- }
- } else {
- if (contains || primIndex == 0) {
- end = lastRange.line;
- start = selectionEnd.line;
- selectionStart = ranges[primIndex+1].anchor;
- }
- }
- if (selectionEnd.ch >= selectionStart.ch) {
- selectionStart.ch--;
- }
- }
- }
- };
- switch(direction) {
- case 'up':
- start = contains ? firstRange.line : selectionEnd.line;
- end = contains ? selectionEnd.line : lastRange.line;
- selectionStart = lastRange;
- processSelectionCrossing();
- break;
- case 'down':
- start = contains ? selectionEnd.line : firstRange.line;
- end = contains ? lastRange.line : selectionEnd.line;
- selectionStart = firstRange;
- processSelectionCrossing();
- break;
- case 'left':
- if ((selectionEnd.ch <= selectionStart.ch) && (curEnd.ch > selectionStart.ch)) {
- selectionStart.ch++;
- selectionEnd.ch--;
- }
- break;
- case 'right':
- if ((selectionStart.ch <= selectionEnd.ch) && (curEnd.ch < selectionStart.ch)) {
- selectionStart.ch--;
- selectionEnd.ch++;
- }
- break;
- default:
- start = selectionStart.line;
- end = selectionEnd.line;
- }
- while (start <= end) {
- var anchor = {line: start, ch: selectionStart.ch};
- var head = {line: start, ch: selectionEnd.ch};
- var range = {anchor: anchor, head: head};
+ var head = copyCursor(cm.clipPos(selectionEnd));
+ var isClipped = !cursorEqual(selectionEnd, head);
+ var curHead = cm.getCursor('head');
+ var primIndex = getIndex(ranges, curHead);
+ var wasClipped = cursorEqual(ranges[primIndex].head, ranges[primIndex].anchor);
+ var max = ranges.length - 1;
+ var index = max - primIndex > primIndex ? max : 0;
+ var base = ranges[index].anchor;
+
+ var firstLine = Math.min(base.line, head.line);
+ var lastLine = Math.max(base.line, head.line);
+ var baseCh = base.ch, headCh = head.ch;
+
+ var dir = ranges[index].head.ch - baseCh;
+ var newDir = headCh - baseCh;
+ if (dir > 0 && newDir <= 0) {
+ baseCh++;
+ if (!isClipped) { headCh--; }
+ } else if (dir < 0 && newDir >= 0) {
+ baseCh--;
+ if (!wasClipped) { headCh++; }
+ } else if (dir < 0 && newDir == -1) {
+ baseCh--;
+ headCh++;
+ }
+ for (var line = firstLine; line <= lastLine; line++) {
+ var range = {anchor: new Pos(line, baseCh), head: new Pos(line, headCh)};
selections.push(range);
- if (cursorEqual(head, selectionEnd)) {
- primIndex = selections.indexOf(range);
- }
- start++;
}
- // Update selectionEnd and selectionStart
- // after selection crossing
- selectionEnd.ch = selections[0].head.ch;
- selectionStart.ch = selections[0].anchor.ch;
- if (cursorEqual(selectionEnd, selections[0].head)) {
- selectionStart.line = selections[selections.length-1].anchor.line;
- } else {
- selectionStart.line = selections[0].anchor.line;
+ primIndex = head.line == lastLine ? selections.length - 1 : 0;
+ cm.setSelections(selections);
+ selectionEnd.ch = headCh;
+ base.ch = baseCh;
+ return base;
+ }
+ function selectForInsert(cm, head, height) {
+ var sel = [];
+ for (var i = 0; i < height; i++) {
+ var lineHead = offsetCursor(head, i, 0);
+ sel.push({anchor: lineHead, head: lineHead});
}
- cm.setSelections(selections, primIndex);
- return selectionStart;
+ cm.setSelections(sel, 0);
}
// getIndex returns the index of the cursor in the selections.
function getIndex(ranges, cursor, end) {
- var pos = -1;
for (var i = 0; i < ranges.length; i++) {
- var atAnchor = cursorEqual(ranges[i].anchor, cursor);
- var atHead = cursorEqual(ranges[i].head, cursor);
- if (end == 'head') {
- pos = atHead ? i : pos;
- } else if (end == 'anchor') {
- pos = atAnchor ? i : pos;
- } else {
- pos = (atAnchor || atHead) ? i : pos;
+ var atAnchor = end != 'head' && cursorEqual(ranges[i].anchor, cursor);
+ var atHead = end != 'anchor' && cursorEqual(ranges[i].head, cursor);
+ if (atAnchor || atHead) {
+ return i;
}
}
- return pos;
+ return -1;
}
function getSelectedAreaRange(cm, vim) {
var lastSelection = vim.lastSelection;
@@ -2845,8 +2684,8 @@
}
cm.setSelections(selections);
} else {
- var start = lastSelection.curStartMark.find();
- var end = lastSelection.curEndMark.find();
+ var start = lastSelection.anchorMark.find();
+ var end = lastSelection.headMark.find();
var line = end.line - start.line;
var ch = end.ch - start.ch;
selectionEnd = {line: selectionEnd.line + line, ch: line ? selectionEnd.ch : ch + selectionEnd.ch};
@@ -2865,51 +2704,133 @@
return getCurrentSelectedAreaRange();
}
}
- function updateLastSelection(cm, vim, selectionStart, selectionEnd) {
- if (!selectionStart || !selectionEnd) {
- selectionStart = vim.marks['<'].find() || cm.getCursor('anchor');
- selectionEnd = vim.marks['>'].find() || cm.getCursor('head');
- }
+ // Updates the previous selection with the current selection's values. This
+ // should only be called in visual mode.
+ function updateLastSelection(cm, vim) {
+ var anchor = vim.sel.anchor;
+ var head = vim.sel.head;
// To accommodate the effect of lastPastedText in the last selection
if (vim.lastPastedText) {
- selectionEnd = cm.posFromIndex(cm.indexFromPos(selectionStart) + vim.lastPastedText.length);
+ head = cm.posFromIndex(cm.indexFromPos(anchor) + vim.lastPastedText.length);
vim.lastPastedText = null;
}
- var ranges = cm.listSelections();
- // This check ensures to set the cursor
- // position where we left off in previous selection
- var swap = getIndex(ranges, selectionStart, 'head') > -1;
- if (vim.visualBlock) {
- var height = Math.abs(selectionStart.line - selectionEnd.line)+1;
- var width = Math.abs(selectionStart.ch - selectionEnd.ch);
- var block = {height: height, width: width};
- }
- // can't use selection state here because yank has already reset its cursor
- // Also, Bookmarks make the visual selections robust to edit operations
- vim.lastSelection = {'curStartMark': cm.setBookmark(swap ? selectionEnd : selectionStart),
- 'curEndMark': cm.setBookmark(swap ? selectionStart : selectionEnd),
+ vim.lastSelection = {'anchorMark': cm.setBookmark(anchor),
+ 'headMark': cm.setBookmark(head),
+ 'anchor': copyCursor(anchor),
+ 'head': copyCursor(head),
'visualMode': vim.visualMode,
'visualLine': vim.visualLine,
- 'visualBlock': block};
+ 'visualBlock': vim.visualBlock};
+ }
+ function expandSelection(cm, start, end) {
+ var sel = cm.state.vim.sel;
+ var head = sel.head;
+ var anchor = sel.anchor;
+ var tmp;
+ if (cursorIsBefore(end, start)) {
+ tmp = end;
+ end = start;
+ start = tmp;
+ }
+ if (cursorIsBefore(head, anchor)) {
+ head = cursorMin(start, head);
+ anchor = cursorMax(anchor, end);
+ } else {
+ anchor = cursorMin(start, anchor);
+ head = cursorMax(head, end);
+ head = offsetCursor(head, 0, -1);
+ if (head.ch == -1 && head.line != cm.firstLine()) {
+ head = Pos(head.line - 1, lineLength(cm, head.line - 1));
+ }
+ }
+ return [anchor, head];
+ }
+ /**
+ * Updates the CodeMirror selection to match the provided vim selection.
+ * If no arguments are given, it uses the current vim selection state.
+ */
+ function updateCmSelection(cm, sel, mode) {
+ var vim = cm.state.vim;
+ sel = sel || vim.sel;
+ var mode = mode ||
+ vim.visualLine ? 'line' : vim.visualBlock ? 'block' : 'char';
+ var cmSel = makeCmSelection(cm, sel, mode);
+ cm.setSelections(cmSel.ranges, cmSel.primary);
+ updateFakeCursor(cm);
+ }
+ function makeCmSelection(cm, sel, mode, exclusive) {
+ var head = copyCursor(sel.head);
+ var anchor = copyCursor(sel.anchor);
+ if (mode == 'char') {
+ var headOffset = !exclusive && !cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
+ var anchorOffset = cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
+ head = offsetCursor(sel.head, 0, headOffset);
+ anchor = offsetCursor(sel.anchor, 0, anchorOffset);
+ return {
+ ranges: [{anchor: anchor, head: head}],
+ primary: 0
+ };
+ } else if (mode == 'line') {
+ if (!cursorIsBefore(sel.head, sel.anchor)) {
+ anchor.ch = 0;
+
+ var lastLine = cm.lastLine();
+ if (head.line > lastLine) {
+ head.line = lastLine;
+ }
+ head.ch = lineLength(cm, head.line);
+ } else {
+ head.ch = 0;
+ anchor.ch = lineLength(cm, anchor.line);
+ }
+ return {
+ ranges: [{anchor: anchor, head: head}],
+ primary: 0
+ };
+ } else if (mode == 'block') {
+ var top = Math.min(anchor.line, head.line),
+ left = Math.min(anchor.ch, head.ch),
+ bottom = Math.max(anchor.line, head.line),
+ right = Math.max(anchor.ch, head.ch) + 1;
+ var height = bottom - top + 1;
+ var primary = head.line == top ? 0 : height - 1;
+ var ranges = [];
+ for (var i = 0; i < height; i++) {
+ ranges.push({
+ anchor: Pos(top + i, left),
+ head: Pos(top + i, right)
+ });
+ }
+ return {
+ ranges: ranges,
+ primary: primary
+ };
+ }
+ }
+ function getHead(cm) {
+ var cur = cm.getCursor('head');
+ if (cm.getSelection().length == 1) {
+ // Small corner case when only 1 character is selected. The "real"
+ // head is the left of head and anchor.
+ cur = cursorMin(cur, cm.getCursor('anchor'));
+ }
+ return cur;
}
- function exitVisualMode(cm) {
- cm.off('mousedown', exitVisualMode);
+ /**
+ * If moveHead is set to false, the CodeMirror selection will not be
+ * touched. The caller assumes the responsibility of putting the cursor
+ * in the right place.
+ */
+ function exitVisualMode(cm, moveHead) {
var vim = cm.state.vim;
- var selectionStart = cm.getCursor('anchor');
- var selectionEnd = cm.getCursor('head');
- // hack to place the cursor at the right place
- // in case of visual block
- if (vim.visualBlock && (cursorIsBefore(selectionStart, selectionEnd))) {
- selectionEnd.ch--;
+ if (moveHead !== false) {
+ cm.setCursor(clipCursorToContent(cm, vim.sel.head));
}
updateLastSelection(cm, vim);
vim.visualMode = false;
vim.visualLine = false;
vim.visualBlock = false;
- if (!cursorEqual(selectionStart, selectionEnd)) {
- cm.setCursor(clipCursorToContent(cm, selectionEnd));
- }
CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
if (vim.fakeCursor) {
vim.fakeCursor.clear();
@@ -2964,7 +2885,7 @@
}
function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) {
- var cur = cm.getCursor();
+ var cur = getHead(cm);
var line = cm.getLine(cur.line);
var idx = cur.ch;
@@ -3239,6 +3160,7 @@
/**
* @param {CodeMirror} cm CodeMirror object.
+ * @param {Pos} cur The position to start from.
* @param {int} repeat Number of words to move past.
* @param {boolean} forward True to search forward. False to search
* backward.
@@ -3248,8 +3170,7 @@
* False if only alphabet characters count as part of the word.
* @return {Cursor} The position the cursor should move to.
*/
- function moveToWord(cm, repeat, forward, wordEnd, bigWord) {
- var cur = cm.getCursor();
+ function moveToWord(cm, cur, repeat, forward, wordEnd, bigWord) {
var curStart = copyCursor(cur);
var words = [];
if (forward && !wordEnd || !forward && wordEnd) {
@@ -3349,8 +3270,8 @@
// TODO: perhaps this finagling of start and end positions belonds
// in codmirror/replaceRange?
- function selectCompanionObject(cm, symb, inclusive) {
- var cur = cm.getCursor(), start, end;
+ function selectCompanionObject(cm, head, symb, inclusive) {
+ var cur = head, start, end;
var bracketRegexp = ({
'(': /[()]/, ')': /[()]/,
@@ -3394,8 +3315,8 @@
// Takes in a symbol and a cursor and tries to simulate text objects that
// have identical opening and closing symbols
// TODO support across multiple lines
- function findBeginningAndEnd(cm, symb, inclusive) {
- var cur = copyCursor(cm.getCursor());
+ function findBeginningAndEnd(cm, head, symb, inclusive) {
+ var cur = copyCursor(head);
var line = cm.getLine(cur.line);
var chars = line.split('');
var start, end, i, len;
@@ -3828,6 +3749,7 @@
// shortNames must not match the prefix of the other command.
var defaultExCommandMap = [
{ name: 'map' },
+ { name: 'imap', shortName: 'im' },
{ name: 'nmap', shortName: 'nm' },
{ name: 'vmap', shortName: 'vm' },
{ name: 'unmap' },
@@ -3842,10 +3764,10 @@
{ name: 'registers', shortName: 'reg', excludeFromCommandHistory: true },
{ name: 'global', shortName: 'g' }
];
- Vim.ExCommandDispatcher = function() {
+ var ExCommandDispatcher = function() {
this.buildCommandMap_();
};
- Vim.ExCommandDispatcher.prototype = {
+ ExCommandDispatcher.prototype = {
processCommand: function(cm, input, opt_params) {
var vim = cm.state.vim;
var commandHistoryRegister = vimGlobalState.registerController.getRegister(':');
@@ -3882,7 +3804,7 @@
if (command.type == 'exToKey') {
// Handle Ex to Key mapping.
for (var i = 0; i < command.toKeys.length; i++) {
- CodeMirror.Vim.handleKey(cm, command.toKeys[i]);
+ CodeMirror.Vim.handleKey(cm, command.toKeys[i], 'mapping');
}
return;
} else if (command.type == 'exToEx') {
@@ -4006,7 +3928,7 @@
this.commandMap_[commandName] = {
name: commandName,
type: 'exToKey',
- toKeys: parseKeyString(rhs),
+ toKeys: rhs,
user: true
};
}
@@ -4014,7 +3936,7 @@
if (rhs != ':' && rhs.charAt(0) == ':') {
// Key to Ex mapping.
var mapping = {
- keys: parseKeyString(lhs),
+ keys: lhs,
type: 'keyToEx',
exArgs: { input: rhs.substring(1) },
user: true};
@@ -4023,9 +3945,9 @@
} else {
// Key to key mapping
var mapping = {
- keys: parseKeyString(lhs),
+ keys: lhs,
type: 'keyToKey',
- toKeys: parseKeyString(rhs),
+ toKeys: rhs,
user: true
};
if (ctx) { mapping.context = ctx; }
@@ -4034,15 +3956,6 @@
}
},
unmap: function(lhs, ctx) {
- var arrayEquals = function(a, b) {
- if (a === b) return true;
- if (a == null || b == null) return true;
- if (a.length != b.length) return false;
- for (var i = 0; i < a.length; i++) {
- if (a[i] !== b[i]) return false;
- }
- return true;
- };
if (lhs != ':' && lhs.charAt(0) == ':') {
// Ex to Ex or Ex to key mapping
if (ctx) { throw Error('Mode not supported for ex mappings'); }
@@ -4053,9 +3966,9 @@
}
} else {
// Key to Ex or key to key mapping
- var keys = parseKeyString(lhs);
+ var keys = lhs;
for (var i = 0; i < defaultKeymap.length; i++) {
- if (arrayEquals(keys, defaultKeymap[i].keys)
+ if (keys == defaultKeymap[i].keys
&& defaultKeymap[i].context === ctx
&& defaultKeymap[i].user) {
defaultKeymap.splice(i, 1);
@@ -4067,21 +3980,6 @@
}
};
- // Converts a key string sequence of the form abd into Vim's
- // keymap representation.
- function parseKeyString(str) {
- var key, match;
- var keys = [];
- while (str) {
- match = (/<\w+-.+?>|<\w+>|./).exec(str);
- if (match === null)break;
- key = match[0];
- str = str.substring(match.index + key.length);
- keys.push(key);
- }
- return keys;
- }
-
var exCommands = {
map: function(cm, params, ctx) {
var mapArgs = params.args;
@@ -4093,6 +3991,7 @@
}
exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx);
},
+ imap: function(cm, params) { this.map(cm, params, 'insert'); },
nmap: function(cm, params) { this.map(cm, params, 'normal'); },
vmap: function(cm, params) { this.map(cm, params, 'visual'); },
unmap: function(cm, params, ctx) {
@@ -4467,7 +4366,7 @@
}
};
- var exCommandDispatcher = new Vim.ExCommandDispatcher();
+ var exCommandDispatcher = new ExCommandDispatcher();
/**
* @param {CodeMirror} cm CodeMirror instance we are in.
@@ -4555,6 +4454,7 @@
break;
}
if (done) { stop(close); }
+ return true;
}
// Actually do replace.
@@ -4574,65 +4474,10 @@
});
}
- // Register Vim with CodeMirror
- function buildVimKeyMap() {
- /**
- * Handle the raw key event from CodeMirror. Translate the
- * Shift + key modifier to the resulting letter, while preserving other
- * modifers.
- */
- function cmKeyToVimKey(key, modifier) {
- var vimKey = key;
- if (isUpperCase(vimKey) && modifier == 'Ctrl') {
- vimKey = vimKey.toLowerCase();
- }
- if (modifier) {
- // Vim will parse modifier+key combination as a single key.
- vimKey = modifier.charAt(0) + '-' + vimKey;
- }
- var specialKey = ({Enter:'CR',Backspace:'BS',Delete:'Del'})[vimKey];
- vimKey = specialKey ? specialKey : vimKey;
- vimKey = vimKey.length > 1 ? '<'+ vimKey + '>' : vimKey;
- return vimKey;
- }
-
- // Closure to bind CodeMirror, key, modifier.
- function keyMapper(vimKey) {
- return function(cm) {
- CodeMirror.signal(cm, 'vim-keypress', vimKey);
- CodeMirror.Vim.handleKey(cm, vimKey);
- };
- }
-
- var cmToVimKeymap = {
- 'nofallthrough': true,
- 'style': 'fat-cursor'
- };
- function bindKeys(keys, modifier) {
- for (var i = 0; i < keys.length; i++) {
- var key = keys[i];
- if (!modifier && key.length == 1) {
- // Wrap all keys without modifiers with '' to identify them by their
- // key characters instead of key identifiers.
- key = "'" + key + "'";
- }
- var vimKey = cmKeyToVimKey(keys[i], modifier);
- var cmKey = modifier ? modifier + '-' + key : key;
- cmToVimKeymap[cmKey] = keyMapper(vimKey);
- }
- }
- bindKeys(upperCaseAlphabet);
- bindKeys(lowerCaseAlphabet);
- bindKeys(upperCaseAlphabet, 'Ctrl');
- bindKeys(specialSymbols);
- bindKeys(specialSymbols, 'Ctrl');
- bindKeys(numbers);
- bindKeys(numbers, 'Ctrl');
- bindKeys(specialKeys);
- bindKeys(specialKeys, 'Ctrl');
- return cmToVimKeymap;
- }
- CodeMirror.keyMap.vim = buildVimKeyMap();
+ CodeMirror.keyMap.vim = {
+ attach: attachVimMap,
+ detach: detachVimMap
+ };
function exitInsertMode(cm) {
var vim = cm.state.vim;
@@ -4688,63 +4533,13 @@
}
}
- defineOption('enableInsertModeEscKeys', false, 'boolean');
- // Use this option to customize the two-character ESC keymap.
- // If you want to use characters other than i j or k you'll have to add
- // lines to the vim-insert and await-second keymaps later in this file.
- defineOption('insertModeEscKeys', 'kj', 'string');
// The timeout in milliseconds for the two-character ESC keymap should be
// adjusted according to your typing speed to prevent false positives.
defineOption('insertModeEscKeysTimeout', 200, 'number');
- function firstEscCharacterHandler(ch) {
- return function(cm){
- var keys = getOption('insertModeEscKeys');
- var firstEscCharacter = keys && keys.length > 1 && keys.charAt(0);
- if (!getOption('enableInsertModeEscKeys')|| firstEscCharacter !== ch) {
- return CodeMirror.Pass;
- } else {
- cm.replaceRange(ch, cm.getCursor(), cm.getCursor(), "+input");
- cm.setOption('keyMap', 'await-second');
- cm.state.vim.awaitingEscapeSecondCharacter = true;
- setTimeout(
- function(){
- if(cm.state.vim.awaitingEscapeSecondCharacter) {
- cm.state.vim.awaitingEscapeSecondCharacter = false;
- cm.setOption('keyMap', 'vim-insert');
- }
- },
- getOption('insertModeEscKeysTimeout'));
- }
- };
- }
- function secondEscCharacterHandler(ch){
- return function(cm) {
- var keys = getOption('insertModeEscKeys');
- var secondEscCharacter = keys && keys.length > 1 && keys.charAt(1);
- if (!getOption('enableInsertModeEscKeys')|| secondEscCharacter !== ch) {
- return CodeMirror.Pass;
- // This is not the handler you're looking for. Just insert as usual.
- } else {
- if (cm.state.vim.insertMode) {
- var lastChange = vimGlobalState.macroModeState.lastInsertModeChanges;
- if (lastChange && lastChange.changes.length) {
- lastChange.changes.pop();
- }
- }
- cm.state.vim.awaitingEscapeSecondCharacter = false;
- cm.replaceRange('', {ch: cm.getCursor().ch - 1, line: cm.getCursor().line},
- cm.getCursor(), "+input");
- exitInsertMode(cm);
- }
- };
- }
CodeMirror.keyMap['vim-insert'] = {
// TODO: override navigation keys so that Esc will cancel automatic
// indentation from o, O, i_
- 'Esc': exitInsertMode,
- 'Ctrl-[': exitInsertMode,
- 'Ctrl-C': exitInsertMode,
'Ctrl-N': 'autocomplete',
'Ctrl-P': 'autocomplete',
'Enter': function(cm) {
@@ -4752,26 +4547,22 @@
CodeMirror.commands.newlineAndIndent;
fn(cm);
},
- // The next few lines are where you'd add additional handlers if
- // you wanted to use keys other than i j and k for two-character
- // escape sequences. Don't forget to add them in the await-second
- // section as well.
- "'i'": firstEscCharacterHandler('i'),
- "'j'": firstEscCharacterHandler('j'),
- "'k'": firstEscCharacterHandler('k'),
- fallthrough: ['default']
+ fallthrough: ['default'],
+ attach: attachVimMap,
+ detach: detachVimMap
};
CodeMirror.keyMap['await-second'] = {
- "'i'": secondEscCharacterHandler('i'),
- "'j'": secondEscCharacterHandler('j'),
- "'k'": secondEscCharacterHandler('k'),
- fallthrough: ['vim-insert']
+ fallthrough: ['vim-insert'],
+ attach: attachVimMap,
+ detach: detachVimMap
};
CodeMirror.keyMap['vim-replace'] = {
'Backspace': 'goCharLeft',
- fallthrough: ['vim-insert']
+ fallthrough: ['vim-insert'],
+ attach: attachVimMap,
+ detach: detachVimMap
};
function executeMacroRegister(cm, vim, macroModeState, registerName) {
@@ -4789,7 +4580,7 @@
match = (/<\w+-.+?>|<\w+>|./).exec(text);
key = match[0];
text = text.substring(match.index + key.length);
- CodeMirror.Vim.handleKey(cm, key);
+ CodeMirror.Vim.handleKey(cm, key, 'macro');
if (vim.insertMode) {
var changes = register.insertModeChanges[imc++].changes;
vimGlobalState.macroModeState.lastInsertModeChanges.changes =
@@ -4866,28 +4657,49 @@
// Cursor moved outside the context of an edit. Reset the change.
lastChange.changes = [];
}
- } else if (cm.doc.history.lastSelOrigin == '*mouse') {
- // Reset lastHPos if mouse click was done in normal mode.
- vim.lastHPos = cm.doc.getCursor().ch;
- if (cm.somethingSelected()) {
- // If something is still selected, enter visual mode.
- vim.visualMode = true;
- }
+ } else if (!cm.curOp.isVimOp) {
+ handleExternalSelection(cm, vim);
}
if (vim.visualMode) {
- var from, head;
- from = head = cm.getCursor('head');
- var anchor = cm.getCursor('anchor');
- var to = Pos(head.line, from.ch + (cursorIsBefore(anchor, head) ? -1 : 1));
- if (cursorIsBefore(to, from)) {
- var temp = from;
- from = to;
- to = temp;
- }
- if (vim.fakeCursor) {
- vim.fakeCursor.clear();
- }
- vim.fakeCursor = cm.markText(from, to, {className: 'cm-animate-fat-cursor'});
+ updateFakeCursor(cm);
+ }
+ }
+ function updateFakeCursor(cm) {
+ var vim = cm.state.vim;
+ var from = copyCursor(vim.sel.head);
+ var to = offsetCursor(from, 0, 1);
+ if (vim.fakeCursor) {
+ vim.fakeCursor.clear();
+ }
+ vim.fakeCursor = cm.markText(from, to, {className: 'cm-animate-fat-cursor'});
+ }
+ function handleExternalSelection(cm, vim) {
+ var anchor = cm.getCursor('anchor');
+ var head = cm.getCursor('head');
+ // Enter or exit visual mode to match mouse selection.
+ if (vim.visualMode && cursorEqual(head, anchor) && lineLength(cm, head.line) > head.ch) {
+ exitVisualMode(cm, false);
+ } else if (!vim.visualMode && !vim.insertMode && cm.somethingSelected()) {
+ vim.visualMode = true;
+ vim.visualLine = false;
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
+ }
+ if (vim.visualMode) {
+ // Bind CodeMirror selection model to vim selection model.
+ // Mouse selections are considered visual characterwise.
+ var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0;
+ var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0;
+ head = offsetCursor(head, 0, headOffset);
+ anchor = offsetCursor(anchor, 0, anchorOffset);
+ vim.sel = {
+ anchor: anchor,
+ head: head
+ };
+ updateMark(cm, vim, '<', cursorMin(head, anchor));
+ updateMark(cm, vim, '>', cursorMax(head, anchor));
+ } else if (!vim.insertMode) {
+ // Reset lastHPos if selection was modified by something outside of vim mode e.g. by mouse.
+ vim.lastHPos = cm.getCursor().ch;
}
}
@@ -4910,7 +4722,7 @@
return true;
}
if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
- CodeMirror.lookupKey(keyName, ['vim-insert'], onKeyFound);
+ CodeMirror.lookupKey(keyName, 'vim-insert', onKeyFound);
}
}
@@ -4979,32 +4791,33 @@
}
return true;
}
- var curStart = cm.getCursor();
+ var head = cm.getCursor('head');
var inVisualBlock = vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock;
if (inVisualBlock) {
// Set up block selection again for repeating the changes.
var vim = cm.state.vim;
- var block = vim.lastSelection.visualBlock;
- var curEnd = Pos(curStart.line + block.height-1, curStart.ch);
- cm.setCursor(curStart);
- selectBlock(cm, curEnd);
+ var lastSel = vim.lastSelection;
+ var offset = getOffset(lastSel.anchor, lastSel.head);
+ selectForInsert(cm, head, offset.line + 1);
repeat = cm.listSelections().length;
- cm.setCursor(curStart);
+ cm.setCursor(head);
}
for (var i = 0; i < repeat; i++) {
+ if (inVisualBlock) {
+ cm.setCursor(offsetCursor(head, i, 0));
+ }
for (var j = 0; j < changes.length; j++) {
var change = changes[j];
if (change instanceof InsertModeKey) {
- CodeMirror.lookupKey(change.keyName, ['vim-insert'], keyHandler);
+ CodeMirror.lookupKey(change.keyName, 'vim-insert', keyHandler);
} else {
var cur = cm.getCursor();
cm.replaceRange(change, cur, cur);
}
}
- if (inVisualBlock) {
- curStart.line++;
- cm.setCursor(curStart);
- }
+ }
+ if (inVisualBlock) {
+ cm.setCursor(offsetCursor(head, 0, 1));
}
}
diff --git a/media/editors/codemirror/lib/addons-uncompressed.js b/media/editors/codemirror/lib/addons-uncompressed.js
index a35cf1e9b8723..433020a6af715 100644
--- a/media/editors/codemirror/lib/addons-uncompressed.js
+++ b/media/editors/codemirror/lib/addons-uncompressed.js
@@ -127,31 +127,32 @@
};
var closingBrackets = "";
for (var i = 0; i < pairs.length; i += 2) (function(left, right) {
- if (left != right) closingBrackets += right;
+ closingBrackets += right;
map["'" + left + "'"] = function(cm) {
if (cm.getOption("disableInput")) return CodeMirror.Pass;
var ranges = cm.listSelections(), type, next;
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i], cur = range.head, curType;
var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1));
- if (!range.empty())
+ if (!range.empty()) {
curType = "surround";
- else if (left == right && next == right) {
+ } else if (left == right && next == right) {
if (cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == left + left + left)
curType = "skipThree";
else
curType = "skip";
} else if (left == right && cur.ch > 1 &&
cm.getRange(Pos(cur.line, cur.ch - 2), cur) == left + left &&
- (cur.ch <= 2 || cm.getRange(Pos(cur.line, cur.ch - 3), Pos(cur.line, cur.ch - 2)) != left))
+ (cur.ch <= 2 || cm.getRange(Pos(cur.line, cur.ch - 3), Pos(cur.line, cur.ch - 2)) != left)) {
curType = "addFour";
- else if (left == '"' || left == "'") {
+ } else if (left == '"' || left == "'") {
if (!CodeMirror.isWordChar(next) && enteringString(cm, cur, left)) curType = "both";
else return CodeMirror.Pass;
- } else if (cm.getLine(cur.line).length == cur.ch || closingBrackets.indexOf(next) >= 0 || SPACE_CHAR_REGEX.test(next))
+ } else if (cm.getLine(cur.line).length == cur.ch || closingBrackets.indexOf(next) >= 0 || SPACE_CHAR_REGEX.test(next)) {
curType = "both";
- else
+ } else {
return CodeMirror.Pass;
+ }
if (!type) type = curType;
else if (type != curType) return CodeMirror.Pass;
}
@@ -1128,12 +1129,12 @@ CodeMirror.registerHelper("fold", "include", function(cm, start) {
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
- mod(require("../../lib/codemirror"));
+ mod(require("../../lib/codemirror"), "cjs");
else if (typeof define == "function" && define.amd) // AMD
- define(["../../lib/codemirror"], mod);
+ define(["../../lib/codemirror"], function(CM) { mod(CM, "amd"); });
else // Plain browser env
- mod(CodeMirror);
-})(function(CodeMirror) {
+ mod(CodeMirror, "plain");
+})(function(CodeMirror, env) {
if (!CodeMirror.modeURL) CodeMirror.modeURL = "../mode/%N/%N.js";
var loading = {};
@@ -1160,21 +1161,24 @@ CodeMirror.registerHelper("fold", "include", function(cm, start) {
if (CodeMirror.modes.hasOwnProperty(mode)) return ensureDeps(mode, cont);
if (loading.hasOwnProperty(mode)) return loading[mode].push(cont);
- var script = document.createElement("script");
- script.src = CodeMirror.modeURL.replace(/%N/g, mode);
- var others = document.getElementsByTagName("script")[0];
- others.parentNode.insertBefore(script, others);
- var list = loading[mode] = [cont];
- var count = 0, poll = setInterval(function() {
- if (++count > 100) return clearInterval(poll);
- if (CodeMirror.modes.hasOwnProperty(mode)) {
- clearInterval(poll);
- loading[mode] = null;
+ var file = CodeMirror.modeURL.replace(/%N/g, mode);
+ if (env == "plain") {
+ var script = document.createElement("script");
+ script.src = file;
+ var others = document.getElementsByTagName("script")[0];
+ var list = loading[mode] = [cont];
+ CodeMirror.on(script, "load", function() {
ensureDeps(mode, function() {
for (var i = 0; i < list.length; ++i) list[i]();
});
- }
- }, 200);
+ });
+ others.parentNode.insertBefore(script, others);
+ } else if (env == "cjs") {
+ require(file);
+ cont();
+ } else if (env == "amd") {
+ requirejs([file], cont);
+ }
};
CodeMirror.autoLoadMode = function(instance, mode) {
@@ -1447,305 +1451,253 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
var defaultKeymap = [
// Key to key mapping. This goes first to make it possible to override
// existing mappings.
- { keys: [''], type: 'keyToKey', toKeys: ['h'] },
- { keys: [''], type: 'keyToKey', toKeys: ['l'] },
- { keys: [''], type: 'keyToKey', toKeys: ['k'] },
- { keys: [''], type: 'keyToKey', toKeys: ['j'] },
- { keys: [''], type: 'keyToKey', toKeys: ['l'] },
- { keys: [''], type: 'keyToKey', toKeys: ['h'] },
- { keys: [''], type: 'keyToKey', toKeys: ['W'] },
- { keys: [''], type: 'keyToKey', toKeys: ['B'] },
- { keys: [''], type: 'keyToKey', toKeys: ['w'] },
- { keys: [''], type: 'keyToKey', toKeys: ['b'] },
- { keys: [''], type: 'keyToKey', toKeys: ['j'] },
- { keys: [''], type: 'keyToKey', toKeys: ['k'] },
- { keys: [''], type: 'keyToKey', toKeys: [''] },
- { keys: [''], type: 'keyToKey', toKeys: [''] },
- { keys: ['s'], type: 'keyToKey', toKeys: ['c', 'l'], context: 'normal' },
- { keys: ['s'], type: 'keyToKey', toKeys: ['x', 'i'], context: 'visual'},
- { keys: ['S'], type: 'keyToKey', toKeys: ['c', 'c'], context: 'normal' },
- { keys: ['S'], type: 'keyToKey', toKeys: ['d', 'c', 'c'], context: 'visual' },
- { keys: [''], type: 'keyToKey', toKeys: ['0'] },
- { keys: [''], type: 'keyToKey', toKeys: ['$'] },
- { keys: [''], type: 'keyToKey', toKeys: [''] },
- { keys: [''], type: 'keyToKey', toKeys: [''] },
- { keys: [''], type: 'keyToKey', toKeys: ['j', '^'], context: 'normal' },
+ { keys: '', type: 'keyToKey', toKeys: 'h' },
+ { keys: '', type: 'keyToKey', toKeys: 'l' },
+ { keys: '', type: 'keyToKey', toKeys: 'k' },
+ { keys: '', type: 'keyToKey', toKeys: 'j' },
+ { keys: '', type: 'keyToKey', toKeys: 'l' },
+ { keys: '', type: 'keyToKey', toKeys: 'h' },
+ { keys: '', type: 'keyToKey', toKeys: 'W' },
+ { keys: '', type: 'keyToKey', toKeys: 'B' },
+ { keys: '', type: 'keyToKey', toKeys: 'w' },
+ { keys: '', type: 'keyToKey', toKeys: 'b' },
+ { keys: '', type: 'keyToKey', toKeys: 'j' },
+ { keys: '', type: 'keyToKey', toKeys: 'k' },
+ { keys: '', type: 'keyToKey', toKeys: '' },
+ { keys: '', type: 'keyToKey', toKeys: '' },
+ { keys: '', type: 'keyToKey', toKeys: '', context: 'insert' },
+ { keys: '', type: 'keyToKey', toKeys: '', context: 'insert' },
+ { keys: 's', type: 'keyToKey', toKeys: 'cl', context: 'normal' },
+ { keys: 's', type: 'keyToKey', toKeys: 'xi', context: 'visual'},
+ { keys: 'S', type: 'keyToKey', toKeys: 'cc', context: 'normal' },
+ { keys: 'S', type: 'keyToKey', toKeys: 'dcc', context: 'visual' },
+ { keys: '', type: 'keyToKey', toKeys: '0' },
+ { keys: '', type: 'keyToKey', toKeys: '$' },
+ { keys: '', type: 'keyToKey', toKeys: '' },
+ { keys: '', type: 'keyToKey', toKeys: '' },
+ { keys: '', type: 'keyToKey', toKeys: 'j^', context: 'normal' },
// Motions
- { keys: ['H'], type: 'motion',
- motion: 'moveToTopLine',
- motionArgs: { linewise: true, toJumplist: true }},
- { keys: ['M'], type: 'motion',
- motion: 'moveToMiddleLine',
- motionArgs: { linewise: true, toJumplist: true }},
- { keys: ['L'], type: 'motion',
- motion: 'moveToBottomLine',
- motionArgs: { linewise: true, toJumplist: true }},
- { keys: ['h'], type: 'motion',
- motion: 'moveByCharacters',
- motionArgs: { forward: false }},
- { keys: ['l'], type: 'motion',
- motion: 'moveByCharacters',
- motionArgs: { forward: true }},
- { keys: ['j'], type: 'motion',
- motion: 'moveByLines',
- motionArgs: { forward: true, linewise: true }},
- { keys: ['k'], type: 'motion',
- motion: 'moveByLines',
- motionArgs: { forward: false, linewise: true }},
- { keys: ['g','j'], type: 'motion',
- motion: 'moveByDisplayLines',
- motionArgs: { forward: true }},
- { keys: ['g','k'], type: 'motion',
- motion: 'moveByDisplayLines',
- motionArgs: { forward: false }},
- { keys: ['w'], type: 'motion',
- motion: 'moveByWords',
- motionArgs: { forward: true, wordEnd: false }},
- { keys: ['W'], type: 'motion',
- motion: 'moveByWords',
- motionArgs: { forward: true, wordEnd: false, bigWord: true }},
- { keys: ['e'], type: 'motion',
- motion: 'moveByWords',
- motionArgs: { forward: true, wordEnd: true, inclusive: true }},
- { keys: ['E'], type: 'motion',
- motion: 'moveByWords',
- motionArgs: { forward: true, wordEnd: true, bigWord: true,
- inclusive: true }},
- { keys: ['b'], type: 'motion',
- motion: 'moveByWords',
- motionArgs: { forward: false, wordEnd: false }},
- { keys: ['B'], type: 'motion',
- motion: 'moveByWords',
- motionArgs: { forward: false, wordEnd: false, bigWord: true }},
- { keys: ['g', 'e'], type: 'motion',
- motion: 'moveByWords',
- motionArgs: { forward: false, wordEnd: true, inclusive: true }},
- { keys: ['g', 'E'], type: 'motion',
- motion: 'moveByWords',
- motionArgs: { forward: false, wordEnd: true, bigWord: true,
- inclusive: true }},
- { keys: ['{'], type: 'motion', motion: 'moveByParagraph',
- motionArgs: { forward: false, toJumplist: true }},
- { keys: ['}'], type: 'motion', motion: 'moveByParagraph',
- motionArgs: { forward: true, toJumplist: true }},
- { keys: [''], type: 'motion',
- motion: 'moveByPage', motionArgs: { forward: true }},
- { keys: [''], type: 'motion',
- motion: 'moveByPage', motionArgs: { forward: false }},
- { keys: [''], type: 'motion',
- motion: 'moveByScroll',
- motionArgs: { forward: true, explicitRepeat: true }},
- { keys: [''], type: 'motion',
- motion: 'moveByScroll',
- motionArgs: { forward: false, explicitRepeat: true }},
- { keys: ['g', 'g'], type: 'motion',
- motion: 'moveToLineOrEdgeOfDocument',
- motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},
- { keys: ['G'], type: 'motion',
- motion: 'moveToLineOrEdgeOfDocument',
- motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},
- { keys: ['0'], type: 'motion', motion: 'moveToStartOfLine' },
- { keys: ['^'], type: 'motion',
- motion: 'moveToFirstNonWhiteSpaceCharacter' },
- { keys: ['+'], type: 'motion',
- motion: 'moveByLines',
- motionArgs: { forward: true, toFirstChar:true }},
- { keys: ['-'], type: 'motion',
- motion: 'moveByLines',
- motionArgs: { forward: false, toFirstChar:true }},
- { keys: ['_'], type: 'motion',
- motion: 'moveByLines',
- motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},
- { keys: ['$'], type: 'motion',
- motion: 'moveToEol',
- motionArgs: { inclusive: true }},
- { keys: ['%'], type: 'motion',
- motion: 'moveToMatchedSymbol',
- motionArgs: { inclusive: true, toJumplist: true }},
- { keys: ['f', 'character'], type: 'motion',
- motion: 'moveToCharacter',
- motionArgs: { forward: true , inclusive: true }},
- { keys: ['F', 'character'], type: 'motion',
- motion: 'moveToCharacter',
- motionArgs: { forward: false }},
- { keys: ['t', 'character'], type: 'motion',
- motion: 'moveTillCharacter',
- motionArgs: { forward: true, inclusive: true }},
- { keys: ['T', 'character'], type: 'motion',
- motion: 'moveTillCharacter',
- motionArgs: { forward: false }},
- { keys: [';'], type: 'motion', motion: 'repeatLastCharacterSearch',
- motionArgs: { forward: true }},
- { keys: [','], type: 'motion', motion: 'repeatLastCharacterSearch',
- motionArgs: { forward: false }},
- { keys: ['\'', 'character'], type: 'motion', motion: 'goToMark',
- motionArgs: {toJumplist: true, linewise: true}},
- { keys: ['`', 'character'], type: 'motion', motion: 'goToMark',
- motionArgs: {toJumplist: true}},
- { keys: [']', '`'], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
- { keys: ['[', '`'], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
- { keys: [']', '\''], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
- { keys: ['[', '\''], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
+ { keys: 'H', type: 'motion', motion: 'moveToTopLine', motionArgs: { linewise: true, toJumplist: true }},
+ { keys: 'M', type: 'motion', motion: 'moveToMiddleLine', motionArgs: { linewise: true, toJumplist: true }},
+ { keys: 'L', type: 'motion', motion: 'moveToBottomLine', motionArgs: { linewise: true, toJumplist: true }},
+ { keys: 'h', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: false }},
+ { keys: 'l', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: true }},
+ { keys: 'j', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, linewise: true }},
+ { keys: 'k', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, linewise: true }},
+ { keys: 'gj', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: true }},
+ { keys: 'gk', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: false }},
+ { keys: 'w', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false }},
+ { keys: 'W', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false, bigWord: true }},
+ { keys: 'e', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, inclusive: true }},
+ { keys: 'E', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, bigWord: true, inclusive: true }},
+ { keys: 'b', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }},
+ { keys: 'B', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false, bigWord: true }},
+ { keys: 'ge', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, inclusive: true }},
+ { keys: 'gE', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, bigWord: true, inclusive: true }},
+ { keys: '{', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: false, toJumplist: true }},
+ { keys: '}', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: true, toJumplist: true }},
+ { keys: '', type: 'motion', motion: 'moveByPage', motionArgs: { forward: true }},
+ { keys: '', type: 'motion', motion: 'moveByPage', motionArgs: { forward: false }},
+ { keys: '', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: true, explicitRepeat: true }},
+ { keys: '', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: false, explicitRepeat: true }},
+ { keys: 'gg', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},
+ { keys: 'G', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},
+ { keys: '0', type: 'motion', motion: 'moveToStartOfLine' },
+ { keys: '^', type: 'motion', motion: 'moveToFirstNonWhiteSpaceCharacter' },
+ { keys: '+', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true }},
+ { keys: '-', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, toFirstChar:true }},
+ { keys: '_', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},
+ { keys: '$', type: 'motion', motion: 'moveToEol', motionArgs: { inclusive: true }},
+ { keys: '%', type: 'motion', motion: 'moveToMatchedSymbol', motionArgs: { inclusive: true, toJumplist: true }},
+ { keys: 'f', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: true , inclusive: true }},
+ { keys: 'F', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: false }},
+ { keys: 't', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: true, inclusive: true }},
+ { keys: 'T', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: false }},
+ { keys: ';', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: true }},
+ { keys: ',', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: false }},
+ { keys: '\'', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true, linewise: true}},
+ { keys: '`', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true}},
+ { keys: ']`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
+ { keys: '[`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
+ { keys: ']\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
+ { keys: '[\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
// the next two aren't motions but must come before more general motion declarations
- { keys: [']', 'p'], type: 'action', action: 'paste', isEdit: true,
- actionArgs: { after: true, isEdit: true, matchIndent: true}},
- { keys: ['[', 'p'], type: 'action', action: 'paste', isEdit: true,
- actionArgs: { after: false, isEdit: true, matchIndent: true}},
- { keys: [']', 'character'], type: 'motion',
- motion: 'moveToSymbol',
- motionArgs: { forward: true, toJumplist: true}},
- { keys: ['[', 'character'], type: 'motion',
- motion: 'moveToSymbol',
- motionArgs: { forward: false, toJumplist: true}},
- { keys: ['|'], type: 'motion',
- motion: 'moveToColumn',
- motionArgs: { }},
- { keys: ['o'], type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: { }, context:'visual'},
- { keys: ['O'], type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: {sameLine: true}, context:'visual'},
+ { keys: ']p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true, matchIndent: true}},
+ { keys: '[p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true, matchIndent: true}},
+ { keys: ']', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: true, toJumplist: true}},
+ { keys: '[', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: false, toJumplist: true}},
+ { keys: '|', type: 'motion', motion: 'moveToColumn'},
+ { keys: 'o', type: 'motion', motion: 'moveToOtherHighlightedEnd', context:'visual'},
+ { keys: 'O', type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: {sameLine: true}, context:'visual'},
// Operators
- { keys: ['d'], type: 'operator', operator: 'delete' },
- { keys: ['y'], type: 'operator', operator: 'yank' },
- { keys: ['c'], type: 'operator', operator: 'change' },
- { keys: ['>'], type: 'operator', operator: 'indent',
- operatorArgs: { indentRight: true }},
- { keys: ['<'], type: 'operator', operator: 'indent',
- operatorArgs: { indentRight: false }},
- { keys: ['g', '~'], type: 'operator', operator: 'swapcase' },
- { keys: ['n'], type: 'motion', motion: 'findNext',
- motionArgs: { forward: true, toJumplist: true }},
- { keys: ['N'], type: 'motion', motion: 'findNext',
- motionArgs: { forward: false, toJumplist: true }},
+ { keys: 'd', type: 'operator', operator: 'delete' },
+ { keys: 'y', type: 'operator', operator: 'yank' },
+ { keys: 'c', type: 'operator', operator: 'change' },
+ { keys: '>', type: 'operator', operator: 'indent', operatorArgs: { indentRight: true }},
+ { keys: '<', type: 'operator', operator: 'indent', operatorArgs: { indentRight: false }},
+ { keys: 'g~', type: 'operator', operator: 'changeCase' },
+ { keys: 'gu', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, isEdit: true },
+ { keys: 'gU', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, isEdit: true },
+ { keys: 'n', type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: true }},
+ { keys: 'N', type: 'motion', motion: 'findNext', motionArgs: { forward: false, toJumplist: true }},
// Operator-Motion dual commands
- { keys: ['x'], type: 'operatorMotion', operator: 'delete',
- motion: 'moveByCharacters', motionArgs: { forward: true },
- operatorMotionArgs: { visualLine: false }},
- { keys: ['X'], type: 'operatorMotion', operator: 'delete',
- motion: 'moveByCharacters', motionArgs: { forward: false },
- operatorMotionArgs: { visualLine: true }},
- { keys: ['D'], type: 'operatorMotion', operator: 'delete',
- motion: 'moveToEol', motionArgs: { inclusive: true },
- operatorMotionArgs: { visualLine: true }},
- { keys: ['Y'], type: 'operatorMotion', operator: 'yank',
- motion: 'moveToEol', motionArgs: { inclusive: true },
- operatorMotionArgs: { visualLine: true }},
- { keys: ['C'], type: 'operatorMotion',
- operator: 'change',
- motion: 'moveToEol', motionArgs: { inclusive: true },
- operatorMotionArgs: { visualLine: true }},
- { keys: ['~'], type: 'operatorMotion',
- operator: 'swapcase', operatorArgs: { shouldMoveCursor: true },
- motion: 'moveByCharacters', motionArgs: { forward: true }},
+ { keys: 'x', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorMotionArgs: { visualLine: false }},
+ { keys: 'X', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: false }, operatorMotionArgs: { visualLine: true }},
+ { keys: 'D', type: 'operatorMotion', operator: 'delete', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
+ { keys: 'D', type: 'operator', operator: 'delete', operatorArgs: { linewise: true }, context: 'visual'},
+ { keys: 'Y', type: 'operatorMotion', operator: 'yank', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
+ { keys: 'Y', type: 'operator', operator: 'yank', operatorArgs: { linewise: true }, context: 'visual'},
+ { keys: 'C', type: 'operatorMotion', operator: 'change', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
+ { keys: 'C', type: 'operator', operator: 'change', operatorArgs: { linewise: true }, context: 'visual'},
+ { keys: '~', type: 'operatorMotion', operator: 'changeCase', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorArgs: { shouldMoveCursor: true }, context: 'normal'},
+ { keys: '~', type: 'operator', operator: 'changeCase', context: 'visual'},
+ { keys: '', type: 'operatorMotion', operator: 'delete', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }, context: 'insert' },
// Actions
- { keys: [''], type: 'action', action: 'jumpListWalk',
- actionArgs: { forward: true }},
- { keys: [''], type: 'action', action: 'jumpListWalk',
- actionArgs: { forward: false }},
- { keys: [''], type: 'action',
- action: 'scroll',
- actionArgs: { forward: true, linewise: true }},
- { keys: [''], type: 'action',
- action: 'scroll',
- actionArgs: { forward: false, linewise: true }},
- { keys: ['a'], type: 'action', action: 'enterInsertMode', isEdit: true,
- actionArgs: { insertAt: 'charAfter' }},
- { keys: ['A'], type: 'action', action: 'enterInsertMode', isEdit: true,
- actionArgs: { insertAt: 'eol' }},
- { keys: ['A'], type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' },
- { keys: ['i'], type: 'action', action: 'enterInsertMode', isEdit: true,
- actionArgs: { insertAt: 'inplace' }},
- { keys: ['I'], type: 'action', action: 'enterInsertMode', isEdit: true,
- actionArgs: { insertAt: 'firstNonBlank' }},
- { keys: ['o'], type: 'action', action: 'newLineAndEnterInsertMode',
- isEdit: true, interlaceInsertRepeat: true,
- actionArgs: { after: true }},
- { keys: ['O'], type: 'action', action: 'newLineAndEnterInsertMode',
- isEdit: true, interlaceInsertRepeat: true,
- actionArgs: { after: false }},
- { keys: ['v'], type: 'action', action: 'toggleVisualMode' },
- { keys: ['V'], type: 'action', action: 'toggleVisualMode',
- actionArgs: { linewise: true }},
- { keys: [''], type: 'action', action: 'toggleVisualMode',
- actionArgs: { blockwise: true }},
- { keys: ['g', 'v'], type: 'action', action: 'reselectLastSelection' },
- { keys: ['J'], type: 'action', action: 'joinLines', isEdit: true },
- { keys: ['p'], type: 'action', action: 'paste', isEdit: true,
- actionArgs: { after: true, isEdit: true }},
- { keys: ['P'], type: 'action', action: 'paste', isEdit: true,
- actionArgs: { after: false, isEdit: true }},
- { keys: ['r', 'character'], type: 'action', action: 'replace', isEdit: true },
- { keys: ['@', 'character'], type: 'action', action: 'replayMacro' },
- { keys: ['q', 'character'], type: 'action', action: 'enterMacroRecordMode' },
+ { keys: '', type: 'action', action: 'jumpListWalk', actionArgs: { forward: true }},
+ { keys: '', type: 'action', action: 'jumpListWalk', actionArgs: { forward: false }},
+ { keys: '', type: 'action', action: 'scroll', actionArgs: { forward: true, linewise: true }},
+ { keys: '', type: 'action', action: 'scroll', actionArgs: { forward: false, linewise: true }},
+ { keys: 'a', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'charAfter' }, context: 'normal' },
+ { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'eol' }, context: 'normal' },
+ { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' },
+ { keys: 'i', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'inplace' }, context: 'normal' },
+ { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'firstNonBlank'}, context: 'normal' },
+ { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'startOfSelectedArea' }, context: 'visual' },
+ { keys: 'o', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: true }, context: 'normal' },
+ { keys: 'O', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: false }, context: 'normal' },
+ { keys: 'v', type: 'action', action: 'toggleVisualMode' },
+ { keys: 'V', type: 'action', action: 'toggleVisualMode', actionArgs: { linewise: true }},
+ { keys: '', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }},
+ { keys: 'gv', type: 'action', action: 'reselectLastSelection' },
+ { keys: 'J', type: 'action', action: 'joinLines', isEdit: true },
+ { keys: 'p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true }},
+ { keys: 'P', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true }},
+ { keys: 'r', type: 'action', action: 'replace', isEdit: true },
+ { keys: '@', type: 'action', action: 'replayMacro' },
+ { keys: 'q', type: 'action', action: 'enterMacroRecordMode' },
// Handle Replace-mode as a special case of insert mode.
- { keys: ['R'], type: 'action', action: 'enterInsertMode', isEdit: true,
- actionArgs: { replace: true }},
- { keys: ['u'], type: 'action', action: 'undo' },
- { keys: ['u'], type: 'action', action: 'changeCase', actionArgs: {toLower: true}, context: 'visual', isEdit: true },
- { keys: ['U'],type: 'action', action: 'changeCase', actionArgs: {toLower: false}, context: 'visual', isEdit: true },
- { keys: [''], type: 'action', action: 'redo' },
- { keys: ['m', 'character'], type: 'action', action: 'setMark' },
- { keys: ['"', 'character'], type: 'action', action: 'setRegister' },
- { keys: ['z', 'z'], type: 'action', action: 'scrollToCursor',
- actionArgs: { position: 'center' }},
- { keys: ['z', '.'], type: 'action', action: 'scrollToCursor',
- actionArgs: { position: 'center' },
- motion: 'moveToFirstNonWhiteSpaceCharacter' },
- { keys: ['z', 't'], type: 'action', action: 'scrollToCursor',
- actionArgs: { position: 'top' }},
- { keys: ['z', ''], type: 'action', action: 'scrollToCursor',
- actionArgs: { position: 'top' },
- motion: 'moveToFirstNonWhiteSpaceCharacter' },
- { keys: ['z', '-'], type: 'action', action: 'scrollToCursor',
- actionArgs: { position: 'bottom' }},
- { keys: ['z', 'b'], type: 'action', action: 'scrollToCursor',
- actionArgs: { position: 'bottom' },
- motion: 'moveToFirstNonWhiteSpaceCharacter' },
- { keys: ['.'], type: 'action', action: 'repeatLastEdit' },
- { keys: [''], type: 'action', action: 'incrementNumberToken',
- isEdit: true,
- actionArgs: {increase: true, backtrack: false}},
- { keys: [''], type: 'action', action: 'incrementNumberToken',
- isEdit: true,
- actionArgs: {increase: false, backtrack: false}},
+ { keys: 'R', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { replace: true }},
+ { keys: 'u', type: 'action', action: 'undo', context: 'normal' },
+ { keys: 'u', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, context: 'visual', isEdit: true },
+ { keys: 'U', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, context: 'visual', isEdit: true },
+ { keys: '', type: 'action', action: 'redo' },
+ { keys: 'm', type: 'action', action: 'setMark' },
+ { keys: '"', type: 'action', action: 'setRegister' },
+ { keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }},
+ { keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
+ { keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }},
+ { keys: 'z', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
+ { keys: 'z-', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }},
+ { keys: 'zb', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
+ { keys: '.', type: 'action', action: 'repeatLastEdit' },
+ { keys: '', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: true, backtrack: false}},
+ { keys: '', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: false, backtrack: false}},
// Text object motions
- { keys: ['a', 'character'], type: 'motion',
- motion: 'textObjectManipulation' },
- { keys: ['i', 'character'], type: 'motion',
- motion: 'textObjectManipulation',
- motionArgs: { textObjectInner: true }},
+ { keys: 'a', type: 'motion', motion: 'textObjectManipulation' },
+ { keys: 'i', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }},
// Search
- { keys: ['/'], type: 'search',
- searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},
- { keys: ['?'], type: 'search',
- searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},
- { keys: ['*'], type: 'search',
- searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
- { keys: ['#'], type: 'search',
- searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
- { keys: ['g', '*'], type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},
- { keys: ['g', '#'], type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},
+ { keys: '/', type: 'search', searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},
+ { keys: '?', type: 'search', searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},
+ { keys: '*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
+ { keys: '#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
+ { keys: 'g*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},
+ { keys: 'g#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},
// Ex command
- { keys: [':'], type: 'ex' }
+ { keys: ':', type: 'ex' }
];
var Pos = CodeMirror.Pos;
+ var modifierCodes = [16, 17, 18, 91];
+ var specialKey = {Enter:'CR',Backspace:'BS',Delete:'Del'};
+ var mac = /Mac/.test(navigator.platform);
var Vim = function() {
- CodeMirror.defineOption('vimMode', false, function(cm, val) {
- if (val) {
- cm.setOption('keyMap', 'vim');
- cm.setOption('disableInput', true);
- cm.setOption('showCursorWhenSelecting', false);
- CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
- cm.on('cursorActivity', onCursorActivity);
- maybeInitVimState(cm);
- CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm));
- } else if (cm.state.vim) {
- cm.setOption('keyMap', 'default');
- cm.setOption('disableInput', false);
- cm.off('cursorActivity', onCursorActivity);
- CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm));
- cm.state.vim = null;
+ function lookupKey(e) {
+ var keyCode = e.keyCode;
+ if (modifierCodes.indexOf(keyCode) != -1) { return; }
+ var hasModifier = e.ctrlKey || e.metaKey;
+ var key = CodeMirror.keyNames[keyCode];
+ key = specialKey[key] || key;
+ var name = '';
+ if (e.ctrlKey) { name += 'C-'; }
+ if (e.altKey) { name += 'A-'; }
+ if (mac && e.metaKey || (!hasModifier && e.shiftKey) && key.length < 2) {
+ // Shift key bindings can only specified for special characters.
+ return;
+ } else if (e.shiftKey && !/^[A-Za-z]$/.test(key)) {
+ name += 'S-';
}
+ if (key.length == 1) { key = key.toLowerCase(); }
+ name += key;
+ if (name.length > 1) { name = '<' + name + '>'; }
+ return name;
+ }
+ // Keys with modifiers are handled using keydown due to limitations of
+ // keypress event.
+ function handleKeyDown(cm, e) {
+ var name = lookupKey(e);
+ if (!name) { return; }
+
+ CodeMirror.signal(cm, 'vim-keypress', name);
+ if (CodeMirror.Vim.handleKey(cm, name, 'user')) {
+ CodeMirror.e_stop(e);
+ }
+ }
+ // Keys without modifiers are handled using keypress to work best with
+ // non-standard keyboard layouts.
+ function handleKeyPress(cm, e) {
+ var code = e.charCode || e.keyCode;
+ if (e.ctrlKey || e.metaKey || e.altKey ||
+ e.shiftKey && code < 32) { return; }
+ var name = String.fromCharCode(code);
+
+ CodeMirror.signal(cm, 'vim-keypress', name);
+ if (CodeMirror.Vim.handleKey(cm, name, 'user')) {
+ CodeMirror.e_stop(e);
+ }
+ }
+
+ function enterVimMode(cm) {
+ cm.setOption('disableInput', true);
+ cm.setOption('showCursorWhenSelecting', false);
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
+ cm.on('cursorActivity', onCursorActivity);
+ maybeInitVimState(cm);
+ CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm));
+ cm.on('keypress', handleKeyPress);
+ cm.on('keydown', handleKeyDown);
+ }
+
+ function leaveVimMode(cm) {
+ cm.setOption('disableInput', false);
+ cm.off('cursorActivity', onCursorActivity);
+ CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm));
+ cm.state.vim = null;
+ cm.off('keypress', handleKeyPress);
+ cm.off('keydown', handleKeyDown);
+ }
+
+ function detachVimMap(cm, next) {
+ if (this == CodeMirror.keyMap.vim)
+ CodeMirror.rmClass(cm.getWrapperElement(), "cm-fat-cursor");
+
+ if (!next || next.attach != attachVimMap)
+ leaveVimMode(cm, false);
+ }
+ function attachVimMap(cm, prev) {
+ if (this == CodeMirror.keyMap.vim)
+ CodeMirror.addClass(cm.getWrapperElement(), "cm-fat-cursor");
+
+ if (!prev || prev.attach != attachVimMap)
+ enterVimMode(cm);
+ }
+
+ // Deprecated, simply setting the keymap works again.
+ CodeMirror.defineOption('vimMode', false, function(cm, val, prev) {
+ if (val && cm.getOption("keyMap") != "vim")
+ cm.setOption("keyMap", "vim");
+ else if (!val && prev != CodeMirror.Init && /^vim/.test(cm.getOption("keyMap")))
+ cm.setOption("keyMap", "default");
});
function getOnPasteFn(cm) {
var vim = cm.state.vim;
@@ -1772,9 +1724,6 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
var upperCaseAlphabet = makeKeyRange(65, 26);
var lowerCaseAlphabet = makeKeyRange(97, 26);
var numbers = makeKeyRange(48, 10);
- var specialSymbols = '~`!@#$%^&*()_-+=[{}]\\|/?.,<>:;"\''.split('');
- var specialKeys = ['Left', 'Right', 'Up', 'Down', 'Space', 'Backspace',
- 'Esc', 'Home', 'End', 'PageUp', 'PageDown', 'Enter'];
var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']);
var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"', '.', ':', '/']);
@@ -1992,8 +1941,8 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
visualBlock: false,
lastSelection: null,
lastPastedText: null,
- // Used by two-character ESC keymap routines. Should not be changed from false here.
- awaitingEscapeSecondCharacter: false
+ sel: {
+ }
};
}
return cm.state.vim;
@@ -2023,6 +1972,7 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
}
}
+ var lastInsertModeKeyTimer;
var vimApi= {
buildKeyMap: function() {
// TODO: Convert keymap into dictionary format for fast lookup.
@@ -2060,58 +2010,121 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
},
// This is the outermost function called by CodeMirror, after keys have
// been mapped to their Vim equivalents.
- handleKey: function(cm, key) {
- var command;
+ handleKey: function(cm, key, origin) {
var vim = maybeInitVimState(cm);
- var macroModeState = vimGlobalState.macroModeState;
- if (macroModeState.isRecording) {
- if (key == 'q') {
- macroModeState.exitMacroRecordMode();
- clearInputState(cm);
- return;
+ function handleMacroRecording() {
+ var macroModeState = vimGlobalState.macroModeState;
+ if (macroModeState.isRecording) {
+ if (key == 'q') {
+ macroModeState.exitMacroRecordMode();
+ clearInputState(cm);
+ return true;
+ }
+ if (origin != 'mapping') {
+ logKey(macroModeState, key);
+ }
}
}
- if (key == '') {
- // Clear input state and get back to normal mode.
- clearInputState(cm);
- if (vim.visualMode) {
- exitVisualMode(cm);
+ function handleEsc() {
+ if (key == '') {
+ // Clear input state and get back to normal mode.
+ clearInputState(cm);
+ if (vim.visualMode) {
+ exitVisualMode(cm);
+ } else if (vim.insertMode) {
+ exitInsertMode(cm);
+ }
+ return true;
}
- return;
}
- // Enter visual mode when the mouse selects text.
- if (!vim.visualMode &&
- !cursorEqual(cm.getCursor('head'), cm.getCursor('anchor'))) {
- vim.visualMode = true;
- vim.visualLine = false;
- CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
- cm.on('mousedown', exitVisualMode);
- }
- if (key != '0' || (key == '0' && vim.inputState.getRepeat() === 0)) {
- // Have to special case 0 since it's both a motion and a number.
- command = commandDispatcher.matchCommand(key, defaultKeymap, vim);
- }
- if (!command) {
- if (isNumber(key)) {
- // Increment count unless count is 0 and key is 0.
- vim.inputState.pushRepeatDigit(key);
+ function doKeyToKey(keys) {
+ // TODO: prevent infinite recursion.
+ var match;
+ while (keys) {
+ // Pull off one command key, which is either a single character
+ // or a special sequence wrapped in '<' and '>', e.g. ''.
+ match = (/<\w+-.+?>|<\w+>|./).exec(keys);
+ key = match[0];
+ keys = keys.substring(match.index + key.length);
+ CodeMirror.Vim.handleKey(cm, key, 'mapping');
+ }
+ }
+
+ function handleKeyInsertMode() {
+ if (handleEsc()) { return true; }
+ var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
+ var keysAreChars = key.length == 1;
+ var match = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
+ // Need to check all key substrings in insert mode.
+ while (keys.length > 1 && match.type != 'full') {
+ var keys = vim.inputState.keyBuffer = keys.slice(1);
+ var thisMatch = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
+ if (thisMatch.type != 'none') { match = thisMatch; }
+ }
+ if (match.type == 'none') { clearInputState(cm); return false; }
+ else if (match.type == 'partial') {
+ if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
+ lastInsertModeKeyTimer = window.setTimeout(
+ function() { if (vim.insertMode && vim.inputState.keyBuffer) { clearInputState(cm); } },
+ getOption('insertModeEscKeysTimeout'));
+ return !keysAreChars;
}
- if (macroModeState.isRecording) {
- logKey(macroModeState, key);
+
+ if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
+ if (keysAreChars) {
+ var here = cm.getCursor();
+ cm.replaceRange('', offsetCursor(here, 0, -(keys.length - 1)), here, '+input');
}
- return;
+ clearInputState(cm);
+ var command = match.command;
+ if (command.type == 'keyToKey') {
+ doKeyToKey(command.toKeys);
+ } else {
+ commandDispatcher.processCommand(cm, vim, command);
+ }
+ return true;
}
- if (command.type == 'keyToKey') {
- // TODO: prevent infinite recursion.
- for (var i = 0; i < command.toKeys.length; i++) {
- this.handleKey(cm, command.toKeys[i]);
+
+ function handleKeyNonInsertMode() {
+ if (handleMacroRecording() || handleEsc()) { return true; };
+
+ var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
+ if (/^[1-9]\d*$/.test(keys)) { return true; }
+
+ var keysMatcher = /^(\d*)(.*)$/.exec(keys);
+ if (!keysMatcher) { clearInputState(cm); return false; }
+ var context = vim.visualMode ? 'visual' :
+ 'normal';
+ var match = commandDispatcher.matchCommand(keysMatcher[2] || keysMatcher[1], defaultKeymap, vim.inputState, context);
+ if (match.type == 'none') { clearInputState(cm); return false; }
+ else if (match.type == 'partial') { return true; }
+
+ vim.inputState.keyBuffer = '';
+ var command = match.command;
+ var keysMatcher = /^(\d*)(.*)$/.exec(keys);
+ if (keysMatcher[1] && keysMatcher[1] != '0') {
+ vim.inputState.pushRepeatDigit(keysMatcher[1]);
}
- } else {
- if (macroModeState.isRecording) {
- logKey(macroModeState, key);
+ if (command.type == 'keyToKey') {
+ doKeyToKey(command.toKeys);
+ } else {
+ commandDispatcher.processCommand(cm, vim, command);
}
- commandDispatcher.processCommand(cm, vim, command);
+ return true;
}
+
+ return cm.operation(function() {
+ cm.curOp.isVimOp = true;
+ try {
+ if (vim.insertMode) { return handleKeyInsertMode(); }
+ else { return handleKeyNonInsertMode(); }
+ } catch (e) {
+ // clear VIM state in case it's in a bad state.
+ cm.state.vim = undefined;
+ maybeInitVimState(cm);
+ throw e;
+ }
+ });
},
handleEx: function(cm, input) {
exCommandDispatcher.processCommand(cm, input);
@@ -2328,83 +2341,25 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
}
};
var commandDispatcher = {
- matchCommand: function(key, keyMap, vim) {
- var inputState = vim.inputState;
- var keys = inputState.keyBuffer.concat(key);
- var matchedCommands = [];
- var selectedCharacter;
- for (var i = 0; i < keyMap.length; i++) {
- var command = keyMap[i];
- if (matchKeysPartial(keys, command.keys)) {
- if (inputState.operator && command.type == 'action') {
- // Ignore matched action commands after an operator. Operators
- // only operate on motions. This check is really for text
- // objects since aW, a[ etcs conflicts with a.
- continue;
- }
- // Match commands that take as an argument.
- if (command.keys[keys.length - 1] == 'character') {
- selectedCharacter = keys[keys.length - 1];
- if (selectedCharacter.length>1){
- switch(selectedCharacter){
- case '':
- selectedCharacter='\n';
- break;
- case '':
- selectedCharacter=' ';
- break;
- default:
- continue;
- }
- }
- }
- // Add the command to the list of matched commands. Choose the best
- // command later.
- matchedCommands.push(command);
- }
+ matchCommand: function(keys, keyMap, inputState, context) {
+ var matches = commandMatches(keys, keyMap, context, inputState);
+ if (!matches.full && !matches.partial) {
+ return {type: 'none'};
+ } else if (!matches.full && matches.partial) {
+ return {type: 'partial'};
}
- // Returns the command if it is a full match, or null if not.
- function getFullyMatchedCommandOrNull(command) {
- if (keys.length < command.keys.length) {
- // Matches part of a multi-key command. Buffer and wait for next
- // stroke.
- inputState.keyBuffer.push(key);
- return null;
- } else {
- if (command.keys[keys.length - 1] == 'character') {
- inputState.selectedCharacter = selectedCharacter;
- }
- // Clear the buffer since a full match was found.
- inputState.keyBuffer = [];
- return command;
+ var bestMatch;
+ for (var i = 0; i < matches.full.length; i++) {
+ var match = matches.full[i];
+ if (!bestMatch) {
+ bestMatch = match;
}
}
-
- if (!matchedCommands.length) {
- // Clear the buffer since there were no matches.
- inputState.keyBuffer = [];
- return null;
- } else if (matchedCommands.length == 1) {
- return getFullyMatchedCommandOrNull(matchedCommands[0]);
- } else {
- // Find the best match in the list of matchedCommands.
- var context = vim.visualMode ? 'visual' : 'normal';
- var bestMatch; // Default to first in the list.
- for (var i = 0; i < matchedCommands.length; i++) {
- var current = matchedCommands[i];
- if (current.context == context) {
- bestMatch = current;
- break;
- } else if (!bestMatch && !current.context) {
- // Only set an imperfect match to best match if no best match is
- // set and the imperfect match is not restricted to another
- // context.
- bestMatch = current;
- }
- }
- return getFullyMatchedCommandOrNull(bestMatch);
+ if (bestMatch.keys.slice(-11) == '') {
+ inputState.selectedCharacter = lastChar(keys);
}
+ return {type: 'full', command: bestMatch};
},
processCommand: function(cm, vim, command) {
vim.inputState.repeatOverride = command.repeatOverride;
@@ -2423,10 +2378,12 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
break;
case 'search':
this.processSearch(cm, vim, command);
+ clearInputState(cm);
break;
case 'ex':
case 'keyToEx':
this.processEx(cm, vim, command);
+ clearInputState(cm);
break;
default:
break;
@@ -2668,13 +2625,13 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
var operator = inputState.operator;
var operatorArgs = inputState.operatorArgs || {};
var registerName = inputState.registerName;
- var selectionEnd = copyCursor(cm.getCursor('head'));
- var selectionStart = copyCursor(cm.getCursor('anchor'));
- // The difference between cur and selection cursors are that cur is
- // being operated on and ignores that there is a selection.
- var curStart = copyCursor(selectionEnd);
- var curOriginal = copyCursor(curStart);
- var curEnd;
+ var sel = vim.sel;
+ // TODO: Make sure cm and vim selections are identical outside visual mode.
+ var origHead = copyCursor(vim.visualMode ? sel.head: cm.getCursor('head'));
+ var origAnchor = copyCursor(vim.visualMode ? sel.anchor : cm.getCursor('anchor'));
+ var oldHead = copyCursor(origHead);
+ var oldAnchor = copyCursor(origAnchor);
+ var newHead, newAnchor;
var repeat;
if (operator) {
this.recordLastEdit(vim, inputState);
@@ -2701,7 +2658,7 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
motionArgs.repeat = repeat;
clearInputState(cm);
if (motion) {
- var motionResult = motions[motion](cm, motionArgs, vim);
+ var motionResult = motions[motion](cm, origHead, motionArgs, vim);
vim.lastMotion = motions[motion];
if (!motionResult) {
return;
@@ -2714,159 +2671,139 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
recordJumpPosition(cm, cachedCursor, motionResult);
delete jumpList.cachedCursor;
} else {
- recordJumpPosition(cm, curOriginal, motionResult);
+ recordJumpPosition(cm, origHead, motionResult);
}
}
if (motionResult instanceof Array) {
- curStart = motionResult[0];
- curEnd = motionResult[1];
+ newAnchor = motionResult[0];
+ newHead = motionResult[1];
} else {
- curEnd = motionResult;
+ newHead = motionResult;
}
// TODO: Handle null returns from motion commands better.
- if (!curEnd) {
- curEnd = Pos(curStart.line, curStart.ch);
+ if (!newHead) {
+ newHead = copyCursor(origHead);
}
if (vim.visualMode) {
- // Check if the selection crossed over itself. Will need to shift
- // the start point if that happened.
- // offset is set to -1 or 1 to shift the curEnd
- // left or right
- var offset = 0;
- if (cursorIsBefore(selectionStart, selectionEnd) &&
- (cursorEqual(selectionStart, curEnd) ||
- cursorIsBefore(curEnd, selectionStart))) {
- // The end of the selection has moved from after the start to
- // before the start. We will shift the start right by 1.
- selectionStart.ch += 1;
- offset = -1;
- } else if (cursorIsBefore(selectionEnd, selectionStart) &&
- (cursorEqual(selectionStart, curEnd) ||
- cursorIsBefore(selectionStart, curEnd))) {
- // The opposite happened. We will shift the start left by 1.
- selectionStart.ch -= 1;
- offset = 1;
- }
- // in case of visual Block selectionStart and curEnd
- // may not be on the same line,
- // Also, In case of v_o this should not happen.
- if (!vim.visualBlock && !(motionResult instanceof Array)) {
- curEnd.ch += offset;
- }
- if (vim.lastHPos != Infinity) {
- vim.lastHPos = curEnd.ch;
- }
- selectionEnd = curEnd;
- selectionStart = (motionResult instanceof Array) ? curStart : selectionStart;
- if (vim.visualLine) {
- if (cursorIsBefore(selectionStart, selectionEnd)) {
- selectionStart.ch = 0;
-
- var lastLine = cm.lastLine();
- if (selectionEnd.line > lastLine) {
- selectionEnd.line = lastLine;
- }
- selectionEnd.ch = lineLength(cm, selectionEnd.line);
- } else {
- selectionEnd.ch = 0;
- selectionStart.ch = lineLength(cm, selectionStart.line);
- }
- } else if (vim.visualBlock) {
- // Select a block and
- // return the diagonally opposite end.
- selectionStart = selectBlock(cm, selectionEnd);
- }
- if (!vim.visualBlock) {
- cm.setSelection(selectionStart, selectionEnd);
+ newHead = clipCursorToContent(cm, newHead, vim.visualBlock);
+ if (newAnchor) {
+ newAnchor = clipCursorToContent(cm, newAnchor, true);
}
+ newAnchor = newAnchor || oldAnchor;
+ sel.anchor = newAnchor;
+ sel.head = newHead;
+ updateCmSelection(cm);
updateMark(cm, vim, '<',
- cursorIsBefore(selectionStart, selectionEnd) ? selectionStart
- : selectionEnd);
+ cursorIsBefore(newAnchor, newHead) ? newAnchor
+ : newHead);
updateMark(cm, vim, '>',
- cursorIsBefore(selectionStart, selectionEnd) ? selectionEnd
- : selectionStart);
+ cursorIsBefore(newAnchor, newHead) ? newHead
+ : newAnchor);
} else if (!operator) {
- curEnd = clipCursorToContent(cm, curEnd);
- cm.setCursor(curEnd.line, curEnd.ch);
+ newHead = clipCursorToContent(cm, newHead);
+ cm.setCursor(newHead.line, newHead.ch);
}
}
-
if (operator) {
- var inverted = false;
- vim.lastMotion = null;
- var lastSelection = vim.lastSelection;
- operatorArgs.repeat = repeat; // Indent in visual mode needs this.
- if (vim.visualMode) {
- curStart = selectionStart;
- curEnd = selectionEnd;
- motionArgs.inclusive = true;
- operatorArgs.shouldMoveCursor = false;
- }
- // Swap start and end if motion was backward.
- if (curEnd && cursorIsBefore(curEnd, curStart)) {
- var tmp = curStart;
- curStart = curEnd;
- curEnd = tmp;
- inverted = true;
- } else if (!curEnd) {
- curEnd = copyCursor(curStart);
- }
- if (motionArgs.inclusive && !vim.visualMode) {
- // Move the selection end one to the right to include the last
- // character.
- curEnd.ch++;
- }
- if (operatorArgs.selOffset) {
+ if (operatorArgs.lastSel) {
// Replaying a visual mode operation
- curEnd.line = curStart.line + operatorArgs.selOffset.line;
- if (operatorArgs.selOffset.line) {curEnd.ch = operatorArgs.selOffset.ch; }
- else { curEnd.ch = curStart.ch + operatorArgs.selOffset.ch; }
- // In case of blockwise visual
- if (lastSelection && lastSelection.visualBlock) {
- var block = lastSelection.visualBlock;
- var width = block.width;
- var height = block.height;
- curEnd = Pos(curStart.line + height, curStart.ch + width);
- // selectBlock creates a 'proper' rectangular block.
- // We do not want that in all cases, so we manually set selections.
- var selections = [];
- for (var i = curStart.line; i < curEnd.line; i++) {
- var anchor = Pos(i, curStart.ch);
- var head = Pos(i, curEnd.ch);
- var range = {anchor: anchor, head: head};
- selections.push(range);
- }
- cm.setSelections(selections);
- var blockSelected = true;
+ newAnchor = oldAnchor;
+ var lastSel = operatorArgs.lastSel;
+ var lineOffset = Math.abs(lastSel.head.line - lastSel.anchor.line);
+ var chOffset = Math.abs(lastSel.head.ch - lastSel.anchor.ch);
+ if (lastSel.visualLine) {
+ // Linewise Visual mode: The same number of lines.
+ newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
+ } else if (lastSel.visualBlock) {
+ // Blockwise Visual mode: The same number of lines and columns.
+ newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch + chOffset);
+ } else if (lastSel.head.line == lastSel.anchor.line) {
+ // Normal Visual mode within one line: The same number of characters.
+ newHead = Pos(oldAnchor.line, oldAnchor.ch + chOffset);
+ } else {
+ // Normal Visual mode with several lines: The same number of lines, in the
+ // last line the same number of characters as in the last line the last time.
+ newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
}
+ vim.visualMode = true;
+ vim.visualLine = lastSel.visualLine;
+ vim.visualBlock = lastSel.visualBlock;
+ sel = vim.sel = {
+ anchor: newAnchor,
+ head: newHead
+ };
+ updateCmSelection(cm);
} else if (vim.visualMode) {
- var selOffset = Pos();
- selOffset.line = curEnd.line - curStart.line;
- if (selOffset.line) { selOffset.ch = curEnd.ch; }
- else { selOffset.ch = curEnd.ch - curStart.ch; }
- operatorArgs.selOffset = selOffset;
- }
- var linewise = motionArgs.linewise ||
- (vim.visualMode && vim.visualLine) ||
- operatorArgs.linewise;
- if (linewise) {
- // Expand selection to entire line.
- expandSelectionToLine(cm, curStart, curEnd);
- } else if (motionArgs.forward) {
- // Clip to trailing newlines only if the motion goes forward.
- clipToLine(cm, curStart, curEnd);
+ operatorArgs.lastSel = {
+ anchor: copyCursor(sel.anchor),
+ head: copyCursor(sel.head),
+ visualBlock: vim.visualBlock,
+ visualLine: vim.visualLine
+ };
}
+ var curStart, curEnd, linewise, mode;
+ var cmSel;
+ if (vim.visualMode) {
+ // Init visual op
+ curStart = cursorMin(sel.head, sel.anchor);
+ curEnd = cursorMax(sel.head, sel.anchor);
+ linewise = vim.visualLine || operatorArgs.linewise;
+ mode = vim.visualBlock ? 'block' :
+ linewise ? 'line' :
+ 'char';
+ cmSel = makeCmSelection(cm, {
+ anchor: curStart,
+ head: curEnd
+ }, mode);
+ if (linewise) {
+ var ranges = cmSel.ranges;
+ if (mode == 'block') {
+ // Linewise operators in visual block mode extend to end of line
+ for (var i = 0; i < ranges.length; i++) {
+ ranges[i].head.ch = lineLength(cm, ranges[i].head.line);
+ }
+ } else if (mode == 'line') {
+ ranges[0].head = Pos(ranges[0].head.line + 1, 0);
+ }
+ }
+ } else {
+ // Init motion op
+ curStart = copyCursor(newAnchor || oldAnchor);
+ curEnd = copyCursor(newHead || oldHead);
+ if (cursorIsBefore(curEnd, curStart)) {
+ var tmp = curStart;
+ curStart = curEnd;
+ curEnd = tmp;
+ }
+ linewise = motionArgs.linewise || operatorArgs.linewise;
+ if (linewise) {
+ // Expand selection to entire line.
+ expandSelectionToLine(cm, curStart, curEnd);
+ } else if (motionArgs.forward) {
+ // Clip to trailing newlines only if the motion goes forward.
+ clipToLine(cm, curStart, curEnd);
+ }
+ mode = 'char';
+ var exclusive = !motionArgs.inclusive || linewise;
+ cmSel = makeCmSelection(cm, {
+ anchor: curStart,
+ head: curEnd
+ }, mode, exclusive);
+ }
+ cm.setSelections(cmSel.ranges, cmSel.primary);
+ vim.lastMotion = null;
+ operatorArgs.repeat = repeat; // For indent in visual mode.
operatorArgs.registerName = registerName;
// Keep track of linewise as it affects how paste and change behave.
operatorArgs.linewise = linewise;
- if (!vim.visualBlock && !blockSelected) {
- cm.setSelection(curStart, curEnd);
- }
- operators[operator](cm, operatorArgs, vim, curStart,
- curEnd, curOriginal);
+ var operatorMoveTo = operators[operator](
+ cm, operatorArgs, cmSel.ranges, oldAnchor, newHead);
if (vim.visualMode) {
exitVisualMode(cm);
}
+ if (operatorMoveTo) {
+ cm.setCursor(operatorMoveTo);
+ }
}
},
recordLastEdit: function(vim, inputState, actionCommand) {
@@ -2885,7 +2822,7 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
*/
// All of the functions below return Cursor objects.
var motions = {
- moveToTopLine: function(cm, motionArgs) {
+ moveToTopLine: function(cm, _head, motionArgs) {
var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;
return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
},
@@ -2894,17 +2831,17 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
var line = Math.floor((range.top + range.bottom) * 0.5);
return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
},
- moveToBottomLine: function(cm, motionArgs) {
+ moveToBottomLine: function(cm, _head, motionArgs) {
var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;
return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
},
- expandToLine: function(cm, motionArgs) {
+ expandToLine: function(_cm, head, motionArgs) {
// Expands forward to end of line, and then to next line if repeat is
// >1. Does not handle backward motion!
- var cur = cm.getCursor();
+ var cur = head;
return Pos(cur.line + motionArgs.repeat - 1, Infinity);
},
- findNext: function(cm, motionArgs) {
+ findNext: function(cm, _head, motionArgs) {
var state = getSearchState(cm);
var query = state.getQuery();
if (!query) {
@@ -2916,7 +2853,7 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
highlightSearchMatches(cm, query);
return findNext(cm, prev/** prev */, query, motionArgs.repeat);
},
- goToMark: function(cm, motionArgs, vim) {
+ goToMark: function(cm, _head, motionArgs, vim) {
var mark = vim.marks[motionArgs.selectedCharacter];
if (mark) {
var pos = mark.find();
@@ -2924,22 +2861,19 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
}
return null;
},
- moveToOtherHighlightedEnd: function(cm, motionArgs, vim) {
- var ranges = cm.listSelections();
- var curEnd = cm.getCursor('head');
- var curStart = ranges[0].anchor;
- var curIndex = cursorEqual(ranges[0].head, curEnd) ? ranges.length-1 : 0;
- if (motionArgs.sameLine && vim.visualBlock) {
- curStart = Pos(curEnd.line, ranges[curIndex].anchor.ch);
- curEnd = Pos(ranges[curIndex].head.line, curEnd.ch);
+ moveToOtherHighlightedEnd: function(cm, _head, motionArgs, vim) {
+ if (vim.visualBlock && motionArgs.sameLine) {
+ var sel = vim.sel;
+ return [
+ clipCursorToContent(cm, Pos(sel.anchor.line, sel.head.ch)),
+ clipCursorToContent(cm, Pos(sel.head.line, sel.anchor.ch))
+ ];
} else {
- curStart = ranges[curIndex].anchor;
+ return ([vim.sel.head, vim.sel.anchor]);
}
- cm.setCursor(curEnd);
- return ([curEnd, curStart]);
},
- jumpToMark: function(cm, motionArgs, vim) {
- var best = cm.getCursor();
+ jumpToMark: function(cm, head, motionArgs, vim) {
+ var best = head;
for (var i = 0; i < motionArgs.repeat; i++) {
var cursor = best;
for (var key in vim.marks) {
@@ -2959,8 +2893,8 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
var equal = cursorEqual(cursor, best);
var between = (motionArgs.forward) ?
- cusrorIsBetween(cursor, mark, best) :
- cusrorIsBetween(best, mark, cursor);
+ cursorIsBetween(cursor, mark, best) :
+ cursorIsBetween(best, mark, cursor);
if (equal || between) {
best = mark;
@@ -2976,14 +2910,14 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
}
return best;
},
- moveByCharacters: function(cm, motionArgs) {
- var cur = cm.getCursor();
+ moveByCharacters: function(_cm, head, motionArgs) {
+ var cur = head;
var repeat = motionArgs.repeat;
var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;
return Pos(cur.line, ch);
},
- moveByLines: function(cm, motionArgs, vim) {
- var cur = cm.getCursor();
+ moveByLines: function(cm, head, motionArgs, vim) {
+ var cur = head;
var endCh = cur.ch;
// Depending what our last motion was, we may want to do different
// things. If our last motion was moving vertically, we want to
@@ -3018,8 +2952,8 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
vim.lastHSPos = cm.charCoords(Pos(line, endCh),'div').left;
return Pos(line, endCh);
},
- moveByDisplayLines: function(cm, motionArgs, vim) {
- var cur = cm.getCursor();
+ moveByDisplayLines: function(cm, head, motionArgs, vim) {
+ var cur = head;
switch (vim.lastMotion) {
case this.moveByDisplayLines:
case this.moveByScroll:
@@ -3046,16 +2980,16 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
vim.lastHPos = res.ch;
return res;
},
- moveByPage: function(cm, motionArgs) {
+ moveByPage: function(cm, head, motionArgs) {
// CodeMirror only exposes functions that move the cursor page down, so
// doing this bad hack to move the cursor and move it back. evalInput
// will move the cursor to where it should be in the end.
- var curStart = cm.getCursor();
+ var curStart = head;
var repeat = motionArgs.repeat;
return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page');
},
- moveByParagraph: function(cm, motionArgs) {
- var line = cm.getCursor().line;
+ moveByParagraph: function(cm, head, motionArgs) {
+ var line = head.line;
var repeat = motionArgs.repeat;
var inc = motionArgs.forward ? 1 : -1;
for (var i = 0; i < repeat; i++) {
@@ -3070,16 +3004,16 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
}
return Pos(line, 0);
},
- moveByScroll: function(cm, motionArgs, vim) {
+ moveByScroll: function(cm, head, motionArgs, vim) {
var scrollbox = cm.getScrollInfo();
var curEnd = null;
var repeat = motionArgs.repeat;
if (!repeat) {
repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
}
- var orig = cm.charCoords(cm.getCursor(), 'local');
+ var orig = cm.charCoords(head, 'local');
motionArgs.repeat = repeat;
- var curEnd = motions.moveByDisplayLines(cm, motionArgs, vim);
+ var curEnd = motions.moveByDisplayLines(cm, head, motionArgs, vim);
if (!curEnd) {
return null;
}
@@ -3087,11 +3021,11 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
return curEnd;
},
- moveByWords: function(cm, motionArgs) {
- return moveToWord(cm, motionArgs.repeat, !!motionArgs.forward,
+ moveByWords: function(cm, head, motionArgs) {
+ return moveToWord(cm, head, motionArgs.repeat, !!motionArgs.forward,
!!motionArgs.wordEnd, !!motionArgs.bigWord);
},
- moveTillCharacter: function(cm, motionArgs) {
+ moveTillCharacter: function(cm, _head, motionArgs) {
var repeat = motionArgs.repeat;
var curEnd = moveToCharacter(cm, repeat, motionArgs.forward,
motionArgs.selectedCharacter);
@@ -3101,26 +3035,26 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
curEnd.ch += increment;
return curEnd;
},
- moveToCharacter: function(cm, motionArgs) {
+ moveToCharacter: function(cm, head, motionArgs) {
var repeat = motionArgs.repeat;
recordLastCharacterSearch(0, motionArgs);
return moveToCharacter(cm, repeat, motionArgs.forward,
- motionArgs.selectedCharacter) || cm.getCursor();
+ motionArgs.selectedCharacter) || head;
},
- moveToSymbol: function(cm, motionArgs) {
+ moveToSymbol: function(cm, head, motionArgs) {
var repeat = motionArgs.repeat;
return findSymbol(cm, repeat, motionArgs.forward,
- motionArgs.selectedCharacter) || cm.getCursor();
+ motionArgs.selectedCharacter) || head;
},
- moveToColumn: function(cm, motionArgs, vim) {
+ moveToColumn: function(cm, head, motionArgs, vim) {
var repeat = motionArgs.repeat;
// repeat is equivalent to which column we want to move to!
vim.lastHPos = repeat - 1;
- vim.lastHSPos = cm.charCoords(cm.getCursor(),'div').left;
+ vim.lastHSPos = cm.charCoords(head,'div').left;
return moveToColumn(cm, repeat);
},
- moveToEol: function(cm, motionArgs, vim) {
- var cur = cm.getCursor();
+ moveToEol: function(cm, head, motionArgs, vim) {
+ var cur = head;
vim.lastHPos = Infinity;
var retval= Pos(cur.line + motionArgs.repeat - 1, Infinity);
var end=cm.clipPos(retval);
@@ -3128,15 +3062,15 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
vim.lastHSPos = cm.charCoords(end,'div').left;
return retval;
},
- moveToFirstNonWhiteSpaceCharacter: function(cm) {
+ moveToFirstNonWhiteSpaceCharacter: function(cm, head) {
// Go to the start of the line where the text begins, or the end for
// whitespace-only lines
- var cursor = cm.getCursor();
+ var cursor = head;
return Pos(cursor.line,
findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)));
},
- moveToMatchedSymbol: function(cm) {
- var cursor = cm.getCursor();
+ moveToMatchedSymbol: function(cm, head) {
+ var cursor = head;
var line = cursor.line;
var ch = cursor.ch;
var lineText = cm.getLine(line);
@@ -3157,11 +3091,10 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
return cursor;
}
},
- moveToStartOfLine: function(cm) {
- var cursor = cm.getCursor();
- return Pos(cursor.line, 0);
+ moveToStartOfLine: function(_cm, head) {
+ return Pos(head.line, 0);
},
- moveToLineOrEdgeOfDocument: function(cm, motionArgs) {
+ moveToLineOrEdgeOfDocument: function(cm, _head, motionArgs) {
var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine();
if (motionArgs.repeatIsExplicit) {
lineNum = motionArgs.repeat - cm.getOption('firstLineNumber');
@@ -3169,7 +3102,7 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
return Pos(lineNum,
findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)));
},
- textObjectManipulation: function(cm, motionArgs) {
+ textObjectManipulation: function(cm, head, motionArgs) {
// TODO: lots of possible exceptions that can be thrown here. Try da(
// outside of a () block.
@@ -3198,9 +3131,9 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
var tmp;
if (mirroredPairs[character]) {
- tmp = selectCompanionObject(cm, character, inclusive);
+ tmp = selectCompanionObject(cm, head, character, inclusive);
} else if (selfPaired[character]) {
- tmp = findBeginningAndEnd(cm, character, inclusive);
+ tmp = findBeginningAndEnd(cm, head, character, inclusive);
} else if (character === 'W') {
tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
true /** bigWord */);
@@ -3212,10 +3145,14 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
return null;
}
- return [tmp.start, tmp.end];
+ if (!cm.state.vim.visualMode) {
+ return [tmp.start, tmp.end];
+ } else {
+ return expandSelection(cm, tmp.start, tmp.end);
+ }
},
- repeatLastCharacterSearch: function(cm, motionArgs) {
+ repeatLastCharacterSearch: function(cm, head, motionArgs) {
var lastSearch = vimGlobalState.lastChararacterSearch;
var repeat = motionArgs.repeat;
var forward = motionArgs.forward === lastSearch.forward;
@@ -3225,133 +3162,107 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);
if (!curEnd) {
cm.moveH(increment, 'char');
- return cm.getCursor();
+ return head;
}
curEnd.ch += increment;
return curEnd;
}
};
+ function fillArray(val, times) {
+ var arr = [];
+ for (var i = 0; i < times; i++) {
+ arr.push(val);
+ }
+ return arr;
+ }
+ /**
+ * An operator acts on a text selection. It receives the list of selections
+ * as input. The corresponding CodeMirror selection is guaranteed to
+ * match the input selection.
+ */
var operators = {
- change: function(cm, operatorArgs, vim) {
- var selections = cm.listSelections();
- var start = selections[0], end = selections[selections.length-1];
- var curStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head;
- var curEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor;
- var text = cm.getSelection();
- var visualBlock = vim.visualBlock;
- if (vim.lastSelection && !vim.visualMode) {
- visualBlock = vim.lastSelection.visualBlock ? true : visualBlock;
- }
- var lastInsertModeChanges = vimGlobalState.macroModeState.lastInsertModeChanges;
- lastInsertModeChanges.inVisualBlock = visualBlock;
- var replacement = new Array(selections.length).join('1').split('1');
- // save the selectionEnd mark
- var selectionEnd = vim.marks['>'] ? vim.marks['>'].find() : cm.getCursor('head');
- vimGlobalState.registerController.pushText(
- operatorArgs.registerName, 'change', text,
- operatorArgs.linewise);
- if (operatorArgs.linewise) {
- // 'C' in visual block extends the block till eol for all lines
- if (visualBlock){
- var startLine = curStart.line;
- while (startLine <= curEnd.line) {
- var endCh = lineLength(cm, startLine);
- var head = Pos(startLine, endCh);
- var anchor = Pos(startLine, curStart.ch);
- startLine++;
- cm.replaceRange('', anchor, head);
- }
- } else {
- // Push the next line back down, if there is a next line.
- replacement = '\n';
- if (curEnd.line == curStart.line && curEnd.line == cm.lastLine()) {
- replacement = '';
- }
- cm.replaceRange(replacement, curStart, curEnd);
- cm.indentLine(curStart.line, 'smart');
- // null ch so setCursor moves to end of line.
- curStart.ch = null;
- cm.setCursor(curStart);
- }
- } else {
- // Exclude trailing whitespace if the range is not all whitespace.
- var text = cm.getRange(curStart, curEnd);
+ change: function(cm, args, ranges) {
+ var finalHead, text;
+ var vim = cm.state.vim;
+ vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock = vim.visualBlock;
+ if (!vim.visualMode) {
+ var anchor = ranges[0].anchor,
+ head = ranges[0].head;
+ text = cm.getRange(anchor, head);
if (!isWhiteSpaceString(text)) {
+ // Exclude trailing whitespace if the range is not all whitespace.
var match = (/\s+$/).exec(text);
if (match) {
- curEnd = offsetCursor(curEnd, 0, - match[0].length);
+ head = offsetCursor(head, 0, - match[0].length);
+ text = text.slice(0, - match[0].length);
}
}
- if (visualBlock) {
- cm.replaceSelections(replacement);
- } else {
- cm.setCursor(curStart);
- cm.replaceRange('', curStart, curEnd);
+ var wasLastLine = head.line - 1 == cm.lastLine();
+ cm.replaceRange('', anchor, head);
+ if (args.linewise && !wasLastLine) {
+ // Push the next line back down, if there is a next line.
+ CodeMirror.commands.newlineAndIndent(cm);
+ // null ch so setCursor moves to end of line.
+ anchor.ch = null;
}
- }
- vim.marks['>'] = cm.setBookmark(selectionEnd);
- actions.enterInsertMode(cm, {}, cm.state.vim);
- },
- // delete is a javascript keyword.
- 'delete': function(cm, operatorArgs, vim) {
- var selections = cm.listSelections();
- var start = selections[0], end = selections[selections.length-1];
- var curStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head;
- var curEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor;
- // Save the '>' mark before cm.replaceRange clears it.
- var selectionEnd, selectionStart;
- var blockwise = vim.visualBlock;
- if (vim.visualMode) {
- selectionEnd = vim.marks['>'].find();
- selectionStart = vim.marks['<'].find();
- } else if (vim.lastSelection) {
- selectionEnd = vim.lastSelection.curStartMark.find();
- selectionStart = vim.lastSelection.curEndMark.find();
- blockwise = vim.lastSelection.visualBlock;
- }
- var text = cm.getSelection();
- vimGlobalState.registerController.pushText(
- operatorArgs.registerName, 'delete', text,
- operatorArgs.linewise, blockwise);
- var replacement = new Array(selections.length).join('1').split('1');
- // If the ending line is past the last line, inclusive, instead of
- // including the trailing \n, include the \n before the starting line
- if (operatorArgs.linewise &&
- curEnd.line == cm.lastLine() && curStart.line == curEnd.line) {
- var tmp = copyCursor(curEnd);
- curStart.line--;
- curStart.ch = lineLength(cm, curStart.line);
- curEnd = tmp;
- cm.replaceRange('', curStart, curEnd);
+ finalHead = anchor;
} else {
+ text = cm.getSelection();
+ var replacement = fillArray('', ranges.length);
cm.replaceSelections(replacement);
+ finalHead = cursorMin(ranges[0].head, ranges[0].anchor);
}
- // restore the saved bookmark
- if (selectionEnd) {
- var curStartMark = cm.setBookmark(selectionStart);
- var curEndMark = cm.setBookmark(selectionEnd);
- if (vim.visualMode) {
- vim.marks['<'] = curStartMark;
- vim.marks['>'] = curEndMark;
- } else {
- vim.lastSelection.curStartMark = curStartMark;
- vim.lastSelection.curEndMark = curEndMark;
+ vimGlobalState.registerController.pushText(
+ args.registerName, 'change', text,
+ args.linewise, ranges.length > 1);
+ actions.enterInsertMode(cm, {head: finalHead}, cm.state.vim);
+ },
+ // delete is a javascript keyword.
+ 'delete': function(cm, args, ranges) {
+ var finalHead, text;
+ var vim = cm.state.vim;
+ if (!vim.visualBlock) {
+ var anchor = ranges[0].anchor,
+ head = ranges[0].head;
+ if (args.linewise &&
+ head.line != cm.firstLine() &&
+ anchor.line == cm.lastLine() &&
+ anchor.line == head.line - 1) {
+ // Special case for dd on last line (and first line).
+ if (anchor.line == cm.firstLine()) {
+ anchor.ch = 0;
+ } else {
+ anchor = Pos(anchor.line - 1, lineLength(cm, anchor.line - 1));
+ }
+ }
+ text = cm.getRange(anchor, head);
+ cm.replaceRange('', anchor, head);
+ finalHead = anchor;
+ if (args.linewise) {
+ finalHead = motions.moveToFirstNonWhiteSpaceCharacter(cm, anchor);
}
- }
- if (operatorArgs.linewise) {
- cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
} else {
- cm.setCursor(curStart);
+ text = cm.getSelection();
+ var replacement = fillArray('', ranges.length);
+ cm.replaceSelections(replacement);
+ finalHead = ranges[0].anchor;
}
+ vimGlobalState.registerController.pushText(
+ args.registerName, 'delete', text,
+ args.linewise, vim.visualBlock);
+ return finalHead;
},
- indent: function(cm, operatorArgs, vim, curStart, curEnd) {
- var startLine = curStart.line;
- var endLine = curEnd.line;
+ indent: function(cm, args, ranges) {
+ var vim = cm.state.vim;
+ var startLine = ranges[0].anchor.line;
+ var endLine = vim.visualBlock ?
+ ranges[ranges.length - 1].anchor.line :
+ ranges[0].head.line;
// In visual mode, n> shifts the selection right n times, instead of
// shifting n lines right once.
- var repeat = (vim.visualMode) ? operatorArgs.repeat : 1;
- if (operatorArgs.linewise) {
+ var repeat = (vim.visualMode) ? args.repeat : 1;
+ if (args.linewise) {
// The only way to delete a newline is to delete until the start of
// the next line, so in linewise mode evalInput will include the next
// line. We don't want this in indent, so we go back a line.
@@ -3359,39 +3270,52 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
}
for (var i = startLine; i <= endLine; i++) {
for (var j = 0; j < repeat; j++) {
- cm.indentLine(i, operatorArgs.indentRight);
+ cm.indentLine(i, args.indentRight);
}
}
- cm.setCursor(curStart);
- cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
+ return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);
},
- swapcase: function(cm, operatorArgs, _vim, _curStart, _curEnd, _curOriginal) {
+ changeCase: function(cm, args, ranges, oldAnchor, newHead) {
var selections = cm.getSelections();
- var ranges = cm.listSelections();
var swapped = [];
+ var toLower = args.toLower;
for (var j = 0; j < selections.length; j++) {
var toSwap = selections[j];
var text = '';
- for (var i = 0; i < toSwap.length; i++) {
- var character = toSwap.charAt(i);
- text += isUpperCase(character) ? character.toLowerCase() :
- character.toUpperCase();
+ if (toLower === true) {
+ text = toSwap.toLowerCase();
+ } else if (toLower === false) {
+ text = toSwap.toUpperCase();
+ } else {
+ for (var i = 0; i < toSwap.length; i++) {
+ var character = toSwap.charAt(i);
+ text += isUpperCase(character) ? character.toLowerCase() :
+ character.toUpperCase();
+ }
}
swapped.push(text);
}
cm.replaceSelections(swapped);
- var curStart = ranges[0].anchor;
- var curEnd = ranges[0].head;
- if (!operatorArgs.shouldMoveCursor) {
- cm.setCursor(cursorIsBefore(curStart, curEnd) ? curStart : curEnd);
+ if (args.shouldMoveCursor){
+ return newHead;
+ } else if (!cm.state.vim.visualMode && args.linewise && ranges[0].anchor.line + 1 == ranges[0].head.line) {
+ return motions.moveToFirstNonWhiteSpaceCharacter(cm, oldAnchor);
+ } else if (args.linewise){
+ return oldAnchor;
+ } else {
+ return cursorMin(ranges[0].anchor, ranges[0].head);
}
},
- yank: function(cm, operatorArgs, vim, _curStart, _curEnd, curOriginal) {
+ yank: function(cm, args, ranges, oldAnchor) {
+ var vim = cm.state.vim;
var text = cm.getSelection();
+ var endPos = vim.visualMode
+ ? cursorMin(vim.sel.anchor, vim.sel.head, ranges[0].head, ranges[0].anchor)
+ : oldAnchor;
vimGlobalState.registerController.pushText(
- operatorArgs.registerName, 'yank',
- text, operatorArgs.linewise, vim.visualBlock);
- cm.setCursor(curOriginal);
+ args.registerName, 'yank',
+ text, args.linewise, vim.visualBlock);
+ return endPos;
}
};
@@ -3483,41 +3407,40 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
vim.insertMode = true;
vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1;
var insertAt = (actionArgs) ? actionArgs.insertAt : null;
- if (vim.visualMode) {
- var selections = getSelectedAreaRange(cm, vim);
- var selectionStart = selections[0];
- var selectionEnd = selections[1];
- }
+ var sel = vim.sel;
+ var head = actionArgs.head || cm.getCursor('head');
+ var height = cm.listSelections().length;
if (insertAt == 'eol') {
- var cursor = cm.getCursor();
- cursor = Pos(cursor.line, lineLength(cm, cursor.line));
- cm.setCursor(cursor);
+ head = Pos(head.line, lineLength(cm, head.line));
} else if (insertAt == 'charAfter') {
- cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
+ head = offsetCursor(head, 0, 1);
} else if (insertAt == 'firstNonBlank') {
- if (vim.visualMode && !vim.visualBlock) {
- if (selectionEnd.line < selectionStart.line) {
- cm.setCursor(selectionEnd);
+ head = motions.moveToFirstNonWhiteSpaceCharacter(cm, head);
+ } else if (insertAt == 'startOfSelectedArea') {
+ if (!vim.visualBlock) {
+ if (sel.head.line < sel.anchor.line) {
+ head = sel.head;
} else {
- selectionStart = Pos(selectionStart.line, 0);
- cm.setCursor(selectionStart);
+ head = Pos(sel.anchor.line, 0);
}
- cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
- } else if (vim.visualBlock) {
- selectionEnd = Pos(selectionEnd.line, selectionStart.ch);
- cm.setCursor(selectionStart);
- selectBlock(cm, selectionEnd);
} else {
- cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
+ head = Pos(
+ Math.min(sel.head.line, sel.anchor.line),
+ Math.min(sel.head.ch, sel.anchor.ch));
+ height = Math.abs(sel.head.line - sel.anchor.line) + 1;
}
} else if (insertAt == 'endOfSelectedArea') {
- if (vim.visualBlock) {
- selectionStart = Pos(selectionStart.line, selectionEnd.ch);
- cm.setCursor(selectionStart);
- selectBlock(cm, selectionEnd);
- } else if (selectionEnd.line < selectionStart.line) {
- selectionEnd = Pos(selectionStart.line, 0);
- cm.setCursor(selectionEnd);
+ if (!vim.visualBlock) {
+ if (sel.head.line >= sel.anchor.line) {
+ head = offsetCursor(sel.head, 0, 1);
+ } else {
+ head = Pos(sel.anchor.line, 0);
+ }
+ } else {
+ head = Pos(
+ Math.min(sel.head.line, sel.anchor.line),
+ Math.max(sel.head.ch + 1, sel.anchor.ch));
+ height = Math.abs(sel.head.line - sel.anchor.line) + 1;
}
} else if (insertAt == 'inplace') {
if (vim.visualMode){
@@ -3543,129 +3466,68 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
if (vim.visualMode) {
exitVisualMode(cm);
}
+ selectForInsert(cm, head, height);
},
toggleVisualMode: function(cm, actionArgs, vim) {
var repeat = actionArgs.repeat;
- var curStart = cm.getCursor();
- var curEnd;
- var selections = cm.listSelections();
+ var anchor = cm.getCursor();
+ var head;
// TODO: The repeat should actually select number of characters/lines
// equal to the repeat times the size of the previous visual
// operation.
if (!vim.visualMode) {
- cm.on('mousedown', exitVisualMode);
+ // Entering visual mode
vim.visualMode = true;
vim.visualLine = !!actionArgs.linewise;
vim.visualBlock = !!actionArgs.blockwise;
- if (vim.visualLine) {
- curStart.ch = 0;
- curEnd = clipCursorToContent(
- cm, Pos(curStart.line + repeat - 1, lineLength(cm, curStart.line)),
- true /** includeLineBreak */);
- } else {
- curEnd = clipCursorToContent(
- cm, Pos(curStart.line, curStart.ch + repeat),
+ head = clipCursorToContent(
+ cm, Pos(anchor.line, anchor.ch + repeat - 1),
true /** includeLineBreak */);
- }
- cm.setSelection(curStart, curEnd);
- CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : ""});
+ vim.sel = {
+ anchor: anchor,
+ head: head
+ };
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
+ updateCmSelection(cm);
+ updateMark(cm, vim, '<', cursorMin(anchor, head));
+ updateMark(cm, vim, '>', cursorMax(anchor, head));
+ } else if (vim.visualLine ^ actionArgs.linewise ||
+ vim.visualBlock ^ actionArgs.blockwise) {
+ // Toggling between modes
+ vim.visualLine = !!actionArgs.linewise;
+ vim.visualBlock = !!actionArgs.blockwise;
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
+ updateCmSelection(cm);
} else {
- curStart = cm.getCursor('anchor');
- curEnd = cm.getCursor('head');
- if (vim.visualLine) {
- if (actionArgs.blockwise) {
- // This means Ctrl-V pressed in linewise visual
- vim.visualBlock = true;
- selectBlock(cm, curEnd);
- CodeMirror.signal(cm, 'vim-mode-change', {mode: 'visual', subMode: 'blockwise'});
- } else if (!actionArgs.linewise) {
- // v pressed in linewise, switch to characterwise visual mode
- CodeMirror.signal(cm, 'vim-mode-change', {mode: 'visual'});
- } else {
- exitVisualMode(cm);
- }
- vim.visualLine = false;
- } else if (vim.visualBlock) {
- if (actionArgs.linewise) {
- // Shift-V pressed in blockwise visual mode
- vim.visualLine = true;
- curStart = Pos(selections[0].anchor.line, 0);
- curEnd = Pos(selections[selections.length-1].anchor.line, lineLength(cm, selections[selections.length-1].anchor.line));
- cm.setSelection(curStart, curEnd);
- CodeMirror.signal(cm, 'vim-mode-change', {mode: 'visual', subMode: 'linewise'});
- } else if (!actionArgs.blockwise) {
- // v pressed in blockwise mode, Switch to characterwise
- if (curEnd != selections[0].head) {
- curStart = selections[0].anchor;
- } else {
- curStart = selections[selections.length-1].anchor;
- }
- cm.setSelection(curStart, curEnd);
- CodeMirror.signal(cm, 'vim-mode-change', {mode: 'visual'});
- } else {
- exitVisualMode(cm);
- }
- vim.visualBlock = false;
- } else if (actionArgs.linewise) {
- // Shift-V pressed in characterwise visual mode. Switch to linewise
- // visual mode instead of exiting visual mode.
- vim.visualLine = true;
- curStart.ch = cursorIsBefore(curStart, curEnd) ? 0 :
- lineLength(cm, curStart.line);
- curEnd.ch = cursorIsBefore(curStart, curEnd) ?
- lineLength(cm, curEnd.line) : 0;
- cm.setSelection(curStart, curEnd);
- CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: "linewise"});
- } else if (actionArgs.blockwise) {
- vim.visualBlock = true;
- selectBlock(cm, curEnd);
- CodeMirror.signal(cm, 'vim-mode-change', {mode: 'visual', subMode: 'blockwise'});
- } else {
- exitVisualMode(cm);
- }
+ exitVisualMode(cm);
}
- updateMark(cm, vim, '<', cursorIsBefore(curStart, curEnd) ? curStart
- : curEnd);
- updateMark(cm, vim, '>', cursorIsBefore(curStart, curEnd) ? curEnd
- : curStart);
},
reselectLastSelection: function(cm, _actionArgs, vim) {
- var curStart = vim.marks['<'].find();
- var curEnd = vim.marks['>'].find();
var lastSelection = vim.lastSelection;
+ if (vim.visualMode) {
+ updateLastSelection(cm, vim);
+ }
if (lastSelection) {
- // Set the selections as per last selection
- var selectionStart = lastSelection.curStartMark.find();
- var selectionEnd = lastSelection.curEndMark.find();
- var blockwise = lastSelection.visualBlock;
- // update last selection
- updateLastSelection(cm, vim, curStart, curEnd);
- if (blockwise) {
- cm.setCursor(selectionStart);
- selectionStart = selectBlock(cm, selectionEnd);
- } else {
- cm.setSelection(selectionStart, selectionEnd);
- selectionStart = cm.getCursor('anchor');
- selectionEnd = cm.getCursor('head');
- }
- if (vim.visualMode) {
- updateMark(cm, vim, '<', cursorIsBefore(selectionStart, selectionEnd) ? selectionStart
- : selectionEnd);
- updateMark(cm, vim, '>', cursorIsBefore(selectionStart, selectionEnd) ? selectionEnd
- : selectionStart);
+ var anchor = lastSelection.anchorMark.find();
+ var head = lastSelection.headMark.find();
+ if (!anchor || !head) {
+ // If the marks have been destroyed due to edits, do nothing.
+ return;
}
- // Last selection is updated now
+ vim.sel = {
+ anchor: anchor,
+ head: head
+ };
vim.visualMode = true;
- if (lastSelection.visualLine) {
- vim.visualLine = true;
- vim.visualBlock = false;
- } else if (lastSelection.visualBlock) {
- vim.visualLine = false;
- vim.visualBlock = true;
- } else {
- vim.visualBlock = vim.visualLine = false;
- }
- CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : ""});
+ vim.visualLine = lastSelection.visualLine;
+ vim.visualBlock = lastSelection.visualBlock;
+ updateCmSelection(cm);
+ updateMark(cm, vim, '<', cursorMin(anchor, head));
+ updateMark(cm, vim, '>', cursorMax(anchor, head));
+ CodeMirror.signal(cm, 'vim-mode-change', {
+ mode: 'visual',
+ subMode: vim.visualLine ? 'linewise' :
+ vim.visualBlock ? 'blockwise' : ''});
}
},
joinLines: function(cm, actionArgs, vim) {
@@ -3682,18 +3544,19 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
Infinity));
}
var finalCh = 0;
- cm.operation(function() {
- for (var i = curStart.line; i < curEnd.line; i++) {
- finalCh = lineLength(cm, curStart.line);
- var tmp = Pos(curStart.line + 1,
- lineLength(cm, curStart.line + 1));
- var text = cm.getRange(curStart, tmp);
- text = text.replace(/\n\s*/g, ' ');
- cm.replaceRange(text, curStart, tmp);
- }
- var curFinalPos = Pos(curStart.line, finalCh);
- cm.setCursor(curFinalPos);
- });
+ for (var i = curStart.line; i < curEnd.line; i++) {
+ finalCh = lineLength(cm, curStart.line);
+ var tmp = Pos(curStart.line + 1,
+ lineLength(cm, curStart.line + 1));
+ var text = cm.getRange(curStart, tmp);
+ text = text.replace(/\n\s*/g, ' ');
+ cm.replaceRange(text, curStart, tmp);
+ }
+ var curFinalPos = Pos(curStart.line, finalCh);
+ cm.setCursor(curFinalPos);
+ if (vim.visualMode) {
+ exitVisualMode(cm);
+ }
},
newLineAndEnterInsertMode: function(cm, actionArgs, vim) {
vim.insertMode = true;
@@ -3722,11 +3585,12 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
return;
}
if (actionArgs.matchIndent) {
- // length that considers tabs and cm.options.tabSize
+ var tabSize = cm.getOption("tabSize");
+ // length that considers tabs and tabSize
var whitespaceLength = function(str) {
var tabs = (str.split("\t").length - 1);
var spaces = (str.split(" ").length - 1);
- return tabs * cm.options.tabSize + spaces * 1;
+ return tabs * tabSize + spaces * 1;
};
var currentLine = cm.getLine(cm.getCursor().line);
var indent = whitespaceLength(currentLine.match(/^\s*/)[0]);
@@ -3739,8 +3603,8 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
if (newIndent < 0) {
return "";
}
- else if (cm.options.indentWithTabs) {
- var quotient = Math.floor(newIndent / cm.options.tabSize);
+ else if (cm.getOption("indentWithTabs")) {
+ var quotient = Math.floor(newIndent / tabSize);
return Array(quotient + 1).join('\t');
}
else {
@@ -3788,7 +3652,7 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
var emptyStrings = new Array(selections.length).join('1').split('1');
// save the curEnd marker before it get cleared due to cm.replaceRange.
if (vim.lastSelection) {
- lastSelectionCurEnd = vim.lastSelection.curEndMark.find();
+ lastSelectionCurEnd = vim.lastSelection.headMark.find();
}
// push the previously selected text to unnamed register
vimGlobalState.registerController.unnamedRegister.setText(selectedText);
@@ -3812,7 +3676,7 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
}
// restore the the curEnd marker
if(lastSelectionCurEnd) {
- vim.lastSelection.curEndMark = cm.setBookmark(lastSelectionCurEnd);
+ vim.lastSelection.headMark = cm.setBookmark(lastSelectionCurEnd);
}
if (linewise) {
curPosFinal.ch=0;
@@ -3854,10 +3718,10 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
}
}
}
- cm.setCursor(curPosFinal);
if (vim.visualMode) {
exitVisualMode(cm);
}
+ cm.setCursor(curPosFinal);
},
undo: function(cm, actionArgs) {
cm.operation(function() {
@@ -3902,7 +3766,7 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
replaceWithStr = replaceWithStr.replace(/[^\n]/g, replaceWith);
if (vim.visualBlock) {
// Tabs are split in visua block before replacing
- var spaces = new Array(cm.options.tabSize+1).join(' ');
+ var spaces = new Array(cm.getOption("tabSize")+1).join(' ');
replaceWithStr = cm.getSelection();
replaceWithStr = replaceWithStr.replace(/\t/g, spaces).replace(/[^\n]/g, replaceWith).split('\n');
cm.replaceSelections(replaceWithStr);
@@ -3958,28 +3822,7 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
}
repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);
},
- changeCase: function(cm, actionArgs, vim) {
- var selectionStart = getSelectedAreaRange(cm, vim)[0];
- var text = cm.getSelection();
- var lastSelectionCurEnd;
- var blockSelection;
- if (vim.lastSelection) {
- // save the curEnd marker to avoid its removal due to cm.replaceRange
- lastSelectionCurEnd = vim.lastSelection.curEndMark.find();
- blockSelection = vim.lastSelection.visualBlock;
- }
- var toLower = actionArgs.toLower;
- text = toLower ? text.toLowerCase() : text.toUpperCase();
- cm.replaceSelections(vim.visualBlock || blockSelection ? text.split('\n') : [text]);
- // restore the last selection curEnd marker
- if (lastSelectionCurEnd) {
- vim.lastSelection.curEndMark = cm.setBookmark(lastSelectionCurEnd);
- }
- cm.setCursor(selectionStart);
- if (vim.visualMode) {
- exitVisualMode(cm);
- }
- }
+ exitInsertMode: exitInsertMode
};
/*
@@ -4007,16 +3850,66 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
return ret;
}
function offsetCursor(cur, offsetLine, offsetCh) {
+ if (typeof offsetLine === 'object') {
+ offsetCh = offsetLine.ch;
+ offsetLine = offsetLine.line;
+ }
return Pos(cur.line + offsetLine, cur.ch + offsetCh);
}
- function matchKeysPartial(pressed, mapped) {
- for (var i = 0; i < pressed.length; i++) {
- // 'character' means any character. For mark, register commads, etc.
- if (pressed[i] != mapped[i] && mapped[i] != 'character') {
- return false;
+ function getOffset(anchor, head) {
+ return {
+ line: head.line - anchor.line,
+ ch: head.line - anchor.line
+ };
+ }
+ function commandMatches(keys, keyMap, context, inputState) {
+ // Partial matches are not applied. They inform the key handler
+ // that the current key sequence is a subsequence of a valid key
+ // sequence, so that the key buffer is not cleared.
+ var match, partial = [], full = [];
+ for (var i = 0; i < keyMap.length; i++) {
+ var command = keyMap[i];
+ if (context == 'insert' && command.context != 'insert' ||
+ command.context && command.context != context ||
+ inputState.operator && command.type == 'action' ||
+ !(match = commandMatch(keys, command.keys))) { continue; }
+ if (match == 'partial') { partial.push(command); }
+ if (match == 'full') { full.push(command); }
+ }
+ return {
+ partial: partial.length && partial,
+ full: full.length && full
+ };
+ }
+ function commandMatch(pressed, mapped) {
+ if (mapped.slice(-11) == '') {
+ // Last character matches anything.
+ var prefixLen = mapped.length - 11;
+ var pressedPrefix = pressed.slice(0, prefixLen);
+ var mappedPrefix = mapped.slice(0, prefixLen);
+ return pressedPrefix == mappedPrefix && pressed.length > prefixLen ? 'full' :
+ mappedPrefix.indexOf(pressedPrefix) == 0 ? 'partial' : false;
+ } else {
+ return pressed == mapped ? 'full' :
+ mapped.indexOf(pressed) == 0 ? 'partial' : false;
+ }
+ }
+ function lastChar(keys) {
+ var match = /^.*(<[\w\-]+>)$/.exec(keys);
+ var selectedCharacter = match ? match[1] : keys.slice(-1);
+ if (selectedCharacter.length > 1){
+ switch(selectedCharacter){
+ case '':
+ selectedCharacter='\n';
+ break;
+ case '':
+ selectedCharacter=' ';
+ break;
+ default:
+ break;
}
}
- return true;
+ return selectedCharacter;
}
function repeatFn(cm, fn, repeat) {
return function() {
@@ -4040,7 +3933,19 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
}
return false;
}
- function cusrorIsBetween(cur1, cur2, cur3) {
+ function cursorMin(cur1, cur2) {
+ if (arguments.length > 2) {
+ cur2 = cursorMin.apply(undefined, Array.prototype.slice.call(arguments, 1));
+ }
+ return cursorIsBefore(cur1, cur2) ? cur1 : cur2;
+ }
+ function cursorMax(cur1, cur2) {
+ if (arguments.length > 2) {
+ cur2 = cursorMax.apply(undefined, Array.prototype.slice.call(arguments, 1));
+ }
+ return cursorIsBefore(cur1, cur2) ? cur2 : cur1;
+ }
+ function cursorIsBetween(cur1, cur2, cur3) {
// returns true if cur2 is between cur1 and cur3.
var cur1before2 = cursorIsBefore(cur1, cur2);
var cur2before3 = cursorIsBefore(cur2, cur3);
@@ -4075,121 +3980,59 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
// Distance between selectionEnd.ch and any(first considered here) selection.ch
function selectBlock(cm, selectionEnd) {
var selections = [], ranges = cm.listSelections();
- var firstRange = ranges[0].anchor, lastRange = ranges[ranges.length-1].anchor;
- var start, end, direction, selectionStart;
- var curEnd = cm.getCursor('head');
- var originalSelectionEnd = copyCursor(selectionEnd);
- start = firstRange.line;
- end = lastRange.line;
- if (selectionEnd.line < curEnd.line) {
- direction = 'up';
- } else if (selectionEnd.line > curEnd.line) {
- direction = 'down';
- } else {
- if (selectionEnd.ch != curEnd.ch) {
- direction = selectionEnd.ch > curEnd.ch ? 'right' : 'left';
- }
- selectionStart = cm.getCursor('anchor');
- }
- var primIndex = getIndex(ranges, curEnd);
- // sets to true when selectionEnd already lies inside the existing selections
- selectionEnd = cm.clipPos(selectionEnd);
- var contains = getIndex(ranges, selectionEnd) < 0 ? false : true;
- var isClipped = !cursorEqual(originalSelectionEnd, selectionEnd);
- // This function helps to check selection crossing
- // in case of short lines.
- var processSelectionCrossing = function() {
- if (isClipped) {
- if (curEnd.ch >= selectionStart.ch) {
- selectionStart.ch++;
- }
- } else if (curEnd.ch == lineLength(cm, curEnd.line)) {
- if (cursorEqual(ranges[primIndex].anchor, ranges[primIndex].head) && ranges.length>1) {
- if (direction == 'up') {
- if (contains || primIndex>0) {
- start = firstRange.line;
- end = selectionEnd.line;
- selectionStart = ranges[primIndex-1].anchor;
- }
- } else {
- if (contains || primIndex == 0) {
- end = lastRange.line;
- start = selectionEnd.line;
- selectionStart = ranges[primIndex+1].anchor;
- }
- }
- if (selectionEnd.ch >= selectionStart.ch) {
- selectionStart.ch--;
- }
- }
- }
- };
- switch(direction) {
- case 'up':
- start = contains ? firstRange.line : selectionEnd.line;
- end = contains ? selectionEnd.line : lastRange.line;
- selectionStart = lastRange;
- processSelectionCrossing();
- break;
- case 'down':
- start = contains ? selectionEnd.line : firstRange.line;
- end = contains ? lastRange.line : selectionEnd.line;
- selectionStart = firstRange;
- processSelectionCrossing();
- break;
- case 'left':
- if ((selectionEnd.ch <= selectionStart.ch) && (curEnd.ch > selectionStart.ch)) {
- selectionStart.ch++;
- selectionEnd.ch--;
- }
- break;
- case 'right':
- if ((selectionStart.ch <= selectionEnd.ch) && (curEnd.ch < selectionStart.ch)) {
- selectionStart.ch--;
- selectionEnd.ch++;
- }
- break;
- default:
- start = selectionStart.line;
- end = selectionEnd.line;
- }
- while (start <= end) {
- var anchor = {line: start, ch: selectionStart.ch};
- var head = {line: start, ch: selectionEnd.ch};
- var range = {anchor: anchor, head: head};
+ var head = copyCursor(cm.clipPos(selectionEnd));
+ var isClipped = !cursorEqual(selectionEnd, head);
+ var curHead = cm.getCursor('head');
+ var primIndex = getIndex(ranges, curHead);
+ var wasClipped = cursorEqual(ranges[primIndex].head, ranges[primIndex].anchor);
+ var max = ranges.length - 1;
+ var index = max - primIndex > primIndex ? max : 0;
+ var base = ranges[index].anchor;
+
+ var firstLine = Math.min(base.line, head.line);
+ var lastLine = Math.max(base.line, head.line);
+ var baseCh = base.ch, headCh = head.ch;
+
+ var dir = ranges[index].head.ch - baseCh;
+ var newDir = headCh - baseCh;
+ if (dir > 0 && newDir <= 0) {
+ baseCh++;
+ if (!isClipped) { headCh--; }
+ } else if (dir < 0 && newDir >= 0) {
+ baseCh--;
+ if (!wasClipped) { headCh++; }
+ } else if (dir < 0 && newDir == -1) {
+ baseCh--;
+ headCh++;
+ }
+ for (var line = firstLine; line <= lastLine; line++) {
+ var range = {anchor: new Pos(line, baseCh), head: new Pos(line, headCh)};
selections.push(range);
- if (cursorEqual(head, selectionEnd)) {
- primIndex = selections.indexOf(range);
- }
- start++;
}
- // Update selectionEnd and selectionStart
- // after selection crossing
- selectionEnd.ch = selections[0].head.ch;
- selectionStart.ch = selections[0].anchor.ch;
- if (cursorEqual(selectionEnd, selections[0].head)) {
- selectionStart.line = selections[selections.length-1].anchor.line;
- } else {
- selectionStart.line = selections[0].anchor.line;
+ primIndex = head.line == lastLine ? selections.length - 1 : 0;
+ cm.setSelections(selections);
+ selectionEnd.ch = headCh;
+ base.ch = baseCh;
+ return base;
+ }
+ function selectForInsert(cm, head, height) {
+ var sel = [];
+ for (var i = 0; i < height; i++) {
+ var lineHead = offsetCursor(head, i, 0);
+ sel.push({anchor: lineHead, head: lineHead});
}
- cm.setSelections(selections, primIndex);
- return selectionStart;
+ cm.setSelections(sel, 0);
}
// getIndex returns the index of the cursor in the selections.
function getIndex(ranges, cursor, end) {
- var pos = -1;
for (var i = 0; i < ranges.length; i++) {
- var atAnchor = cursorEqual(ranges[i].anchor, cursor);
- var atHead = cursorEqual(ranges[i].head, cursor);
- if (end == 'head') {
- pos = atHead ? i : pos;
- } else if (end == 'anchor') {
- pos = atAnchor ? i : pos;
- } else {
- pos = (atAnchor || atHead) ? i : pos;
+ var atAnchor = end != 'head' && cursorEqual(ranges[i].anchor, cursor);
+ var atHead = end != 'anchor' && cursorEqual(ranges[i].head, cursor);
+ if (atAnchor || atHead) {
+ return i;
}
}
- return pos;
+ return -1;
}
function getSelectedAreaRange(cm, vim) {
var lastSelection = vim.lastSelection;
@@ -4220,8 +4063,8 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
}
cm.setSelections(selections);
} else {
- var start = lastSelection.curStartMark.find();
- var end = lastSelection.curEndMark.find();
+ var start = lastSelection.anchorMark.find();
+ var end = lastSelection.headMark.find();
var line = end.line - start.line;
var ch = end.ch - start.ch;
selectionEnd = {line: selectionEnd.line + line, ch: line ? selectionEnd.ch : ch + selectionEnd.ch};
@@ -4240,51 +4083,133 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
return getCurrentSelectedAreaRange();
}
}
- function updateLastSelection(cm, vim, selectionStart, selectionEnd) {
- if (!selectionStart || !selectionEnd) {
- selectionStart = vim.marks['<'].find() || cm.getCursor('anchor');
- selectionEnd = vim.marks['>'].find() || cm.getCursor('head');
- }
+ // Updates the previous selection with the current selection's values. This
+ // should only be called in visual mode.
+ function updateLastSelection(cm, vim) {
+ var anchor = vim.sel.anchor;
+ var head = vim.sel.head;
// To accommodate the effect of lastPastedText in the last selection
if (vim.lastPastedText) {
- selectionEnd = cm.posFromIndex(cm.indexFromPos(selectionStart) + vim.lastPastedText.length);
+ head = cm.posFromIndex(cm.indexFromPos(anchor) + vim.lastPastedText.length);
vim.lastPastedText = null;
}
- var ranges = cm.listSelections();
- // This check ensures to set the cursor
- // position where we left off in previous selection
- var swap = getIndex(ranges, selectionStart, 'head') > -1;
- if (vim.visualBlock) {
- var height = Math.abs(selectionStart.line - selectionEnd.line)+1;
- var width = Math.abs(selectionStart.ch - selectionEnd.ch);
- var block = {height: height, width: width};
- }
- // can't use selection state here because yank has already reset its cursor
- // Also, Bookmarks make the visual selections robust to edit operations
- vim.lastSelection = {'curStartMark': cm.setBookmark(swap ? selectionEnd : selectionStart),
- 'curEndMark': cm.setBookmark(swap ? selectionStart : selectionEnd),
+ vim.lastSelection = {'anchorMark': cm.setBookmark(anchor),
+ 'headMark': cm.setBookmark(head),
+ 'anchor': copyCursor(anchor),
+ 'head': copyCursor(head),
'visualMode': vim.visualMode,
'visualLine': vim.visualLine,
- 'visualBlock': block};
+ 'visualBlock': vim.visualBlock};
}
+ function expandSelection(cm, start, end) {
+ var sel = cm.state.vim.sel;
+ var head = sel.head;
+ var anchor = sel.anchor;
+ var tmp;
+ if (cursorIsBefore(end, start)) {
+ tmp = end;
+ end = start;
+ start = tmp;
+ }
+ if (cursorIsBefore(head, anchor)) {
+ head = cursorMin(start, head);
+ anchor = cursorMax(anchor, end);
+ } else {
+ anchor = cursorMin(start, anchor);
+ head = cursorMax(head, end);
+ head = offsetCursor(head, 0, -1);
+ if (head.ch == -1 && head.line != cm.firstLine()) {
+ head = Pos(head.line - 1, lineLength(cm, head.line - 1));
+ }
+ }
+ return [anchor, head];
+ }
+ /**
+ * Updates the CodeMirror selection to match the provided vim selection.
+ * If no arguments are given, it uses the current vim selection state.
+ */
+ function updateCmSelection(cm, sel, mode) {
+ var vim = cm.state.vim;
+ sel = sel || vim.sel;
+ var mode = mode ||
+ vim.visualLine ? 'line' : vim.visualBlock ? 'block' : 'char';
+ var cmSel = makeCmSelection(cm, sel, mode);
+ cm.setSelections(cmSel.ranges, cmSel.primary);
+ updateFakeCursor(cm);
+ }
+ function makeCmSelection(cm, sel, mode, exclusive) {
+ var head = copyCursor(sel.head);
+ var anchor = copyCursor(sel.anchor);
+ if (mode == 'char') {
+ var headOffset = !exclusive && !cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
+ var anchorOffset = cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
+ head = offsetCursor(sel.head, 0, headOffset);
+ anchor = offsetCursor(sel.anchor, 0, anchorOffset);
+ return {
+ ranges: [{anchor: anchor, head: head}],
+ primary: 0
+ };
+ } else if (mode == 'line') {
+ if (!cursorIsBefore(sel.head, sel.anchor)) {
+ anchor.ch = 0;
- function exitVisualMode(cm) {
- cm.off('mousedown', exitVisualMode);
+ var lastLine = cm.lastLine();
+ if (head.line > lastLine) {
+ head.line = lastLine;
+ }
+ head.ch = lineLength(cm, head.line);
+ } else {
+ head.ch = 0;
+ anchor.ch = lineLength(cm, anchor.line);
+ }
+ return {
+ ranges: [{anchor: anchor, head: head}],
+ primary: 0
+ };
+ } else if (mode == 'block') {
+ var top = Math.min(anchor.line, head.line),
+ left = Math.min(anchor.ch, head.ch),
+ bottom = Math.max(anchor.line, head.line),
+ right = Math.max(anchor.ch, head.ch) + 1;
+ var height = bottom - top + 1;
+ var primary = head.line == top ? 0 : height - 1;
+ var ranges = [];
+ for (var i = 0; i < height; i++) {
+ ranges.push({
+ anchor: Pos(top + i, left),
+ head: Pos(top + i, right)
+ });
+ }
+ return {
+ ranges: ranges,
+ primary: primary
+ };
+ }
+ }
+ function getHead(cm) {
+ var cur = cm.getCursor('head');
+ if (cm.getSelection().length == 1) {
+ // Small corner case when only 1 character is selected. The "real"
+ // head is the left of head and anchor.
+ cur = cursorMin(cur, cm.getCursor('anchor'));
+ }
+ return cur;
+ }
+
+ /**
+ * If moveHead is set to false, the CodeMirror selection will not be
+ * touched. The caller assumes the responsibility of putting the cursor
+ * in the right place.
+ */
+ function exitVisualMode(cm, moveHead) {
var vim = cm.state.vim;
- var selectionStart = cm.getCursor('anchor');
- var selectionEnd = cm.getCursor('head');
- // hack to place the cursor at the right place
- // in case of visual block
- if (vim.visualBlock && (cursorIsBefore(selectionStart, selectionEnd))) {
- selectionEnd.ch--;
+ if (moveHead !== false) {
+ cm.setCursor(clipCursorToContent(cm, vim.sel.head));
}
updateLastSelection(cm, vim);
vim.visualMode = false;
vim.visualLine = false;
vim.visualBlock = false;
- if (!cursorEqual(selectionStart, selectionEnd)) {
- cm.setCursor(clipCursorToContent(cm, selectionEnd));
- }
CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
if (vim.fakeCursor) {
vim.fakeCursor.clear();
@@ -4339,7 +4264,7 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
}
function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) {
- var cur = cm.getCursor();
+ var cur = getHead(cm);
var line = cm.getLine(cur.line);
var idx = cur.ch;
@@ -4614,6 +4539,7 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
/**
* @param {CodeMirror} cm CodeMirror object.
+ * @param {Pos} cur The position to start from.
* @param {int} repeat Number of words to move past.
* @param {boolean} forward True to search forward. False to search
* backward.
@@ -4623,8 +4549,7 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
* False if only alphabet characters count as part of the word.
* @return {Cursor} The position the cursor should move to.
*/
- function moveToWord(cm, repeat, forward, wordEnd, bigWord) {
- var cur = cm.getCursor();
+ function moveToWord(cm, cur, repeat, forward, wordEnd, bigWord) {
var curStart = copyCursor(cur);
var words = [];
if (forward && !wordEnd || !forward && wordEnd) {
@@ -4724,8 +4649,8 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
// TODO: perhaps this finagling of start and end positions belonds
// in codmirror/replaceRange?
- function selectCompanionObject(cm, symb, inclusive) {
- var cur = cm.getCursor(), start, end;
+ function selectCompanionObject(cm, head, symb, inclusive) {
+ var cur = head, start, end;
var bracketRegexp = ({
'(': /[()]/, ')': /[()]/,
@@ -4769,8 +4694,8 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
// Takes in a symbol and a cursor and tries to simulate text objects that
// have identical opening and closing symbols
// TODO support across multiple lines
- function findBeginningAndEnd(cm, symb, inclusive) {
- var cur = copyCursor(cm.getCursor());
+ function findBeginningAndEnd(cm, head, symb, inclusive) {
+ var cur = copyCursor(head);
var line = cm.getLine(cur.line);
var chars = line.split('');
var start, end, i, len;
@@ -5203,6 +5128,7 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
// shortNames must not match the prefix of the other command.
var defaultExCommandMap = [
{ name: 'map' },
+ { name: 'imap', shortName: 'im' },
{ name: 'nmap', shortName: 'nm' },
{ name: 'vmap', shortName: 'vm' },
{ name: 'unmap' },
@@ -5217,10 +5143,10 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
{ name: 'registers', shortName: 'reg', excludeFromCommandHistory: true },
{ name: 'global', shortName: 'g' }
];
- Vim.ExCommandDispatcher = function() {
+ var ExCommandDispatcher = function() {
this.buildCommandMap_();
};
- Vim.ExCommandDispatcher.prototype = {
+ ExCommandDispatcher.prototype = {
processCommand: function(cm, input, opt_params) {
var vim = cm.state.vim;
var commandHistoryRegister = vimGlobalState.registerController.getRegister(':');
@@ -5257,7 +5183,7 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
if (command.type == 'exToKey') {
// Handle Ex to Key mapping.
for (var i = 0; i < command.toKeys.length; i++) {
- CodeMirror.Vim.handleKey(cm, command.toKeys[i]);
+ CodeMirror.Vim.handleKey(cm, command.toKeys[i], 'mapping');
}
return;
} else if (command.type == 'exToEx') {
@@ -5381,7 +5307,7 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
this.commandMap_[commandName] = {
name: commandName,
type: 'exToKey',
- toKeys: parseKeyString(rhs),
+ toKeys: rhs,
user: true
};
}
@@ -5389,7 +5315,7 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
if (rhs != ':' && rhs.charAt(0) == ':') {
// Key to Ex mapping.
var mapping = {
- keys: parseKeyString(lhs),
+ keys: lhs,
type: 'keyToEx',
exArgs: { input: rhs.substring(1) },
user: true};
@@ -5398,9 +5324,9 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
} else {
// Key to key mapping
var mapping = {
- keys: parseKeyString(lhs),
+ keys: lhs,
type: 'keyToKey',
- toKeys: parseKeyString(rhs),
+ toKeys: rhs,
user: true
};
if (ctx) { mapping.context = ctx; }
@@ -5409,15 +5335,6 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
}
},
unmap: function(lhs, ctx) {
- var arrayEquals = function(a, b) {
- if (a === b) return true;
- if (a == null || b == null) return true;
- if (a.length != b.length) return false;
- for (var i = 0; i < a.length; i++) {
- if (a[i] !== b[i]) return false;
- }
- return true;
- };
if (lhs != ':' && lhs.charAt(0) == ':') {
// Ex to Ex or Ex to key mapping
if (ctx) { throw Error('Mode not supported for ex mappings'); }
@@ -5428,9 +5345,9 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
}
} else {
// Key to Ex or key to key mapping
- var keys = parseKeyString(lhs);
+ var keys = lhs;
for (var i = 0; i < defaultKeymap.length; i++) {
- if (arrayEquals(keys, defaultKeymap[i].keys)
+ if (keys == defaultKeymap[i].keys
&& defaultKeymap[i].context === ctx
&& defaultKeymap[i].user) {
defaultKeymap.splice(i, 1);
@@ -5442,21 +5359,6 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
}
};
- // Converts a key string sequence of the form abd into Vim's
- // keymap representation.
- function parseKeyString(str) {
- var key, match;
- var keys = [];
- while (str) {
- match = (/<\w+-.+?>|<\w+>|./).exec(str);
- if (match === null)break;
- key = match[0];
- str = str.substring(match.index + key.length);
- keys.push(key);
- }
- return keys;
- }
-
var exCommands = {
map: function(cm, params, ctx) {
var mapArgs = params.args;
@@ -5468,6 +5370,7 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
}
exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx);
},
+ imap: function(cm, params) { this.map(cm, params, 'insert'); },
nmap: function(cm, params) { this.map(cm, params, 'normal'); },
vmap: function(cm, params) { this.map(cm, params, 'visual'); },
unmap: function(cm, params, ctx) {
@@ -5842,7 +5745,7 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
}
};
- var exCommandDispatcher = new Vim.ExCommandDispatcher();
+ var exCommandDispatcher = new ExCommandDispatcher();
/**
* @param {CodeMirror} cm CodeMirror instance we are in.
@@ -5930,6 +5833,7 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
break;
}
if (done) { stop(close); }
+ return true;
}
// Actually do replace.
@@ -5949,65 +5853,10 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
});
}
- // Register Vim with CodeMirror
- function buildVimKeyMap() {
- /**
- * Handle the raw key event from CodeMirror. Translate the
- * Shift + key modifier to the resulting letter, while preserving other
- * modifers.
- */
- function cmKeyToVimKey(key, modifier) {
- var vimKey = key;
- if (isUpperCase(vimKey) && modifier == 'Ctrl') {
- vimKey = vimKey.toLowerCase();
- }
- if (modifier) {
- // Vim will parse modifier+key combination as a single key.
- vimKey = modifier.charAt(0) + '-' + vimKey;
- }
- var specialKey = ({Enter:'CR',Backspace:'BS',Delete:'Del'})[vimKey];
- vimKey = specialKey ? specialKey : vimKey;
- vimKey = vimKey.length > 1 ? '<'+ vimKey + '>' : vimKey;
- return vimKey;
- }
-
- // Closure to bind CodeMirror, key, modifier.
- function keyMapper(vimKey) {
- return function(cm) {
- CodeMirror.signal(cm, 'vim-keypress', vimKey);
- CodeMirror.Vim.handleKey(cm, vimKey);
- };
- }
-
- var cmToVimKeymap = {
- 'nofallthrough': true,
- 'style': 'fat-cursor'
- };
- function bindKeys(keys, modifier) {
- for (var i = 0; i < keys.length; i++) {
- var key = keys[i];
- if (!modifier && key.length == 1) {
- // Wrap all keys without modifiers with '' to identify them by their
- // key characters instead of key identifiers.
- key = "'" + key + "'";
- }
- var vimKey = cmKeyToVimKey(keys[i], modifier);
- var cmKey = modifier ? modifier + '-' + key : key;
- cmToVimKeymap[cmKey] = keyMapper(vimKey);
- }
- }
- bindKeys(upperCaseAlphabet);
- bindKeys(lowerCaseAlphabet);
- bindKeys(upperCaseAlphabet, 'Ctrl');
- bindKeys(specialSymbols);
- bindKeys(specialSymbols, 'Ctrl');
- bindKeys(numbers);
- bindKeys(numbers, 'Ctrl');
- bindKeys(specialKeys);
- bindKeys(specialKeys, 'Ctrl');
- return cmToVimKeymap;
- }
- CodeMirror.keyMap.vim = buildVimKeyMap();
+ CodeMirror.keyMap.vim = {
+ attach: attachVimMap,
+ detach: detachVimMap
+ };
function exitInsertMode(cm) {
var vim = cm.state.vim;
@@ -6063,63 +5912,13 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
}
}
- defineOption('enableInsertModeEscKeys', false, 'boolean');
- // Use this option to customize the two-character ESC keymap.
- // If you want to use characters other than i j or k you'll have to add
- // lines to the vim-insert and await-second keymaps later in this file.
- defineOption('insertModeEscKeys', 'kj', 'string');
// The timeout in milliseconds for the two-character ESC keymap should be
// adjusted according to your typing speed to prevent false positives.
defineOption('insertModeEscKeysTimeout', 200, 'number');
- function firstEscCharacterHandler(ch) {
- return function(cm){
- var keys = getOption('insertModeEscKeys');
- var firstEscCharacter = keys && keys.length > 1 && keys.charAt(0);
- if (!getOption('enableInsertModeEscKeys')|| firstEscCharacter !== ch) {
- return CodeMirror.Pass;
- } else {
- cm.replaceRange(ch, cm.getCursor(), cm.getCursor(), "+input");
- cm.setOption('keyMap', 'await-second');
- cm.state.vim.awaitingEscapeSecondCharacter = true;
- setTimeout(
- function(){
- if(cm.state.vim.awaitingEscapeSecondCharacter) {
- cm.state.vim.awaitingEscapeSecondCharacter = false;
- cm.setOption('keyMap', 'vim-insert');
- }
- },
- getOption('insertModeEscKeysTimeout'));
- }
- };
- }
- function secondEscCharacterHandler(ch){
- return function(cm) {
- var keys = getOption('insertModeEscKeys');
- var secondEscCharacter = keys && keys.length > 1 && keys.charAt(1);
- if (!getOption('enableInsertModeEscKeys')|| secondEscCharacter !== ch) {
- return CodeMirror.Pass;
- // This is not the handler you're looking for. Just insert as usual.
- } else {
- if (cm.state.vim.insertMode) {
- var lastChange = vimGlobalState.macroModeState.lastInsertModeChanges;
- if (lastChange && lastChange.changes.length) {
- lastChange.changes.pop();
- }
- }
- cm.state.vim.awaitingEscapeSecondCharacter = false;
- cm.replaceRange('', {ch: cm.getCursor().ch - 1, line: cm.getCursor().line},
- cm.getCursor(), "+input");
- exitInsertMode(cm);
- }
- };
- }
CodeMirror.keyMap['vim-insert'] = {
// TODO: override navigation keys so that Esc will cancel automatic
// indentation from o, O, i_
- 'Esc': exitInsertMode,
- 'Ctrl-[': exitInsertMode,
- 'Ctrl-C': exitInsertMode,
'Ctrl-N': 'autocomplete',
'Ctrl-P': 'autocomplete',
'Enter': function(cm) {
@@ -6127,26 +5926,22 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
CodeMirror.commands.newlineAndIndent;
fn(cm);
},
- // The next few lines are where you'd add additional handlers if
- // you wanted to use keys other than i j and k for two-character
- // escape sequences. Don't forget to add them in the await-second
- // section as well.
- "'i'": firstEscCharacterHandler('i'),
- "'j'": firstEscCharacterHandler('j'),
- "'k'": firstEscCharacterHandler('k'),
- fallthrough: ['default']
+ fallthrough: ['default'],
+ attach: attachVimMap,
+ detach: detachVimMap
};
CodeMirror.keyMap['await-second'] = {
- "'i'": secondEscCharacterHandler('i'),
- "'j'": secondEscCharacterHandler('j'),
- "'k'": secondEscCharacterHandler('k'),
- fallthrough: ['vim-insert']
+ fallthrough: ['vim-insert'],
+ attach: attachVimMap,
+ detach: detachVimMap
};
CodeMirror.keyMap['vim-replace'] = {
'Backspace': 'goCharLeft',
- fallthrough: ['vim-insert']
+ fallthrough: ['vim-insert'],
+ attach: attachVimMap,
+ detach: detachVimMap
};
function executeMacroRegister(cm, vim, macroModeState, registerName) {
@@ -6164,7 +5959,7 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
match = (/<\w+-.+?>|<\w+>|./).exec(text);
key = match[0];
text = text.substring(match.index + key.length);
- CodeMirror.Vim.handleKey(cm, key);
+ CodeMirror.Vim.handleKey(cm, key, 'macro');
if (vim.insertMode) {
var changes = register.insertModeChanges[imc++].changes;
vimGlobalState.macroModeState.lastInsertModeChanges.changes =
@@ -6241,28 +6036,49 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
// Cursor moved outside the context of an edit. Reset the change.
lastChange.changes = [];
}
- } else if (cm.doc.history.lastSelOrigin == '*mouse') {
- // Reset lastHPos if mouse click was done in normal mode.
- vim.lastHPos = cm.doc.getCursor().ch;
- if (cm.somethingSelected()) {
- // If something is still selected, enter visual mode.
- vim.visualMode = true;
- }
+ } else if (!cm.curOp.isVimOp) {
+ handleExternalSelection(cm, vim);
}
if (vim.visualMode) {
- var from, head;
- from = head = cm.getCursor('head');
- var anchor = cm.getCursor('anchor');
- var to = Pos(head.line, from.ch + (cursorIsBefore(anchor, head) ? -1 : 1));
- if (cursorIsBefore(to, from)) {
- var temp = from;
- from = to;
- to = temp;
- }
- if (vim.fakeCursor) {
- vim.fakeCursor.clear();
- }
- vim.fakeCursor = cm.markText(from, to, {className: 'cm-animate-fat-cursor'});
+ updateFakeCursor(cm);
+ }
+ }
+ function updateFakeCursor(cm) {
+ var vim = cm.state.vim;
+ var from = copyCursor(vim.sel.head);
+ var to = offsetCursor(from, 0, 1);
+ if (vim.fakeCursor) {
+ vim.fakeCursor.clear();
+ }
+ vim.fakeCursor = cm.markText(from, to, {className: 'cm-animate-fat-cursor'});
+ }
+ function handleExternalSelection(cm, vim) {
+ var anchor = cm.getCursor('anchor');
+ var head = cm.getCursor('head');
+ // Enter or exit visual mode to match mouse selection.
+ if (vim.visualMode && cursorEqual(head, anchor) && lineLength(cm, head.line) > head.ch) {
+ exitVisualMode(cm, false);
+ } else if (!vim.visualMode && !vim.insertMode && cm.somethingSelected()) {
+ vim.visualMode = true;
+ vim.visualLine = false;
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
+ }
+ if (vim.visualMode) {
+ // Bind CodeMirror selection model to vim selection model.
+ // Mouse selections are considered visual characterwise.
+ var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0;
+ var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0;
+ head = offsetCursor(head, 0, headOffset);
+ anchor = offsetCursor(anchor, 0, anchorOffset);
+ vim.sel = {
+ anchor: anchor,
+ head: head
+ };
+ updateMark(cm, vim, '<', cursorMin(head, anchor));
+ updateMark(cm, vim, '>', cursorMax(head, anchor));
+ } else if (!vim.insertMode) {
+ // Reset lastHPos if selection was modified by something outside of vim mode e.g. by mouse.
+ vim.lastHPos = cm.getCursor().ch;
}
}
@@ -6285,7 +6101,7 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
return true;
}
if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
- CodeMirror.lookupKey(keyName, ['vim-insert'], onKeyFound);
+ CodeMirror.lookupKey(keyName, 'vim-insert', onKeyFound);
}
}
@@ -6354,32 +6170,33 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
}
return true;
}
- var curStart = cm.getCursor();
+ var head = cm.getCursor('head');
var inVisualBlock = vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock;
if (inVisualBlock) {
// Set up block selection again for repeating the changes.
var vim = cm.state.vim;
- var block = vim.lastSelection.visualBlock;
- var curEnd = Pos(curStart.line + block.height-1, curStart.ch);
- cm.setCursor(curStart);
- selectBlock(cm, curEnd);
+ var lastSel = vim.lastSelection;
+ var offset = getOffset(lastSel.anchor, lastSel.head);
+ selectForInsert(cm, head, offset.line + 1);
repeat = cm.listSelections().length;
- cm.setCursor(curStart);
+ cm.setCursor(head);
}
for (var i = 0; i < repeat; i++) {
+ if (inVisualBlock) {
+ cm.setCursor(offsetCursor(head, i, 0));
+ }
for (var j = 0; j < changes.length; j++) {
var change = changes[j];
if (change instanceof InsertModeKey) {
- CodeMirror.lookupKey(change.keyName, ['vim-insert'], keyHandler);
+ CodeMirror.lookupKey(change.keyName, 'vim-insert', keyHandler);
} else {
var cur = cm.getCursor();
cm.replaceRange(change, cur, cur);
}
}
- if (inVisualBlock) {
- curStart.line++;
- cm.setCursor(curStart);
- }
+ }
+ if (inVisualBlock) {
+ cm.setCursor(offsetCursor(head, 0, 1));
}
}
diff --git a/media/editors/codemirror/lib/addons.js b/media/editors/codemirror/lib/addons.js
index b8a2f6e274ef9..a04ffd1099cac 100644
--- a/media/editors/codemirror/lib/addons.js
+++ b/media/editors/codemirror/lib/addons.js
@@ -1 +1 @@
-(function(a){if(typeof exports=="object"&&typeof module=="object"){a(require("../../lib/codemirror"))}else{if(typeof define=="function"&&define.amd){define(["../../lib/codemirror"],a)}else{a(CodeMirror)}}})(function(a){a.defineOption("fullScreen",false,function(d,f,e){if(e==a.Init){e=false}if(!e==!f){return}if(f){b(d)}else{c(d)}});function b(d){var e=d.getWrapperElement();d.state.fullScreenRestore={scrollTop:window.pageYOffset,scrollLeft:window.pageXOffset,width:e.style.width,height:e.style.height};e.style.width="";e.style.height="auto";e.className+=" CodeMirror-fullscreen";document.documentElement.style.overflow="hidden";d.refresh()}function c(d){var e=d.getWrapperElement();e.className=e.className.replace(/\s*CodeMirror-fullscreen\b/,"");document.documentElement.style.overflow="";var f=d.state.fullScreenRestore;e.style.width=f.width;e.style.height=f.height;window.scrollTo(f.scrollLeft,f.scrollTop);d.refresh()}});(function(a){if(typeof exports=="object"&&typeof module=="object"){a(require("../../lib/codemirror"))}else{if(typeof define=="function"&&define.amd){define(["../../lib/codemirror"],a)}else{a(CodeMirror)}}})(function(c){var h="()[]{}''\"\"";var g="[]{}";var i=/\s/;var f=c.Pos;c.defineOption("autoCloseBrackets",false,function(j,o,k){if(k!=c.Init&&k){j.removeKeyMap("autoCloseBrackets")}if(!o){return}var m=h,l=g;if(typeof o=="string"){m=o}else{if(typeof o=="object"){if(o.pairs!=null){m=o.pairs}if(o.explode!=null){l=o.explode}}}var n=b(m);if(l){n.Enter=a(l)}j.addKeyMap(n)});function d(j,l){var k=j.getRange(f(l.line,l.ch-1),f(l.line,l.ch+1));return k.length==2?k:null}function e(j,p,n){var k=j.getLine(p.line);var m=j.getTokenAt(p);if(/\bstring2?\b/.test(m.type)){return false}var o=new c.StringStream(k.slice(0,p.ch)+n+k.slice(p.ch),4);o.pos=o.start=m.start;for(;;){var l=j.getMode().token(o,m.state);if(o.pos>=p.ch+1){return/\bstring2?\b/.test(l)}o.start=o.pos}}function b(l){var m={name:"autoCloseBrackets",Backspace:function(n){if(n.getOption("disableInput")){return c.Pass}var o=n.listSelections();for(var p=0;p=0;p--){var r=o[p].head;n.replaceRange("",f(r.line,r.ch-1),f(r.line,r.ch+1))}}};var k="";for(var j=0;j1&&p.getRange(f(w.line,w.ch-2),w)==o+o&&(w.ch<=2||p.getRange(f(w.line,w.ch-3),f(w.line,w.ch-2))!=o)){s="addFour"}else{if(o=='"'||o=="'"){if(!c.isWordChar(u)&&e(p,w,o)){s="both"}else{return c.Pass}}else{if(p.getLine(w.line).length==w.ch||k.indexOf(u)>=0||i.test(u)){s="both"}else{return c.Pass}}}}}if(!v){v=s}else{if(v!=s){return c.Pass}}}p.operation(function(){if(v=="skip"){p.execCommand("goCharRight")}else{if(v=="skipThree"){for(var y=0;y<3;y++){p.execCommand("goCharRight")}}else{if(v=="surround"){var x=p.getSelections();for(var y=0;y'"]=function(l){return a(l)}}h.addKeyMap(j)});var d=["area","base","br","col","command","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"];var c=["applet","blockquote","body","button","div","dl","fieldset","form","frameset","h1","h2","h3","h4","h5","h6","head","html","iframe","layer","legend","object","ol","p","select","table","ul"];function a(w){if(w.getOption("disableInput")){return b.Pass}var j=w.listSelections(),q=[];for(var r=0;rv.ch){p=p.slice(0,p.length-x.end+v.ch)}var t=p.toLowerCase();if(!p||x.type=="string"&&(x.end!=v.ch||!/[\"\']/.test(x.string.charAt(x.string.length-1))||x.string.length==1)||x.type=="tag"&&h.type=="closeTag"||x.string.indexOf("/")==(x.string.length-1)||m&&g(m,t)>-1||f(w,p,v,h,true)){return b.Pass}var o=u&&g(u,t)>-1;q[r]={indent:o,text:">"+(o?"\n\n":"")+""+p+">",newPos:o?b.Pos(v.line+1,0):b.Pos(v.line,v.ch+1)}}for(var r=j.length-1;r>=0;r--){var n=q[r];w.replaceRange(n.text,j[r].head,j[r].anchor,"+insert");var l=w.listSelections().slice(0);l[r]={head:n.newPos,anchor:n.newPos};w.setSelections(l);if(n.indent){w.indentLine(n.newPos.line,null,true);w.indentLine(n.newPos.line+1,null,true)}}}function e(h){if(h.getOption("disableInput")){return b.Pass}var j=h.listSelections(),n=[];for(var m=0;m"}else{if(h.getMode().name=="htmlmixed"&&k.mode.name=="css"){n[m]="/style>"}else{return b.Pass}}}else{if(!o.context||!o.context.tagName||f(h,o.context.tagName,p,o)){return b.Pass}n[m]="/"+o.context.tagName+">"}}h.replaceSelections(n);j=h.listSelections();for(var m=0;m",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"};function f(q,m,p,k){var s=q.getLineHandle(m.line),o=m.ch-1;var n=(o>=0&&a[s.text.charAt(o)])||a[s.text.charAt(++o)];if(!n){return null}var l=n.charAt(1)==">"?1:-1;if(p&&(l>0)!=(o==m.ch)){return null}var j=q.getTokenTypeAt(i(m.line,o+1));var r=g(q,i(m.line,o+(l>0?1:0)),l,j||null,k);if(r==null){return null}return{from:i(m.line,o),to:r&&r.pos,match:r&&r.ch==n.charAt(0),forward:l>0}}function g(w,r,n,k,m){var l=(m&&m.maxScanLineLength)||10000;var t=(m&&m.maxScanLines)||1000;var v=[];var x=m&&m.bracketRegex?m.bracketRegex:/[(){}[\]]/;var q=n>0?Math.min(r.line+t,w.lastLine()+1):Math.max(w.firstLine()-1,r.line-t);for(var o=r.line;o!=q;o+=n){var y=w.getLine(o);if(!y){continue}var u=n>0?0:y.length-1,p=n>0?y.length:-1;if(y.length>l){continue}if(o==r.line){u=r.ch-(n<0?1:0)}for(;u!=p;u+=n){var j=y.charAt(u);if(x.test(j)&&(k===undefined||w.getTokenTypeAt(i(o,u+1))==k)){var s=a[j];if((s.charAt(1)==">")==(n>0)){v.push(j)}else{if(!v.length){return{pos:i(o,u),ch:j}}else{v.pop()}}}}}return o-n==(n>0?w.lastLine():w.firstLine())?false:null}function b(s,n,m){var k=s.state.matchBrackets.maxHighlightLineLength||1000;var r=[],l=s.listSelections();for(var o=0;ob.lastLine()){return null}var o=b.getTokenAt(a.Pos(k,1));if(!/\S/.test(o.string)){o=b.getTokenAt(a.Pos(k,o.end+1))}if(o.type!="keyword"||o.string!="import"){return null}for(var l=k,m=Math.min(b.lastLine(),k+10);l<=m;++l){var n=b.getLine(l),j=n.indexOf(";");if(j!=-1){return{startCh:o.end,end:a.Pos(l,j)}}}}var h=h.line,d=g(h),f;if(!d||g(h-1)||((f=g(h-2))&&f.end.line==h-1)){return null}for(var c=d.end;;){var e=g(c.line+1);if(e==null){break}c=e.end}return{from:b.clipPos(a.Pos(h,d.startCh+1)),to:c}});a.registerHelper("fold","include",function(b,g){function f(h){if(hb.lastLine()){return null}var i=b.getTokenAt(a.Pos(h,1));if(!/\S/.test(i.string)){i=b.getTokenAt(a.Pos(h,i.end+1))}if(i.type=="meta"&&i.string.slice(0,8)=="#include"){return i.start+8}}var g=g.line,d=f(g);if(d==null||f(g-1)!=null){return null}for(var c=g;;){var e=f(c+1);if(e==null){break}++c}return{from:a.Pos(g,d+1),to:b.clipPos(a.Pos(c))}})});(function(a){if(typeof exports=="object"&&typeof module=="object"){a(require("../../lib/codemirror"))}else{if(typeof define=="function"&&define.amd){define(["../../lib/codemirror"],a)}else{a(CodeMirror)}}})(function(b){function d(n,m,o,i){if(o&&o.call){var g=o;o=null}else{var g=c(n,o,"rangeFinder")}if(typeof m=="number"){m=b.Pos(m,0)}var h=c(n,o,"minFoldSize");function f(p){var q=g(n,m);if(!q||q.to.line-q.from.linen.firstLine()){m=b.Pos(m.line-1,0);k=f(false)}}if(!k||k.cleared||i==="unfold"){return}var l=e(n,o);b.on(l,"mousedown",function(p){j.clear();b.e_preventDefault(p)});var j=n.markText(k.from,k.to,{replacedWith:l,clearOnEnter:true,__isFold:true});j.on("clear",function(q,p){b.signal(n,"unfold",n,q,p)});b.signal(n,"fold",n,k.from,k.to)}function e(f,g){var h=c(f,g,"widget");if(typeof h=="string"){var i=document.createTextNode(h);h=document.createElement("span");h.appendChild(i);h.className="CodeMirror-foldmarker"}return h}b.newFoldFunction=function(g,f){return function(h,i){d(h,i,{rangeFinder:g,widget:f})}};b.defineExtension("foldCode",function(h,f,g){d(this,h,f,g)});b.defineExtension("isFolded",function(h){var g=this.findMarksAt(h);for(var f=0;f20||o.from-p.to>20){b(m)}else{m.operation(function(){if(p.fromo.to){a(m,o.to,p.to);o.to=p.to}})}},n.updateViewportTimeSpan||400)}function e(m,p){var o=m.state.foldGutter,n=p.line;if(n>=o.from&&n=q.max){return}q.ch=0;q.text=q.cm.getLine(++q.line);return true}function n(q){if(q.line<=q.min){return}q.text=q.cm.getLine(--q.line);q.ch=q.text.length;return true}function g(s){for(;;){var r=s.text.indexOf(">",s.ch);if(r==-1){if(a(s)){continue}else{return}}if(!h(s,r+1)){s.ch=r+1;continue}var q=s.text.lastIndexOf("/",r);var t=q>-1&&!/\S/.test(s.text.slice(q+1,r));s.ch=r+1;return t?"selfClose":"regular"}}function k(r){for(;;){var q=r.ch?r.text.lastIndexOf("<",r.ch-1):-1;if(q==-1){if(n(r)){continue}else{return}}if(!h(r,q+1)){r.ch=q;continue}d.lastIndex=q;r.ch=q;var s=d.exec(r.text);if(s&&s.index==q){return s}}}function p(q){for(;;){d.lastIndex=q.ch;var r=d.exec(q.text);if(!r){if(a(q)){continue}else{return}}if(!h(q,r.index+1)){q.ch=r.index+1;continue}q.ch=r.index+r[0].length;return r}}function e(s){for(;;){var r=s.ch?s.text.lastIndexOf(">",s.ch-1):-1;if(r==-1){if(n(s)){continue}else{return}}if(!h(s,r+1)){s.ch=r;continue}var q=s.text.lastIndexOf("/",r);var t=q>-1&&!/\S/.test(s.text.slice(q+1,r));s.ch=r+1;return t?"selfClose":"regular"}}function f(t,r){var q=[];for(;;){var v=p(t),s,x=t.line,w=t.ch-(v?v[0].length:0);if(!v||!(s=g(t))){return}if(s=="selfClose"){continue}if(v[1]){for(var u=q.length-1;u>=0;--u){if(q[u]==v[2]){q.length=u;break}}if(u<0&&(!r||r==v[2])){return{tag:v[2],from:m(x,w),to:m(t.line,t.ch)}}}else{q.push(v[2])}}}function c(s,r){var q=[];for(;;){var w=e(s);if(!w){return}if(w=="selfClose"){k(s);continue}var v=s.line,u=s.ch;var x=k(s);if(!x){return}if(x[1]){q.push(x[2])}else{for(var t=q.length-1;t>=0;--t){if(q[t]==x[2]){q.length=t;break}}if(t<0&&(!r||r==x[2])){return{tag:x[2],from:m(s.line,s.ch),to:m(v,u)}}}}}i.registerHelper("fold","xml",function(q,v){var s=new b(q,v.line,0);for(;;){var t=p(s),r;if(!t||s.line!=v.line||!(r=g(s))){return}if(!t[1]&&r!="selfClose"){var v=m(s.line,s.ch);var u=f(s,t[2]);return u&&{from:v,to:u.from}}}});i.findMatchingTag=function(q,x,t){var s=new b(q,x.line,x.ch,t);if(s.text.indexOf(">")==-1&&s.text.indexOf("<")==-1){return}var r=g(s),w=r&&m(s.line,s.ch);var v=r&&k(s);if(!r||!v||l(s,x)>0){return}var u={from:m(s.line,s.ch),to:w,tag:v[2]};if(r=="selfClose"){return{open:u,close:null,at:"open"}}if(v[1]){return{open:c(s,v[2]),close:u,at:"close"}}else{s=new b(q,w.line,w.ch,t);return{open:u,close:f(s,v[2]),at:"open"}}};i.findEnclosingTag=function(q,w,s){var r=new b(q,w.line,w.ch,s);for(;;){var u=c(r);if(!u){break}var t=new b(q,w.line,w.ch,s);var v=f(t,u.tag);if(v){return{open:u,close:v}}}};i.scanForClosingTag=function(q,u,t,s){var r=new b(q,u.line,u.ch,s?{from:0,to:s}:null);return f(r,t)}});(function(a){if(typeof exports=="object"&&typeof module=="object"){a(require("../../lib/codemirror"))}else{if(typeof define=="function"&&define.amd){define(["../../lib/codemirror"],a)}else{a(CodeMirror)}}})(function(a){if(!a.modeURL){a.modeURL="../mode/%N/%N.js"}var d={};function c(e,g){var f=g;return function(){if(--f==0){e()}}}function b(k,e){var j=a.modes[k].dependencies;if(!j){return e()}var h=[];for(var g=0;g100){return clearInterval(j)}if(a.modes.hasOwnProperty(k)){clearInterval(j);d[k]=null;b(k,function(){for(var l=0;l-1){o.string=m.slice(0,p)}var n=k.mode.token(o,f.inner);if(p>-1){o.string=m}if(k.innerStyle){if(n){n=n+" "+k.innerStyle}else{n=k.innerStyle}}return n}},indent:function(g,f){var h=g.innerActive?g.innerActive.mode:c;if(!h.indent){return a.Pass}return h.indent(g.innerActive?g.inner:g.outer,f)},blankLine:function(h){var j=h.innerActive?h.innerActive.mode:c;if(j.blankLine){j.blankLine(h.innerActive?h.inner:h.outer)}if(!h.innerActive){for(var g=0;g"],type:"keyToKey",toKeys:["h"]},{keys:[""],type:"keyToKey",toKeys:["l"]},{keys:[""],type:"keyToKey",toKeys:["k"]},{keys:[""],type:"keyToKey",toKeys:["j"]},{keys:[""],type:"keyToKey",toKeys:["l"]},{keys:[""],type:"keyToKey",toKeys:["h"]},{keys:[""],type:"keyToKey",toKeys:["W"]},{keys:[""],type:"keyToKey",toKeys:["B"]},{keys:[""],type:"keyToKey",toKeys:["w"]},{keys:[""],type:"keyToKey",toKeys:["b"]},{keys:[""],type:"keyToKey",toKeys:["j"]},{keys:[""],type:"keyToKey",toKeys:["k"]},{keys:[""],type:"keyToKey",toKeys:[""]},{keys:[""],type:"keyToKey",toKeys:[""]},{keys:["s"],type:"keyToKey",toKeys:["c","l"],context:"normal"},{keys:["s"],type:"keyToKey",toKeys:["x","i"],context:"visual"},{keys:["S"],type:"keyToKey",toKeys:["c","c"],context:"normal"},{keys:["S"],type:"keyToKey",toKeys:["d","c","c"],context:"visual"},{keys:[""],type:"keyToKey",toKeys:["0"]},{keys:[""],type:"keyToKey",toKeys:["$"]},{keys:[""],type:"keyToKey",toKeys:[""]},{keys:[""],type:"keyToKey",toKeys:[""]},{keys:[""],type:"keyToKey",toKeys:["j","^"],context:"normal"},{keys:["H"],type:"motion",motion:"moveToTopLine",motionArgs:{linewise:true,toJumplist:true}},{keys:["M"],type:"motion",motion:"moveToMiddleLine",motionArgs:{linewise:true,toJumplist:true}},{keys:["L"],type:"motion",motion:"moveToBottomLine",motionArgs:{linewise:true,toJumplist:true}},{keys:["h"],type:"motion",motion:"moveByCharacters",motionArgs:{forward:false}},{keys:["l"],type:"motion",motion:"moveByCharacters",motionArgs:{forward:true}},{keys:["j"],type:"motion",motion:"moveByLines",motionArgs:{forward:true,linewise:true}},{keys:["k"],type:"motion",motion:"moveByLines",motionArgs:{forward:false,linewise:true}},{keys:["g","j"],type:"motion",motion:"moveByDisplayLines",motionArgs:{forward:true}},{keys:["g","k"],type:"motion",motion:"moveByDisplayLines",motionArgs:{forward:false}},{keys:["w"],type:"motion",motion:"moveByWords",motionArgs:{forward:true,wordEnd:false}},{keys:["W"],type:"motion",motion:"moveByWords",motionArgs:{forward:true,wordEnd:false,bigWord:true}},{keys:["e"],type:"motion",motion:"moveByWords",motionArgs:{forward:true,wordEnd:true,inclusive:true}},{keys:["E"],type:"motion",motion:"moveByWords",motionArgs:{forward:true,wordEnd:true,bigWord:true,inclusive:true}},{keys:["b"],type:"motion",motion:"moveByWords",motionArgs:{forward:false,wordEnd:false}},{keys:["B"],type:"motion",motion:"moveByWords",motionArgs:{forward:false,wordEnd:false,bigWord:true}},{keys:["g","e"],type:"motion",motion:"moveByWords",motionArgs:{forward:false,wordEnd:true,inclusive:true}},{keys:["g","E"],type:"motion",motion:"moveByWords",motionArgs:{forward:false,wordEnd:true,bigWord:true,inclusive:true}},{keys:["{"],type:"motion",motion:"moveByParagraph",motionArgs:{forward:false,toJumplist:true}},{keys:["}"],type:"motion",motion:"moveByParagraph",motionArgs:{forward:true,toJumplist:true}},{keys:[""],type:"motion",motion:"moveByPage",motionArgs:{forward:true}},{keys:[""],type:"motion",motion:"moveByPage",motionArgs:{forward:false}},{keys:[""],type:"motion",motion:"moveByScroll",motionArgs:{forward:true,explicitRepeat:true}},{keys:[""],type:"motion",motion:"moveByScroll",motionArgs:{forward:false,explicitRepeat:true}},{keys:["g","g"],type:"motion",motion:"moveToLineOrEdgeOfDocument",motionArgs:{forward:false,explicitRepeat:true,linewise:true,toJumplist:true}},{keys:["G"],type:"motion",motion:"moveToLineOrEdgeOfDocument",motionArgs:{forward:true,explicitRepeat:true,linewise:true,toJumplist:true}},{keys:["0"],type:"motion",motion:"moveToStartOfLine"},{keys:["^"],type:"motion",motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:["+"],type:"motion",motion:"moveByLines",motionArgs:{forward:true,toFirstChar:true}},{keys:["-"],type:"motion",motion:"moveByLines",motionArgs:{forward:false,toFirstChar:true}},{keys:["_"],type:"motion",motion:"moveByLines",motionArgs:{forward:true,toFirstChar:true,repeatOffset:-1}},{keys:["$"],type:"motion",motion:"moveToEol",motionArgs:{inclusive:true}},{keys:["%"],type:"motion",motion:"moveToMatchedSymbol",motionArgs:{inclusive:true,toJumplist:true}},{keys:["f","character"],type:"motion",motion:"moveToCharacter",motionArgs:{forward:true,inclusive:true}},{keys:["F","character"],type:"motion",motion:"moveToCharacter",motionArgs:{forward:false}},{keys:["t","character"],type:"motion",motion:"moveTillCharacter",motionArgs:{forward:true,inclusive:true}},{keys:["T","character"],type:"motion",motion:"moveTillCharacter",motionArgs:{forward:false}},{keys:[";"],type:"motion",motion:"repeatLastCharacterSearch",motionArgs:{forward:true}},{keys:[","],type:"motion",motion:"repeatLastCharacterSearch",motionArgs:{forward:false}},{keys:["'","character"],type:"motion",motion:"goToMark",motionArgs:{toJumplist:true,linewise:true}},{keys:["`","character"],type:"motion",motion:"goToMark",motionArgs:{toJumplist:true}},{keys:["]","`"],type:"motion",motion:"jumpToMark",motionArgs:{forward:true}},{keys:["[","`"],type:"motion",motion:"jumpToMark",motionArgs:{forward:false}},{keys:["]","'"],type:"motion",motion:"jumpToMark",motionArgs:{forward:true,linewise:true}},{keys:["[","'"],type:"motion",motion:"jumpToMark",motionArgs:{forward:false,linewise:true}},{keys:["]","p"],type:"action",action:"paste",isEdit:true,actionArgs:{after:true,isEdit:true,matchIndent:true}},{keys:["[","p"],type:"action",action:"paste",isEdit:true,actionArgs:{after:false,isEdit:true,matchIndent:true}},{keys:["]","character"],type:"motion",motion:"moveToSymbol",motionArgs:{forward:true,toJumplist:true}},{keys:["[","character"],type:"motion",motion:"moveToSymbol",motionArgs:{forward:false,toJumplist:true}},{keys:["|"],type:"motion",motion:"moveToColumn",motionArgs:{}},{keys:["o"],type:"motion",motion:"moveToOtherHighlightedEnd",motionArgs:{},context:"visual"},{keys:["O"],type:"motion",motion:"moveToOtherHighlightedEnd",motionArgs:{sameLine:true},context:"visual"},{keys:["d"],type:"operator",operator:"delete"},{keys:["y"],type:"operator",operator:"yank"},{keys:["c"],type:"operator",operator:"change"},{keys:[">"],type:"operator",operator:"indent",operatorArgs:{indentRight:true}},{keys:["<"],type:"operator",operator:"indent",operatorArgs:{indentRight:false}},{keys:["g","~"],type:"operator",operator:"swapcase"},{keys:["n"],type:"motion",motion:"findNext",motionArgs:{forward:true,toJumplist:true}},{keys:["N"],type:"motion",motion:"findNext",motionArgs:{forward:false,toJumplist:true}},{keys:["x"],type:"operatorMotion",operator:"delete",motion:"moveByCharacters",motionArgs:{forward:true},operatorMotionArgs:{visualLine:false}},{keys:["X"],type:"operatorMotion",operator:"delete",motion:"moveByCharacters",motionArgs:{forward:false},operatorMotionArgs:{visualLine:true}},{keys:["D"],type:"operatorMotion",operator:"delete",motion:"moveToEol",motionArgs:{inclusive:true},operatorMotionArgs:{visualLine:true}},{keys:["Y"],type:"operatorMotion",operator:"yank",motion:"moveToEol",motionArgs:{inclusive:true},operatorMotionArgs:{visualLine:true}},{keys:["C"],type:"operatorMotion",operator:"change",motion:"moveToEol",motionArgs:{inclusive:true},operatorMotionArgs:{visualLine:true}},{keys:["~"],type:"operatorMotion",operator:"swapcase",operatorArgs:{shouldMoveCursor:true},motion:"moveByCharacters",motionArgs:{forward:true}},{keys:[""],type:"action",action:"jumpListWalk",actionArgs:{forward:true}},{keys:[""],type:"action",action:"jumpListWalk",actionArgs:{forward:false}},{keys:["