active-line.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. // Because sometimes you need to style the cursor's line.
  4. //
  5. // Adds an option 'styleActiveLine' which, when enabled, gives the
  6. // active line's wrapping <div> the CSS class "CodeMirror-activeline",
  7. // and gives its background <div> the class "CodeMirror-activeline-background".
  8. (function(mod) {
  9. if (typeof exports == "object" && typeof module == "object") // CommonJS
  10. mod(require("../../lib/codemirror"));
  11. else if (typeof define == "function" && define.amd) // AMD
  12. define(["../../lib/codemirror"], mod);
  13. else // Plain browser env
  14. mod(CodeMirror);
  15. })(function(CodeMirror) {
  16. "use strict";
  17. var WRAP_CLASS = "CodeMirror-activeline";
  18. var BACK_CLASS = "CodeMirror-activeline-background";
  19. CodeMirror.defineOption("styleActiveLine", false, function(cm, val, old) {
  20. var prev = old && old != CodeMirror.Init;
  21. if (val && !prev) {
  22. cm.state.activeLines = [];
  23. updateActiveLines(cm, cm.listSelections());
  24. cm.on("beforeSelectionChange", selectionChange);
  25. } else if (!val && prev) {
  26. cm.off("beforeSelectionChange", selectionChange);
  27. clearActiveLines(cm);
  28. delete cm.state.activeLines;
  29. }
  30. });
  31. function clearActiveLines(cm) {
  32. for (var i = 0; i < cm.state.activeLines.length; i++) {
  33. cm.removeLineClass(cm.state.activeLines[i], "wrap", WRAP_CLASS);
  34. cm.removeLineClass(cm.state.activeLines[i], "background", BACK_CLASS);
  35. }
  36. }
  37. function sameArray(a, b) {
  38. if (a.length != b.length) return false;
  39. for (var i = 0; i < a.length; i++)
  40. if (a[i] != b[i]) return false;
  41. return true;
  42. }
  43. function updateActiveLines(cm, ranges) {
  44. var active = [];
  45. for (var i = 0; i < ranges.length; i++) {
  46. var range = ranges[i];
  47. if (!range.empty()) continue;
  48. var line = cm.getLineHandleVisualStart(range.head.line);
  49. if (active[active.length - 1] != line) active.push(line);
  50. }
  51. if (sameArray(cm.state.activeLines, active)) return;
  52. cm.operation(function() {
  53. clearActiveLines(cm);
  54. for (var i = 0; i < active.length; i++) {
  55. cm.addLineClass(active[i], "wrap", WRAP_CLASS);
  56. cm.addLineClass(active[i], "background", BACK_CLASS);
  57. }
  58. cm.state.activeLines = active;
  59. });
  60. }
  61. function selectionChange(cm, sel) {
  62. updateActiveLines(cm, sel.ranges);
  63. }
  64. });