continuecomment.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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") 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) {
  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) {
  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. CodeMirror.defineOption("continueComments", null, function(cm, val, prev) {
  42. if (prev && prev != CodeMirror.Init)
  43. cm.removeKeyMap("continueComment");
  44. if (val) {
  45. var map = {name: "continueComment"};
  46. map[typeof val == "string" ? val : "Enter"] = continueComment;
  47. cm.addKeyMap(map);
  48. }
  49. });
  50. })();