2 var DEFAULT_BRACKETS = "()[]{}''\"\"";
3 var DEFAULT_EXPLODE_ON_ENTER = "[]{}";
4 var SPACE_CHAR_REGEX = /\s/;
6 CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) {
7 if (old != CodeMirror.Init && old)
8 cm.removeKeyMap("autoCloseBrackets");
10 var pairs = DEFAULT_BRACKETS, explode = DEFAULT_EXPLODE_ON_ENTER;
11 if (typeof val == "string") pairs = val;
12 else if (typeof val == "object") {
13 if (val.pairs != null) pairs = val.pairs;
14 if (val.explode != null) explode = val.explode;
16 var map = buildKeymap(pairs);
17 if (explode) map.Enter = buildExplodeHandler(explode);
21 function charsAround(cm, pos) {
22 var str = cm.getRange(CodeMirror.Pos(pos.line, pos.ch - 1),
23 CodeMirror.Pos(pos.line, pos.ch + 1));
24 return str.length == 2 ? str : null;
27 function buildKeymap(pairs) {
29 name : "autoCloseBrackets",
30 Backspace: function(cm) {
31 if (cm.somethingSelected()) return CodeMirror.Pass;
32 var cur = cm.getCursor(), around = charsAround(cm, cur);
33 if (around && pairs.indexOf(around) % 2 == 0)
34 cm.replaceRange("", CodeMirror.Pos(cur.line, cur.ch - 1), CodeMirror.Pos(cur.line, cur.ch + 1));
36 return CodeMirror.Pass;
39 var closingBrackets = "";
40 for (var i = 0; i < pairs.length; i += 2) (function(left, right) {
41 if (left != right) closingBrackets += right;
42 function surround(cm) {
43 var selection = cm.getSelection();
44 cm.replaceSelection(left + selection + right);
46 function maybeOverwrite(cm) {
47 var cur = cm.getCursor(), ahead = cm.getRange(cur, CodeMirror.Pos(cur.line, cur.ch + 1));
48 if (ahead != right || cm.somethingSelected()) return CodeMirror.Pass;
49 else cm.execCommand("goCharRight");
51 map["'" + left + "'"] = function(cm) {
52 if (left == "'" && cm.getTokenAt(cm.getCursor()).type == "comment")
53 return CodeMirror.Pass;
54 if (cm.somethingSelected()) return surround(cm);
55 if (left == right && maybeOverwrite(cm) != CodeMirror.Pass) return;
56 var cur = cm.getCursor(), ahead = CodeMirror.Pos(cur.line, cur.ch + 1);
57 var line = cm.getLine(cur.line), nextChar = line.charAt(cur.ch), curChar = cur.ch > 0 ? line.charAt(cur.ch - 1) : "";
58 if (left == right && CodeMirror.isWordChar(curChar))
59 return CodeMirror.Pass;
60 if (line.length == cur.ch || closingBrackets.indexOf(nextChar) >= 0 || SPACE_CHAR_REGEX.test(nextChar))
61 cm.replaceSelection(left + right, {head: ahead, anchor: ahead});
63 return CodeMirror.Pass;
65 if (left != right) map["'" + right + "'"] = maybeOverwrite;
66 })(pairs.charAt(i), pairs.charAt(i + 1));
70 function buildExplodeHandler(pairs) {
72 var cur = cm.getCursor(), around = charsAround(cm, cur);
73 if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass;
74 cm.operation(function() {
75 var newPos = CodeMirror.Pos(cur.line + 1, 0);
76 cm.replaceSelection("\n\n", {anchor: newPos, head: newPos}, "+input");
77 cm.indentLine(cur.line + 1, null, true);
78 cm.indentLine(cur.line + 2, null, true);