closebrackets.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 += 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 (left == "'" && cm.getTokenAt(cm.getCursor()).type == "comment")
  38. return CodeMirror.Pass;
  39. if (cm.somethingSelected()) return surround(cm);
  40. if (left == right && maybeOverwrite(cm) != CodeMirror.Pass) return;
  41. var cur = cm.getCursor(), ahead = CodeMirror.Pos(cur.line, cur.ch + 1);
  42. var line = cm.getLine(cur.line), nextChar = line.charAt(cur.ch);
  43. if (line.length == cur.ch || closingBrackets.indexOf(nextChar) >= 0 || SPACE_CHAR_REGEX.test(nextChar))
  44. cm.replaceSelection(left + right, {head: ahead, anchor: ahead});
  45. else
  46. return CodeMirror.Pass;
  47. };
  48. if (left != right) map["'" + right + "'"] = maybeOverwrite;
  49. })(pairs.charAt(i), pairs.charAt(i + 1));
  50. return map;
  51. }
  52. })();