closebrackets.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. (function() {
  2. var DEFAULT_BRACKETS = "()[]{}''\"\"";
  3. var SPACE_CHAR_REGEX = /\s/;
  4. CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) {
  5. var wasOn = old && old != CodeMirror.Init;
  6. if (val && !wasOn)
  7. cm.addKeyMap(buildKeymap(typeof val == "string" ? val : DEFAULT_BRACKETS));
  8. else if (!val && wasOn)
  9. cm.removeKeyMap("autoCloseBrackets");
  10. });
  11. function buildKeymap(pairs) {
  12. var map = {
  13. name : "autoCloseBrackets",
  14. Backspace: function(cm) {
  15. if (cm.somethingSelected()) return CodeMirror.Pass;
  16. var cur = cm.getCursor(), line = cm.getLine(cur.line);
  17. if (cur.ch && cur.ch < line.length &&
  18. pairs.indexOf(line.slice(cur.ch - 1, cur.ch + 1)) % 2 == 0)
  19. cm.replaceRange("", CodeMirror.Pos(cur.line, cur.ch - 1), CodeMirror.Pos(cur.line, cur.ch + 1));
  20. else
  21. return CodeMirror.Pass;
  22. }
  23. };
  24. var closingBrackets = [];
  25. for (var i = 0; i < pairs.length; i += 2) (function(left, right) {
  26. if (left != right) closingBrackets.push(right);
  27. function surround(cm) {
  28. var selection = cm.getSelection();
  29. cm.replaceSelection(left + selection + right);
  30. }
  31. function maybeOverwrite(cm) {
  32. var cur = cm.getCursor(), ahead = cm.getRange(cur, CodeMirror.Pos(cur.line, cur.ch + 1));
  33. if (ahead != right || cm.somethingSelected()) return CodeMirror.Pass;
  34. else cm.execCommand("goCharRight");
  35. }
  36. map["'" + left + "'"] = function(cm) {
  37. if (cm.somethingSelected()) return surround(cm);
  38. if (left == right && maybeOverwrite(cm) != CodeMirror.Pass) return;
  39. var cur = cm.getCursor(), ahead = CodeMirror.Pos(cur.line, cur.ch + 1);
  40. var line = cm.getLine(cur.line), nextChar = line.charAt(cur.ch);
  41. if (line.length == cur.ch || closingBrackets.indexOf(nextChar) >= 0 || SPACE_CHAR_REGEX.test(nextChar))
  42. cm.replaceSelection(left + right, {head: ahead, anchor: ahead});
  43. else
  44. return CodeMirror.Pass;
  45. };
  46. if (left != right) map["'" + right + "'"] = maybeOverwrite;
  47. })(pairs.charAt(i), pairs.charAt(i + 1));
  48. return map;
  49. }
  50. })();