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