continuecomment.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. (function() {
  2. var modes = ["clike", "css", "javascript"];
  3. for (var i = 0; i < modes.length; ++i)
  4. CodeMirror.extendMode(modes[i], {blockCommentContinue: " * "});
  5. function continueComment(cm) {
  6. var pos = cm.getCursor(), token = cm.getTokenAt(pos);
  7. if (token.type != "comment" || cm.getOption("disableInput")) return CodeMirror.Pass;
  8. var mode = CodeMirror.innerMode(cm.getMode(), token.state).mode;
  9. var insert;
  10. if (mode.blockCommentStart && mode.blockCommentContinue) {
  11. var end = token.string.indexOf(mode.blockCommentEnd);
  12. var full = cm.getRange(CodeMirror.Pos(pos.line, 0), CodeMirror.Pos(pos.line, token.end)), found;
  13. if (end != -1 && end == token.string.length - mode.blockCommentEnd.length && pos.ch >= end) {
  14. // Comment ended, don't continue it
  15. } else if (token.string.indexOf(mode.blockCommentStart) == 0) {
  16. insert = full.slice(0, token.start);
  17. if (!/^\s*$/.test(insert)) {
  18. insert = "";
  19. for (var i = 0; i < token.start; ++i) insert += " ";
  20. }
  21. } else if ((found = full.indexOf(mode.blockCommentContinue)) != -1 &&
  22. found + mode.blockCommentContinue.length > token.start &&
  23. /^\s*$/.test(full.slice(0, found))) {
  24. insert = full.slice(0, found);
  25. }
  26. if (insert != null) insert += mode.blockCommentContinue;
  27. }
  28. if (insert == null && mode.lineComment && continueLineCommentEnabled(cm)) {
  29. var line = cm.getLine(pos.line), found = line.indexOf(mode.lineComment);
  30. if (found > -1) {
  31. insert = line.slice(0, found);
  32. if (/\S/.test(insert)) insert = null;
  33. else insert += mode.lineComment + line.slice(found + mode.lineComment.length).match(/^\s*/)[0];
  34. }
  35. }
  36. if (insert != null)
  37. cm.replaceSelection("\n" + insert, "end");
  38. else
  39. return CodeMirror.Pass;
  40. }
  41. function continueLineCommentEnabled(cm) {
  42. var opt = cm.getOption("continueComments");
  43. if (opt && typeof opt == "object")
  44. return opt.continueLineComment !== false;
  45. return true;
  46. }
  47. CodeMirror.defineOption("continueComments", null, function(cm, val, prev) {
  48. if (prev && prev != CodeMirror.Init)
  49. cm.removeKeyMap("continueComment");
  50. if (val) {
  51. var key = "Enter";
  52. if (typeof val == "string")
  53. key = val;
  54. else if (typeof val == "object" && val.key)
  55. key = val.key;
  56. var map = {name: "continueComment"};
  57. map[key] = continueComment;
  58. cm.addKeyMap(map);
  59. }
  60. });
  61. })();