closebrackets.html 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>CodeMirror: Closebrackets Demo</title>
  6. <link rel="stylesheet" href="../lib/codemirror.css">
  7. <script src="../lib/codemirror.js"></script>
  8. <script src="../addon/edit/closebrackets.js"></script>
  9. <script src="../mode/javascript/javascript.js"></script>
  10. <link rel="stylesheet" href="../doc/docs.css">
  11. <style type="text/css">
  12. .CodeMirror {border-top: 1px solid #888; border-bottom: 1px solid #888;}
  13. </style>
  14. </head>
  15. <body>
  16. <h1>CodeMirror: Closebrackets Demo</h1>
  17. <p>Type a bracket like '[', '(', '{', '&quot;', or '''
  18. and <a href="../doc/manual.html#addon_closebrackets">the addon</a>
  19. will auto-close it. Type the closing variant when directly in
  20. front of a matching character and it will overwrite it.</p>
  21. <p>If you backspace over a starting bracket while inside empty brackets
  22. (e.g. <code>{|}</code>), it will delete the closing bracket for you.</p>
  23. <form><textarea id="code" name="code">(function() {
  24. var DEFAULT_BRACKETS = "()[]{}''\"\"";
  25. CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) {
  26. var wasOn = old && old != CodeMirror.Init;
  27. if (val && !wasOn)
  28. cm.addKeyMap(buildKeymap(typeof val == "string" ? val : DEFAULT_BRACKETS));
  29. else if (!val && wasOn)
  30. cm.removeKeyMap("autoCloseBrackets");
  31. });
  32. function buildKeymap(pairs) {
  33. var map = {name : "autoCloseBrackets"};
  34. for (var i = 0; i < pairs.length; i += 2) (function(left, right) {
  35. function maybeOverwrite(cm) {
  36. var cur = cm.getCursor(), ahead = cm.getRange(cur, CodeMirror.Pos(cur.line, cur.ch + 1));
  37. if (ahead != right) return CodeMirror.Pass;
  38. else cm.execCommand("goCharRight");
  39. }
  40. map["'" + left + "'"] = function(cm) {
  41. if (left == right && maybeOverwrite(cm) != CodeMirror.Pass) return;
  42. var cur = cm.getCursor(), ahead = CodeMirror.Pos(cur.line, cur.ch + 1);
  43. cm.replaceSelection(left + right, {head: ahead, anchor: ahead});
  44. };
  45. if (left != right) map["'" + right + "'"] = maybeOverwrite;
  46. })(pairs.charAt(i), pairs.charAt(i + 1));
  47. return map;
  48. }
  49. })();
  50. </textarea></form>
  51. <script type="text/javascript">
  52. var editor = CodeMirror.fromTextArea(document.getElementById("code"), {autoCloseBrackets: true});
  53. </script>
  54. </body>
  55. </html>