##// END OF EJS Templates
updated codemirror to 2.34
marcink -
r2861:f034e6a1 beta
parent child Browse files
Show More
@@ -1,168 +1,173
1 .CodeMirror {
1 .CodeMirror {
2 line-height: 1em;
2 line-height: 1em;
3 font-family: monospace;
3 font-family: monospace;
4
4
5 /* Necessary so the scrollbar can be absolutely positioned within the wrapper on Lion. */
5 /* Necessary so the scrollbar can be absolutely positioned within the wrapper on Lion. */
6 position: relative;
6 position: relative;
7 /* This prevents unwanted scrollbars from showing up on the body and wrapper in IE. */
7 /* This prevents unwanted scrollbars from showing up on the body and wrapper in IE. */
8 overflow: hidden;
8 overflow: hidden;
9 }
9 }
10
10
11 .CodeMirror-scroll {
11 .CodeMirror-scroll {
12 overflow-x: auto;
12 overflow: auto;
13 overflow-y: hidden;
14 height: 300px;
13 height: 300px;
15 /* This is needed to prevent an IE[67] bug where the scrolled content
14 /* This is needed to prevent an IE[67] bug where the scrolled content
16 is visible outside of the scrolling box. */
15 is visible outside of the scrolling box. */
17 position: relative;
16 position: relative;
18 outline: none;
17 outline: none;
19 }
18 }
20
19
21 /* Vertical scrollbar */
20 /* Vertical scrollbar */
22 .CodeMirror-scrollbar {
21 .CodeMirror-scrollbar {
23 float: right;
22 position: absolute;
23 right: 0; top: 0;
24 overflow-x: hidden;
24 overflow-x: hidden;
25 overflow-y: scroll;
25 overflow-y: scroll;
26
26 z-index: 5;
27 /* This corrects for the 1px gap introduced to the left of the scrollbar
28 by the rule for .CodeMirror-scrollbar-inner. */
29 margin-left: -1px;
30 }
27 }
31 .CodeMirror-scrollbar-inner {
28 .CodeMirror-scrollbar-inner {
32 /* This needs to have a nonzero width in order for the scrollbar to appear
29 /* This needs to have a nonzero width in order for the scrollbar to appear
33 in Firefox and IE9. */
30 in Firefox and IE9. */
34 width: 1px;
31 width: 1px;
35 }
32 }
36 .CodeMirror-scrollbar.cm-sb-overlap {
33 .CodeMirror-scrollbar.cm-sb-overlap {
37 /* Ensure that the scrollbar appears in Lion, and that it overlaps the content
34 /* Ensure that the scrollbar appears in Lion, and that it overlaps the content
38 rather than sitting to the right of it. */
35 rather than sitting to the right of it. */
39 position: absolute;
36 position: absolute;
40 z-index: 1;
37 z-index: 1;
41 float: none;
38 float: none;
42 right: 0;
39 right: 0;
43 min-width: 12px;
40 min-width: 12px;
44 }
41 }
45 .CodeMirror-scrollbar.cm-sb-nonoverlap {
42 .CodeMirror-scrollbar.cm-sb-nonoverlap {
46 min-width: 12px;
43 min-width: 12px;
47 }
44 }
48 .CodeMirror-scrollbar.cm-sb-ie7 {
45 .CodeMirror-scrollbar.cm-sb-ie7 {
49 min-width: 18px;
46 min-width: 18px;
50 }
47 }
51
48
52 .CodeMirror-gutter {
49 .CodeMirror-gutter {
53 position: absolute; left: 0; top: 0;
50 position: absolute; left: 0; top: 0;
54 z-index: 10;
51 z-index: 10;
55 background-color: #f7f7f7;
52 background-color: #f7f7f7;
56 border-right: 1px solid #eee;
53 border-right: 1px solid #eee;
57 min-width: 2em;
54 min-width: 2em;
58 height: 100%;
55 height: 100%;
59 }
56 }
60 .CodeMirror-gutter-text {
57 .CodeMirror-gutter-text {
61 color: #aaa;
58 color: #aaa;
62 text-align: right;
59 text-align: right;
63 padding: .4em .2em .4em .4em;
60 padding: .4em .2em .4em .4em;
64 white-space: pre !important;
61 white-space: pre !important;
62 cursor: default;
65 }
63 }
66 .CodeMirror-lines {
64 .CodeMirror-lines {
67 padding: .4em;
65 padding: .4em;
68 white-space: pre;
66 white-space: pre;
69 cursor: text;
67 cursor: text;
70 }
68 }
71 .CodeMirror-lines * {
72 /* Necessary for throw-scrolling to decelerate properly on Safari. */
73 pointer-events: none;
74 }
75
69
76 .CodeMirror pre {
70 .CodeMirror pre {
77 -moz-border-radius: 0;
71 -moz-border-radius: 0;
78 -webkit-border-radius: 0;
72 -webkit-border-radius: 0;
79 -o-border-radius: 0;
73 -o-border-radius: 0;
80 border-radius: 0;
74 border-radius: 0;
81 border-width: 0; margin: 0; padding: 0; background: transparent;
75 border-width: 0; margin: 0; padding: 0; background: transparent;
82 font-family: inherit;
76 font-family: inherit;
83 font-size: inherit;
77 font-size: inherit;
84 padding: 0; margin: 0;
78 padding: 0; margin: 0;
85 white-space: pre;
79 white-space: pre;
86 word-wrap: normal;
80 word-wrap: normal;
87 line-height: inherit;
81 line-height: inherit;
88 color: inherit;
82 color: inherit;
89 }
83 }
90
84
91 .CodeMirror-wrap pre {
85 .CodeMirror-wrap pre {
92 word-wrap: break-word;
86 word-wrap: break-word;
93 white-space: pre-wrap;
87 white-space: pre-wrap;
94 word-break: normal;
88 word-break: normal;
95 }
89 }
96 .CodeMirror-wrap .CodeMirror-scroll {
90 .CodeMirror-wrap .CodeMirror-scroll {
97 overflow-x: hidden;
91 overflow-x: hidden;
98 }
92 }
99
93
100 .CodeMirror textarea {
94 .CodeMirror textarea {
101 outline: none !important;
95 outline: none !important;
102 }
96 }
103
97
104 .CodeMirror pre.CodeMirror-cursor {
98 .CodeMirror pre.CodeMirror-cursor {
105 z-index: 10;
99 z-index: 10;
106 position: absolute;
100 position: absolute;
107 visibility: hidden;
101 visibility: hidden;
108 border-left: 1px solid black;
102 border-left: 1px solid black;
109 border-right: none;
103 border-right: none;
110 width: 0;
104 width: 0;
111 }
105 }
112 .cm-keymap-fat-cursor pre.CodeMirror-cursor {
106 .cm-keymap-fat-cursor pre.CodeMirror-cursor {
113 width: auto;
107 width: auto;
114 border: 0;
108 border: 0;
115 background: transparent;
109 background: transparent;
116 background: rgba(0, 200, 0, .4);
110 background: rgba(0, 200, 0, .4);
117 filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#6600c800, endColorstr=#4c00c800);
111 filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#6600c800, endColorstr=#4c00c800);
118 }
112 }
119 /* Kludge to turn off filter in ie9+, which also accepts rgba */
113 /* Kludge to turn off filter in ie9+, which also accepts rgba */
120 .cm-keymap-fat-cursor pre.CodeMirror-cursor:not(#nonsense_id) {
114 .cm-keymap-fat-cursor pre.CodeMirror-cursor:not(#nonsense_id) {
121 filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
115 filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
122 }
116 }
123 .CodeMirror pre.CodeMirror-cursor.CodeMirror-overwrite {}
117 .CodeMirror pre.CodeMirror-cursor.CodeMirror-overwrite {}
124 .CodeMirror-focused pre.CodeMirror-cursor {
118 .CodeMirror-focused pre.CodeMirror-cursor {
125 visibility: visible;
119 visibility: visible;
126 }
120 }
127
121
128 div.CodeMirror-selected { background: #d9d9d9; }
122 div.CodeMirror-selected { background: #d9d9d9; }
129 .CodeMirror-focused div.CodeMirror-selected { background: #d7d4f0; }
123 .CodeMirror-focused div.CodeMirror-selected { background: #d7d4f0; }
130
124
131 .CodeMirror-searching {
125 .CodeMirror-searching {
132 background: #ffa;
126 background: #ffa;
133 background: rgba(255, 255, 0, .4);
127 background: rgba(255, 255, 0, .4);
134 }
128 }
135
129
136 /* Default theme */
130 /* Default theme */
137
131
138 .cm-s-default span.cm-keyword {color: #708;}
132 .cm-s-default span.cm-keyword {color: #708;}
139 .cm-s-default span.cm-atom {color: #219;}
133 .cm-s-default span.cm-atom {color: #219;}
140 .cm-s-default span.cm-number {color: #164;}
134 .cm-s-default span.cm-number {color: #164;}
141 .cm-s-default span.cm-def {color: #00f;}
135 .cm-s-default span.cm-def {color: #00f;}
142 .cm-s-default span.cm-variable {color: black;}
136 .cm-s-default span.cm-variable {color: black;}
143 .cm-s-default span.cm-variable-2 {color: #05a;}
137 .cm-s-default span.cm-variable-2 {color: #05a;}
144 .cm-s-default span.cm-variable-3 {color: #085;}
138 .cm-s-default span.cm-variable-3 {color: #085;}
145 .cm-s-default span.cm-property {color: black;}
139 .cm-s-default span.cm-property {color: black;}
146 .cm-s-default span.cm-operator {color: black;}
140 .cm-s-default span.cm-operator {color: black;}
147 .cm-s-default span.cm-comment {color: #a50;}
141 .cm-s-default span.cm-comment {color: #a50;}
148 .cm-s-default span.cm-string {color: #a11;}
142 .cm-s-default span.cm-string {color: #a11;}
149 .cm-s-default span.cm-string-2 {color: #f50;}
143 .cm-s-default span.cm-string-2 {color: #f50;}
150 .cm-s-default span.cm-meta {color: #555;}
144 .cm-s-default span.cm-meta {color: #555;}
151 .cm-s-default span.cm-error {color: #f00;}
145 .cm-s-default span.cm-error {color: #f00;}
152 .cm-s-default span.cm-qualifier {color: #555;}
146 .cm-s-default span.cm-qualifier {color: #555;}
153 .cm-s-default span.cm-builtin {color: #30a;}
147 .cm-s-default span.cm-builtin {color: #30a;}
154 .cm-s-default span.cm-bracket {color: #cc7;}
148 .cm-s-default span.cm-bracket {color: #997;}
155 .cm-s-default span.cm-tag {color: #170;}
149 .cm-s-default span.cm-tag {color: #170;}
156 .cm-s-default span.cm-attribute {color: #00c;}
150 .cm-s-default span.cm-attribute {color: #00c;}
157 .cm-s-default span.cm-header {color: blue;}
151 .cm-s-default span.cm-header {color: blue;}
158 .cm-s-default span.cm-quote {color: #090;}
152 .cm-s-default span.cm-quote {color: #090;}
159 .cm-s-default span.cm-hr {color: #999;}
153 .cm-s-default span.cm-hr {color: #999;}
160 .cm-s-default span.cm-link {color: #00c;}
154 .cm-s-default span.cm-link {color: #00c;}
161
155
162 span.cm-header, span.cm-strong {font-weight: bold;}
156 span.cm-header, span.cm-strong {font-weight: bold;}
163 span.cm-em {font-style: italic;}
157 span.cm-em {font-style: italic;}
164 span.cm-emstrong {font-style: italic; font-weight: bold;}
158 span.cm-emstrong {font-style: italic; font-weight: bold;}
165 span.cm-link {text-decoration: underline;}
159 span.cm-link {text-decoration: underline;}
166
160
161 span.cm-invalidchar {color: #f00;}
162
167 div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
163 div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
168 div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
164 div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
165
166 @media print {
167
168 /* Hide the cursor when printing */
169 .CodeMirror pre.CodeMirror-cursor {
170 visibility: hidden;
171 }
172
173 }
This diff has been collapsed as it changes many lines, (1624 lines changed) Show them Hide them
@@ -1,3179 +1,3141
1 // All functions that need access to the editor's state live inside
1 // All functions that need access to the editor's state live inside
2 // the CodeMirror function. Below that, at the bottom of the file,
2 // the CodeMirror function. Below that, at the bottom of the file,
3 // some utilities are defined.
3 // some utilities are defined.
4
4
5 // CodeMirror is the only global var we claim
5 // CodeMirror is the only global var we claim
6 var CodeMirror = (function() {
6 window.CodeMirror = (function() {
7 "use strict";
7 // This is the function that produces an editor instance. Its
8 // This is the function that produces an editor instance. Its
8 // closure is used to store the editor state.
9 // closure is used to store the editor state.
9 function CodeMirror(place, givenOptions) {
10 function CodeMirror(place, givenOptions) {
10 // Determine effective options based on given values and defaults.
11 // Determine effective options based on given values and defaults.
11 var options = {}, defaults = CodeMirror.defaults;
12 var options = {}, defaults = CodeMirror.defaults;
12 for (var opt in defaults)
13 for (var opt in defaults)
13 if (defaults.hasOwnProperty(opt))
14 if (defaults.hasOwnProperty(opt))
14 options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt];
15 options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt];
15
16
17 var input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em");
18 input.setAttribute("wrap", "off"); input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off");
19 // Wraps and hides input textarea
20 var inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
21 // The empty scrollbar content, used solely for managing the scrollbar thumb.
22 var scrollbarInner = elt("div", null, "CodeMirror-scrollbar-inner");
23 // The vertical scrollbar. Horizontal scrolling is handled by the scroller itself.
24 var scrollbar = elt("div", [scrollbarInner], "CodeMirror-scrollbar");
25 // DIVs containing the selection and the actual code
26 var lineDiv = elt("div"), selectionDiv = elt("div", null, null, "position: relative; z-index: -1");
27 // Blinky cursor, and element used to ensure cursor fits at the end of a line
28 var cursor = elt("pre", "\u00a0", "CodeMirror-cursor"), widthForcer = elt("pre", "\u00a0", "CodeMirror-cursor", "visibility: hidden");
29 // Used to measure text size
30 var measure = elt("div", null, null, "position: absolute; width: 100%; height: 0px; overflow: hidden; visibility: hidden;");
31 var lineSpace = elt("div", [measure, cursor, widthForcer, selectionDiv, lineDiv], null, "position: relative; z-index: 0");
32 var gutterText = elt("div", null, "CodeMirror-gutter-text"), gutter = elt("div", [gutterText], "CodeMirror-gutter");
33 // Moved around its parent to cover visible view
34 var mover = elt("div", [gutter, elt("div", [lineSpace], "CodeMirror-lines")], null, "position: relative");
35 // Set to the height of the text, causes scrolling
36 var sizer = elt("div", [mover], null, "position: relative");
37 // Provides scrolling
38 var scroller = elt("div", [sizer], "CodeMirror-scroll");
39 scroller.setAttribute("tabIndex", "-1");
16 // The element in which the editor lives.
40 // The element in which the editor lives.
17 var wrapper = document.createElement("div");
41 var wrapper = elt("div", [inputDiv, scrollbar, scroller], "CodeMirror" + (options.lineWrapping ? " CodeMirror-wrap" : ""));
18 wrapper.className = "CodeMirror" + (options.lineWrapping ? " CodeMirror-wrap" : "");
19 // This mess creates the base DOM structure for the editor.
20 wrapper.innerHTML =
21 '<div style="overflow: hidden; position: relative; width: 3px; height: 0px;">' + // Wraps and hides input textarea
22 '<textarea style="position: absolute; padding: 0; width: 1px; height: 1em" wrap="off" ' +
23 'autocorrect="off" autocapitalize="off"></textarea></div>' +
24 '<div class="CodeMirror-scrollbar">' + // The vertical scrollbar. Horizontal scrolling is handled by the scroller itself.
25 '<div class="CodeMirror-scrollbar-inner">' + // The empty scrollbar content, used solely for managing the scrollbar thumb.
26 '</div></div>' + // This must be before the scroll area because it's float-right.
27 '<div class="CodeMirror-scroll" tabindex="-1">' +
28 '<div style="position: relative">' + // Set to the height of the text, causes scrolling
29 '<div style="position: relative">' + // Moved around its parent to cover visible view
30 '<div class="CodeMirror-gutter"><div class="CodeMirror-gutter-text"></div></div>' +
31 // Provides positioning relative to (visible) text origin
32 '<div class="CodeMirror-lines"><div style="position: relative; z-index: 0">' +
33 // Used to measure text size
34 '<div style="position: absolute; width: 100%; height: 0; overflow: hidden; visibility: hidden;"></div>' +
35 '<pre class="CodeMirror-cursor">&#160;</pre>' + // Absolutely positioned blinky cursor
36 '<pre class="CodeMirror-cursor" style="visibility: hidden">&#160;</pre>' + // Used to force a width
37 '<div style="position: relative; z-index: -1"></div><div></div>' + // DIVs containing the selection and the actual code
38 '</div></div></div></div></div>';
39 if (place.appendChild) place.appendChild(wrapper); else place(wrapper);
42 if (place.appendChild) place.appendChild(wrapper); else place(wrapper);
40 // I've never seen more elegant code in my life.
43
41 var inputDiv = wrapper.firstChild, input = inputDiv.firstChild,
42 scroller = wrapper.lastChild, code = scroller.firstChild,
43 mover = code.firstChild, gutter = mover.firstChild, gutterText = gutter.firstChild,
44 lineSpace = gutter.nextSibling.firstChild, measure = lineSpace.firstChild,
45 cursor = measure.nextSibling, widthForcer = cursor.nextSibling,
46 selectionDiv = widthForcer.nextSibling, lineDiv = selectionDiv.nextSibling,
47 scrollbar = inputDiv.nextSibling, scrollbarInner = scrollbar.firstChild;
48 themeChanged(); keyMapChanged();
44 themeChanged(); keyMapChanged();
49 // Needed to hide big blue blinking cursor on Mobile Safari
45 // Needed to hide big blue blinking cursor on Mobile Safari
50 if (ios) input.style.width = "0px";
46 if (ios) input.style.width = "0px";
51 if (!webkit) scroller.draggable = true;
47 if (!webkit) scroller.draggable = true;
52 lineSpace.style.outline = "none";
48 lineSpace.style.outline = "none";
53 if (options.tabindex != null) input.tabIndex = options.tabindex;
49 if (options.tabindex != null) input.tabIndex = options.tabindex;
54 if (options.autofocus) focusInput();
50 if (options.autofocus) focusInput();
55 if (!options.gutter && !options.lineNumbers) gutter.style.display = "none";
51 if (!options.gutter && !options.lineNumbers) gutter.style.display = "none";
56 // Needed to handle Tab key in KHTML
52 // Needed to handle Tab key in KHTML
57 if (khtml) inputDiv.style.height = "1px", inputDiv.style.position = "absolute";
53 if (khtml) inputDiv.style.height = "1px", inputDiv.style.position = "absolute";
58
54
59 // Check for OS X >= 10.7. If so, we need to force a width on the scrollbar, and
55 // Check for OS X >= 10.7. This has transparent scrollbars, so the
60 // make it overlap the content. (But we only do this if the scrollbar doesn't already
56 // overlaying of one scrollbar with another won't work. This is a
61 // have a natural width. If the mouse is plugged in or the user sets the system pref
57 // temporary hack to simply turn off the overlay scrollbar. See
62 // to always show scrollbars, the scrollbar shouldn't overlap.)
58 // issue #727.
63 if (mac_geLion) {
59 if (mac_geLion) { scrollbar.style.zIndex = -2; scrollbar.style.visibility = "hidden"; }
64 scrollbar.className += (overlapScrollbars() ? " cm-sb-overlap" : " cm-sb-nonoverlap");
60 // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
65 } else if (ie_lt8) {
61 else if (ie_lt8) scrollbar.style.minWidth = "18px";
66 // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
67 scrollbar.className += " cm-sb-ie7";
68 }
69
70 // Check for problem with IE innerHTML not working when we have a
71 // P (or similar) parent node.
72 try { stringWidth("x"); }
73 catch (e) {
74 if (e.message.match(/runtime/i))
75 e = new Error("A CodeMirror inside a P-style element does not work in Internet Explorer. (innerHTML bug)");
76 throw e;
77 }
78
62
79 // Delayed object wrap timeouts, making sure only one is active. blinker holds an interval.
63 // Delayed object wrap timeouts, making sure only one is active. blinker holds an interval.
80 var poll = new Delayed(), highlight = new Delayed(), blinker;
64 var poll = new Delayed(), highlight = new Delayed(), blinker;
81
65
82 // mode holds a mode API object. doc is the tree of Line objects,
66 // mode holds a mode API object. doc is the tree of Line objects,
83 // work an array of lines that should be parsed, and history the
67 // frontier is the point up to which the content has been parsed,
84 // undo history (instance of History constructor).
68 // and history the undo history (instance of History constructor).
85 var mode, doc = new BranchChunk([new LeafChunk([new Line("")])]), work, focused;
69 var mode, doc = new BranchChunk([new LeafChunk([new Line("")])]), frontier = 0, focused;
86 loadMode();
70 loadMode();
87 // The selection. These are always maintained to point at valid
71 // The selection. These are always maintained to point at valid
88 // positions. Inverted is used to remember that the user is
72 // positions. Inverted is used to remember that the user is
89 // selecting bottom-to-top.
73 // selecting bottom-to-top.
90 var sel = {from: {line: 0, ch: 0}, to: {line: 0, ch: 0}, inverted: false};
74 var sel = {from: {line: 0, ch: 0}, to: {line: 0, ch: 0}, inverted: false};
91 // Selection-related flags. shiftSelecting obviously tracks
75 // Selection-related flags. shiftSelecting obviously tracks
92 // whether the user is holding shift.
76 // whether the user is holding shift.
93 var shiftSelecting, lastClick, lastDoubleClick, lastScrollTop = 0, lastScrollLeft = 0, draggingText,
77 var shiftSelecting, lastClick, lastDoubleClick, lastScrollTop = 0, draggingText,
94 overwrite = false, suppressEdits = false;
78 overwrite = false, suppressEdits = false;
95 // Variables used by startOperation/endOperation to track what
79 // Variables used by startOperation/endOperation to track what
96 // happened during the operation.
80 // happened during the operation.
97 var updateInput, userSelChange, changes, textChanged, selectionChanged, leaveInputAlone,
81 var updateInput, userSelChange, changes, textChanged, selectionChanged,
98 gutterDirty, callbacks;
82 gutterDirty, callbacks;
99 // Current visible range (may be bigger than the view window).
83 // Current visible range (may be bigger than the view window).
100 var displayOffset = 0, showingFrom = 0, showingTo = 0, lastSizeC = 0;
84 var displayOffset = 0, showingFrom = 0, showingTo = 0, lastSizeC = 0;
101 // bracketHighlighted is used to remember that a bracket has been
85 // bracketHighlighted is used to remember that a bracket has been
102 // marked.
86 // marked.
103 var bracketHighlighted;
87 var bracketHighlighted;
104 // Tracks the maximum line length so that the horizontal scrollbar
88 // Tracks the maximum line length so that the horizontal scrollbar
105 // can be kept static when scrolling.
89 // can be kept static when scrolling.
106 var maxLine = "", updateMaxLine = false, maxLineChanged = true;
90 var maxLine = getLine(0), updateMaxLine = false, maxLineChanged = true;
107 var tabCache = {};
91 var pollingFast = false; // Ensures slowPoll doesn't cancel fastPoll
92 var goalColumn = null;
108
93
109 // Initialize the content.
94 // Initialize the content.
110 operation(function(){setValue(options.value || ""); updateInput = false;})();
95 operation(function(){setValue(options.value || ""); updateInput = false;})();
111 var history = new History();
96 var history = new History();
112
97
113 // Register our event handlers.
98 // Register our event handlers.
114 connect(scroller, "mousedown", operation(onMouseDown));
99 connect(scroller, "mousedown", operation(onMouseDown));
115 connect(scroller, "dblclick", operation(onDoubleClick));
100 connect(scroller, "dblclick", operation(onDoubleClick));
116 connect(lineSpace, "selectstart", e_preventDefault);
101 connect(lineSpace, "selectstart", e_preventDefault);
117 // Gecko browsers fire contextmenu *after* opening the menu, at
102 // Gecko browsers fire contextmenu *after* opening the menu, at
118 // which point we can't mess with it anymore. Context menu is
103 // which point we can't mess with it anymore. Context menu is
119 // handled in onMouseDown for Gecko.
104 // handled in onMouseDown for Gecko.
120 if (!gecko) connect(scroller, "contextmenu", onContextMenu);
105 if (!gecko) connect(scroller, "contextmenu", onContextMenu);
121 connect(scroller, "scroll", onScroll);
106 connect(scroller, "scroll", onScrollMain);
122 connect(scrollbar, "scroll", onScroll);
107 connect(scrollbar, "scroll", onScrollBar);
123 connect(scrollbar, "mousedown", function() {setTimeout(focusInput, 0);});
108 connect(scrollbar, "mousedown", function() {if (focused) setTimeout(focusInput, 0);});
124 connect(scroller, "mousewheel", onMouseWheel);
109 var resizeHandler = connect(window, "resize", function() {
125 connect(scroller, "DOMMouseScroll", onMouseWheel);
110 if (wrapper.parentNode) updateDisplay(true);
126 connect(window, "resize", function() {updateDisplay(true);});
111 else resizeHandler();
112 }, true);
127 connect(input, "keyup", operation(onKeyUp));
113 connect(input, "keyup", operation(onKeyUp));
128 connect(input, "input", fastPoll);
114 connect(input, "input", fastPoll);
129 connect(input, "keydown", operation(onKeyDown));
115 connect(input, "keydown", operation(onKeyDown));
130 connect(input, "keypress", operation(onKeyPress));
116 connect(input, "keypress", operation(onKeyPress));
131 connect(input, "focus", onFocus);
117 connect(input, "focus", onFocus);
132 connect(input, "blur", onBlur);
118 connect(input, "blur", onBlur);
133
119
120 function drag_(e) {
121 if (options.onDragEvent && options.onDragEvent(instance, addStop(e))) return;
122 e_stop(e);
123 }
134 if (options.dragDrop) {
124 if (options.dragDrop) {
135 connect(scroller, "dragstart", onDragStart);
125 connect(scroller, "dragstart", onDragStart);
136 function drag_(e) {
137 if (options.onDragEvent && options.onDragEvent(instance, addStop(e))) return;
138 e_stop(e);
139 }
140 connect(scroller, "dragenter", drag_);
126 connect(scroller, "dragenter", drag_);
141 connect(scroller, "dragover", drag_);
127 connect(scroller, "dragover", drag_);
142 connect(scroller, "drop", operation(onDrop));
128 connect(scroller, "drop", operation(onDrop));
143 }
129 }
144 connect(scroller, "paste", function(){focusInput(); fastPoll();});
130 connect(scroller, "paste", function(){focusInput(); fastPoll();});
145 connect(input, "paste", fastPoll);
131 connect(input, "paste", fastPoll);
146 connect(input, "cut", operation(function(){
132 connect(input, "cut", operation(function(){
147 if (!options.readOnly) replaceSelection("");
133 if (!options.readOnly) replaceSelection("");
148 }));
134 }));
149
135
150 // Needed to handle Tab key in KHTML
136 // Needed to handle Tab key in KHTML
151 if (khtml) connect(code, "mouseup", function() {
137 if (khtml) connect(sizer, "mouseup", function() {
152 if (document.activeElement == input) input.blur();
138 if (document.activeElement == input) input.blur();
153 focusInput();
139 focusInput();
154 });
140 });
155
141
156 // IE throws unspecified error in certain cases, when
142 // IE throws unspecified error in certain cases, when
157 // trying to access activeElement before onload
143 // trying to access activeElement before onload
158 var hasFocus; try { hasFocus = (document.activeElement == input); } catch(e) { }
144 var hasFocus; try { hasFocus = (document.activeElement == input); } catch(e) { }
159 if (hasFocus || options.autofocus) setTimeout(onFocus, 20);
145 if (hasFocus || options.autofocus) setTimeout(onFocus, 20);
160 else onBlur();
146 else onBlur();
161
147
162 function isLine(l) {return l >= 0 && l < doc.size;}
148 function isLine(l) {return l >= 0 && l < doc.size;}
163 // The instance object that we'll return. Mostly calls out to
149 // The instance object that we'll return. Mostly calls out to
164 // local functions in the CodeMirror function. Some do some extra
150 // local functions in the CodeMirror function. Some do some extra
165 // range checking and/or clipping. operation is used to wrap the
151 // range checking and/or clipping. operation is used to wrap the
166 // call so that changes it makes are tracked, and the display is
152 // call so that changes it makes are tracked, and the display is
167 // updated afterwards.
153 // updated afterwards.
168 var instance = wrapper.CodeMirror = {
154 var instance = wrapper.CodeMirror = {
169 getValue: getValue,
155 getValue: getValue,
170 setValue: operation(setValue),
156 setValue: operation(setValue),
171 getSelection: getSelection,
157 getSelection: getSelection,
172 replaceSelection: operation(replaceSelection),
158 replaceSelection: operation(replaceSelection),
173 focus: function(){window.focus(); focusInput(); onFocus(); fastPoll();},
159 focus: function(){window.focus(); focusInput(); onFocus(); fastPoll();},
174 setOption: function(option, value) {
160 setOption: function(option, value) {
175 var oldVal = options[option];
161 var oldVal = options[option];
176 options[option] = value;
162 options[option] = value;
177 if (option == "mode" || option == "indentUnit") loadMode();
163 if (option == "mode" || option == "indentUnit") loadMode();
178 else if (option == "readOnly" && value == "nocursor") {onBlur(); input.blur();}
164 else if (option == "readOnly" && value == "nocursor") {onBlur(); input.blur();}
179 else if (option == "readOnly" && !value) {resetInput(true);}
165 else if (option == "readOnly" && !value) {resetInput(true);}
180 else if (option == "theme") themeChanged();
166 else if (option == "theme") themeChanged();
181 else if (option == "lineWrapping" && oldVal != value) operation(wrappingChanged)();
167 else if (option == "lineWrapping" && oldVal != value) operation(wrappingChanged)();
182 else if (option == "tabSize") updateDisplay(true);
168 else if (option == "tabSize") updateDisplay(true);
183 else if (option == "keyMap") keyMapChanged();
169 else if (option == "keyMap") keyMapChanged();
184 if (option == "lineNumbers" || option == "gutter" || option == "firstLineNumber" || option == "theme") {
170 if (option == "lineNumbers" || option == "gutter" || option == "firstLineNumber" ||
171 option == "theme" || option == "lineNumberFormatter") {
185 gutterChanged();
172 gutterChanged();
186 updateDisplay(true);
173 updateDisplay(true);
187 }
174 }
188 },
175 },
189 getOption: function(option) {return options[option];},
176 getOption: function(option) {return options[option];},
177 getMode: function() {return mode;},
190 undo: operation(undo),
178 undo: operation(undo),
191 redo: operation(redo),
179 redo: operation(redo),
192 indentLine: operation(function(n, dir) {
180 indentLine: operation(function(n, dir) {
193 if (typeof dir != "string") {
181 if (typeof dir != "string") {
194 if (dir == null) dir = options.smartIndent ? "smart" : "prev";
182 if (dir == null) dir = options.smartIndent ? "smart" : "prev";
195 else dir = dir ? "add" : "subtract";
183 else dir = dir ? "add" : "subtract";
196 }
184 }
197 if (isLine(n)) indentLine(n, dir);
185 if (isLine(n)) indentLine(n, dir);
198 }),
186 }),
199 indentSelection: operation(indentSelected),
187 indentSelection: operation(indentSelected),
200 historySize: function() {return {undo: history.done.length, redo: history.undone.length};},
188 historySize: function() {return {undo: history.done.length, redo: history.undone.length};},
201 clearHistory: function() {history = new History();},
189 clearHistory: function() {history = new History();},
190 setHistory: function(histData) {
191 history = new History();
192 history.done = histData.done;
193 history.undone = histData.undone;
194 },
195 getHistory: function() {
196 function cp(arr) {
197 for (var i = 0, nw = [], nwelt; i < arr.length; ++i) {
198 nw.push(nwelt = []);
199 for (var j = 0, elt = arr[i]; j < elt.length; ++j) {
200 var old = [], cur = elt[j];
201 nwelt.push({start: cur.start, added: cur.added, old: old});
202 for (var k = 0; k < cur.old.length; ++k) old.push(hlText(cur.old[k]));
203 }
204 }
205 return nw;
206 }
207 return {done: cp(history.done), undone: cp(history.undone)};
208 },
202 matchBrackets: operation(function(){matchBrackets(true);}),
209 matchBrackets: operation(function(){matchBrackets(true);}),
203 getTokenAt: operation(function(pos) {
210 getTokenAt: operation(function(pos) {
204 pos = clipPos(pos);
211 pos = clipPos(pos);
205 return getLine(pos.line).getTokenAt(mode, getStateBefore(pos.line), pos.ch);
212 return getLine(pos.line).getTokenAt(mode, getStateBefore(pos.line), options.tabSize, pos.ch);
206 }),
213 }),
207 getStateAfter: function(line) {
214 getStateAfter: function(line) {
208 line = clipLine(line == null ? doc.size - 1: line);
215 line = clipLine(line == null ? doc.size - 1: line);
209 return getStateBefore(line + 1);
216 return getStateBefore(line + 1);
210 },
217 },
211 cursorCoords: function(start, mode) {
218 cursorCoords: function(start, mode) {
212 if (start == null) start = sel.inverted;
219 if (start == null) start = sel.inverted;
213 return this.charCoords(start ? sel.from : sel.to, mode);
220 return this.charCoords(start ? sel.from : sel.to, mode);
214 },
221 },
215 charCoords: function(pos, mode) {
222 charCoords: function(pos, mode) {
216 pos = clipPos(pos);
223 pos = clipPos(pos);
217 if (mode == "local") return localCoords(pos, false);
224 if (mode == "local") return localCoords(pos, false);
218 if (mode == "div") return localCoords(pos, true);
225 if (mode == "div") return localCoords(pos, true);
219 return pageCoords(pos);
226 return pageCoords(pos);
220 },
227 },
221 coordsChar: function(coords) {
228 coordsChar: function(coords) {
222 var off = eltOffset(lineSpace);
229 var off = eltOffset(lineSpace);
223 return coordsChar(coords.x - off.left, coords.y - off.top);
230 return coordsChar(coords.x - off.left, coords.y - off.top);
224 },
231 },
225 markText: operation(markText),
232 markText: operation(markText),
226 setBookmark: setBookmark,
233 setBookmark: setBookmark,
227 findMarksAt: findMarksAt,
234 findMarksAt: findMarksAt,
228 setMarker: operation(addGutterMarker),
235 setMarker: operation(addGutterMarker),
229 clearMarker: operation(removeGutterMarker),
236 clearMarker: operation(removeGutterMarker),
230 setLineClass: operation(setLineClass),
237 setLineClass: operation(setLineClass),
231 hideLine: operation(function(h) {return setLineHidden(h, true);}),
238 hideLine: operation(function(h) {return setLineHidden(h, true);}),
232 showLine: operation(function(h) {return setLineHidden(h, false);}),
239 showLine: operation(function(h) {return setLineHidden(h, false);}),
233 onDeleteLine: function(line, f) {
240 onDeleteLine: function(line, f) {
234 if (typeof line == "number") {
241 if (typeof line == "number") {
235 if (!isLine(line)) return null;
242 if (!isLine(line)) return null;
236 line = getLine(line);
243 line = getLine(line);
237 }
244 }
238 (line.handlers || (line.handlers = [])).push(f);
245 (line.handlers || (line.handlers = [])).push(f);
239 return line;
246 return line;
240 },
247 },
241 lineInfo: lineInfo,
248 lineInfo: lineInfo,
249 getViewport: function() { return {from: showingFrom, to: showingTo};},
242 addWidget: function(pos, node, scroll, vert, horiz) {
250 addWidget: function(pos, node, scroll, vert, horiz) {
243 pos = localCoords(clipPos(pos));
251 pos = localCoords(clipPos(pos));
244 var top = pos.yBot, left = pos.x;
252 var top = pos.yBot, left = pos.x;
245 node.style.position = "absolute";
253 node.style.position = "absolute";
246 code.appendChild(node);
254 sizer.appendChild(node);
247 if (vert == "over") top = pos.y;
255 if (vert == "over") top = pos.y;
248 else if (vert == "near") {
256 else if (vert == "near") {
249 var vspace = Math.max(scroller.offsetHeight, doc.height * textHeight()),
257 var vspace = Math.max(scroller.offsetHeight, doc.height * textHeight()),
250 hspace = Math.max(code.clientWidth, lineSpace.clientWidth) - paddingLeft();
258 hspace = Math.max(sizer.clientWidth, lineSpace.clientWidth) - paddingLeft();
251 if (pos.yBot + node.offsetHeight > vspace && pos.y > node.offsetHeight)
259 if (pos.yBot + node.offsetHeight > vspace && pos.y > node.offsetHeight)
252 top = pos.y - node.offsetHeight;
260 top = pos.y - node.offsetHeight;
253 if (left + node.offsetWidth > hspace)
261 if (left + node.offsetWidth > hspace)
254 left = hspace - node.offsetWidth;
262 left = hspace - node.offsetWidth;
255 }
263 }
256 node.style.top = (top + paddingTop()) + "px";
264 node.style.top = (top + paddingTop()) + "px";
257 node.style.left = node.style.right = "";
265 node.style.left = node.style.right = "";
258 if (horiz == "right") {
266 if (horiz == "right") {
259 left = code.clientWidth - node.offsetWidth;
267 left = sizer.clientWidth - node.offsetWidth;
260 node.style.right = "0px";
268 node.style.right = "0px";
261 } else {
269 } else {
262 if (horiz == "left") left = 0;
270 if (horiz == "left") left = 0;
263 else if (horiz == "middle") left = (code.clientWidth - node.offsetWidth) / 2;
271 else if (horiz == "middle") left = (sizer.clientWidth - node.offsetWidth) / 2;
264 node.style.left = (left + paddingLeft()) + "px";
272 node.style.left = (left + paddingLeft()) + "px";
265 }
273 }
266 if (scroll)
274 if (scroll)
267 scrollIntoView(left, top, left + node.offsetWidth, top + node.offsetHeight);
275 scrollIntoView(left, top, left + node.offsetWidth, top + node.offsetHeight);
268 },
276 },
269
277
270 lineCount: function() {return doc.size;},
278 lineCount: function() {return doc.size;},
271 clipPos: clipPos,
279 clipPos: clipPos,
272 getCursor: function(start) {
280 getCursor: function(start) {
273 if (start == null) start = sel.inverted;
281 if (start == null) start = sel.inverted;
274 return copyPos(start ? sel.from : sel.to);
282 return copyPos(start ? sel.from : sel.to);
275 },
283 },
276 somethingSelected: function() {return !posEq(sel.from, sel.to);},
284 somethingSelected: function() {return !posEq(sel.from, sel.to);},
277 setCursor: operation(function(line, ch, user) {
285 setCursor: operation(function(line, ch, user) {
278 if (ch == null && typeof line.line == "number") setCursor(line.line, line.ch, user);
286 if (ch == null && typeof line.line == "number") setCursor(line.line, line.ch, user);
279 else setCursor(line, ch, user);
287 else setCursor(line, ch, user);
280 }),
288 }),
281 setSelection: operation(function(from, to, user) {
289 setSelection: operation(function(from, to, user) {
282 (user ? setSelectionUser : setSelection)(clipPos(from), clipPos(to || from));
290 (user ? setSelectionUser : setSelection)(clipPos(from), clipPos(to || from));
283 }),
291 }),
284 getLine: function(line) {if (isLine(line)) return getLine(line).text;},
292 getLine: function(line) {if (isLine(line)) return getLine(line).text;},
285 getLineHandle: function(line) {if (isLine(line)) return getLine(line);},
293 getLineHandle: function(line) {if (isLine(line)) return getLine(line);},
286 setLine: operation(function(line, text) {
294 setLine: operation(function(line, text) {
287 if (isLine(line)) replaceRange(text, {line: line, ch: 0}, {line: line, ch: getLine(line).text.length});
295 if (isLine(line)) replaceRange(text, {line: line, ch: 0}, {line: line, ch: getLine(line).text.length});
288 }),
296 }),
289 removeLine: operation(function(line) {
297 removeLine: operation(function(line) {
290 if (isLine(line)) replaceRange("", {line: line, ch: 0}, clipPos({line: line+1, ch: 0}));
298 if (isLine(line)) replaceRange("", {line: line, ch: 0}, clipPos({line: line+1, ch: 0}));
291 }),
299 }),
292 replaceRange: operation(replaceRange),
300 replaceRange: operation(replaceRange),
293 getRange: function(from, to) {return getRange(clipPos(from), clipPos(to));},
301 getRange: function(from, to, lineSep) {return getRange(clipPos(from), clipPos(to), lineSep);},
294
302
295 triggerOnKeyDown: operation(onKeyDown),
303 triggerOnKeyDown: operation(onKeyDown),
296 execCommand: function(cmd) {return commands[cmd](instance);},
304 execCommand: function(cmd) {return commands[cmd](instance);},
297 // Stuff used by commands, probably not much use to outside code.
305 // Stuff used by commands, probably not much use to outside code.
298 moveH: operation(moveH),
306 moveH: operation(moveH),
299 deleteH: operation(deleteH),
307 deleteH: operation(deleteH),
300 moveV: operation(moveV),
308 moveV: operation(moveV),
301 toggleOverwrite: function() {
309 toggleOverwrite: function() {
302 if(overwrite){
310 if(overwrite){
303 overwrite = false;
311 overwrite = false;
304 cursor.className = cursor.className.replace(" CodeMirror-overwrite", "");
312 cursor.className = cursor.className.replace(" CodeMirror-overwrite", "");
305 } else {
313 } else {
306 overwrite = true;
314 overwrite = true;
307 cursor.className += " CodeMirror-overwrite";
315 cursor.className += " CodeMirror-overwrite";
308 }
316 }
309 },
317 },
310
318
311 posFromIndex: function(off) {
319 posFromIndex: function(off) {
312 var lineNo = 0, ch;
320 var lineNo = 0, ch;
313 doc.iter(0, doc.size, function(line) {
321 doc.iter(0, doc.size, function(line) {
314 var sz = line.text.length + 1;
322 var sz = line.text.length + 1;
315 if (sz > off) { ch = off; return true; }
323 if (sz > off) { ch = off; return true; }
316 off -= sz;
324 off -= sz;
317 ++lineNo;
325 ++lineNo;
318 });
326 });
319 return clipPos({line: lineNo, ch: ch});
327 return clipPos({line: lineNo, ch: ch});
320 },
328 },
321 indexFromPos: function (coords) {
329 indexFromPos: function (coords) {
322 if (coords.line < 0 || coords.ch < 0) return 0;
330 if (coords.line < 0 || coords.ch < 0) return 0;
323 var index = coords.ch;
331 var index = coords.ch;
324 doc.iter(0, coords.line, function (line) {
332 doc.iter(0, coords.line, function (line) {
325 index += line.text.length + 1;
333 index += line.text.length + 1;
326 });
334 });
327 return index;
335 return index;
328 },
336 },
329 scrollTo: function(x, y) {
337 scrollTo: function(x, y) {
330 if (x != null) scroller.scrollLeft = x;
338 if (x != null) scroller.scrollLeft = x;
331 if (y != null) scrollbar.scrollTop = y;
339 if (y != null) scrollbar.scrollTop = scroller.scrollTop = y;
332 updateDisplay([]);
340 updateDisplay([]);
333 },
341 },
334 getScrollInfo: function() {
342 getScrollInfo: function() {
335 return {x: scroller.scrollLeft, y: scrollbar.scrollTop,
343 return {x: scroller.scrollLeft, y: scrollbar.scrollTop,
336 height: scrollbar.scrollHeight, width: scroller.scrollWidth};
344 height: scrollbar.scrollHeight, width: scroller.scrollWidth};
337 },
345 },
346 setSize: function(width, height) {
347 function interpret(val) {
348 val = String(val);
349 return /^\d+$/.test(val) ? val + "px" : val;
350 }
351 if (width != null) wrapper.style.width = interpret(width);
352 if (height != null) scroller.style.height = interpret(height);
353 instance.refresh();
354 },
338
355
339 operation: function(f){return operation(f)();},
356 operation: function(f){return operation(f)();},
340 compoundChange: function(f){return compoundChange(f);},
357 compoundChange: function(f){return compoundChange(f);},
341 refresh: function(){
358 refresh: function(){
342 updateDisplay(true);
359 updateDisplay(true, null, lastScrollTop);
343 if (scrollbar.scrollHeight > lastScrollTop)
360 if (scrollbar.scrollHeight > lastScrollTop)
344 scrollbar.scrollTop = lastScrollTop;
361 scrollbar.scrollTop = lastScrollTop;
345 },
362 },
346 getInputField: function(){return input;},
363 getInputField: function(){return input;},
347 getWrapperElement: function(){return wrapper;},
364 getWrapperElement: function(){return wrapper;},
348 getScrollerElement: function(){return scroller;},
365 getScrollerElement: function(){return scroller;},
349 getGutterElement: function(){return gutter;}
366 getGutterElement: function(){return gutter;}
350 };
367 };
351
368
352 function getLine(n) { return getLineAt(doc, n); }
369 function getLine(n) { return getLineAt(doc, n); }
353 function updateLineHeight(line, height) {
370 function updateLineHeight(line, height) {
354 gutterDirty = true;
371 gutterDirty = true;
355 var diff = height - line.height;
372 var diff = height - line.height;
356 for (var n = line; n; n = n.parent) n.height += diff;
373 for (var n = line; n; n = n.parent) n.height += diff;
357 }
374 }
358
375
376 function lineContent(line, wrapAt) {
377 if (!line.styles)
378 line.highlight(mode, line.stateAfter = getStateBefore(lineNo(line)), options.tabSize);
379 return line.getContent(options.tabSize, wrapAt, options.lineWrapping);
380 }
381
359 function setValue(code) {
382 function setValue(code) {
360 var top = {line: 0, ch: 0};
383 var top = {line: 0, ch: 0};
361 updateLines(top, {line: doc.size - 1, ch: getLine(doc.size-1).text.length},
384 updateLines(top, {line: doc.size - 1, ch: getLine(doc.size-1).text.length},
362 splitLines(code), top, top);
385 splitLines(code), top, top);
363 updateInput = true;
386 updateInput = true;
364 }
387 }
365 function getValue() {
388 function getValue(lineSep) {
366 var text = [];
389 var text = [];
367 doc.iter(0, doc.size, function(line) { text.push(line.text); });
390 doc.iter(0, doc.size, function(line) { text.push(line.text); });
368 return text.join("\n");
391 return text.join(lineSep || "\n");
369 }
392 }
370
393
371 function onScroll(e) {
394 function onScrollBar(e) {
372 if (lastScrollTop != scrollbar.scrollTop || lastScrollLeft != scroller.scrollLeft) {
395 if (scrollbar.scrollTop != lastScrollTop) {
373 lastScrollTop = scrollbar.scrollTop;
396 lastScrollTop = scroller.scrollTop = scrollbar.scrollTop;
374 lastScrollLeft = scroller.scrollLeft;
375 updateDisplay([]);
397 updateDisplay([]);
376 if (options.fixedGutter) gutter.style.left = scroller.scrollLeft + "px";
377 if (options.onScroll) options.onScroll(instance);
378 }
398 }
379 }
399 }
380
400
401 function onScrollMain(e) {
402 if (options.fixedGutter && gutter.style.left != scroller.scrollLeft + "px")
403 gutter.style.left = scroller.scrollLeft + "px";
404 if (scroller.scrollTop != lastScrollTop) {
405 lastScrollTop = scroller.scrollTop;
406 if (scrollbar.scrollTop != lastScrollTop)
407 scrollbar.scrollTop = lastScrollTop;
408 updateDisplay([]);
409 }
410 if (options.onScroll) options.onScroll(instance);
411 }
412
381 function onMouseDown(e) {
413 function onMouseDown(e) {
382 setShift(e_prop(e, "shiftKey"));
414 setShift(e_prop(e, "shiftKey"));
383 // Check whether this is a click in a widget
415 // Check whether this is a click in a widget
384 for (var n = e_target(e); n != wrapper; n = n.parentNode)
416 for (var n = e_target(e); n != wrapper; n = n.parentNode)
385 if (n.parentNode == code && n != mover) return;
417 if (n.parentNode == sizer && n != mover) return;
386
418
387 // See if this is a click in the gutter
419 // See if this is a click in the gutter
388 for (var n = e_target(e); n != wrapper; n = n.parentNode)
420 for (var n = e_target(e); n != wrapper; n = n.parentNode)
389 if (n.parentNode == gutterText) {
421 if (n.parentNode == gutterText) {
390 if (options.onGutterClick)
422 if (options.onGutterClick)
391 options.onGutterClick(instance, indexOf(gutterText.childNodes, n) + showingFrom, e);
423 options.onGutterClick(instance, indexOf(gutterText.childNodes, n) + showingFrom, e);
392 return e_preventDefault(e);
424 return e_preventDefault(e);
393 }
425 }
394
426
395 var start = posFromMouse(e);
427 var start = posFromMouse(e);
396
428
397 switch (e_button(e)) {
429 switch (e_button(e)) {
398 case 3:
430 case 3:
399 if (gecko && !mac) onContextMenu(e);
431 if (gecko) onContextMenu(e);
400 return;
432 return;
401 case 2:
433 case 2:
402 if (start) setCursor(start.line, start.ch, true);
434 if (start) setCursor(start.line, start.ch, true);
403 setTimeout(focusInput, 20);
435 setTimeout(focusInput, 20);
404 e_preventDefault(e);
436 e_preventDefault(e);
405 return;
437 return;
406 }
438 }
407 // For button 1, if it was clicked inside the editor
439 // For button 1, if it was clicked inside the editor
408 // (posFromMouse returning non-null), we have to adjust the
440 // (posFromMouse returning non-null), we have to adjust the
409 // selection.
441 // selection.
410 if (!start) {if (e_target(e) == scroller) e_preventDefault(e); return;}
442 if (!start) {if (e_target(e) == scroller) e_preventDefault(e); return;}
411
443
412 if (!focused) onFocus();
444 if (!focused) onFocus();
413
445
414 var now = +new Date;
446 var now = +new Date, type = "single";
415 if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) {
447 if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) {
448 type = "triple";
416 e_preventDefault(e);
449 e_preventDefault(e);
417 setTimeout(focusInput, 20);
450 setTimeout(focusInput, 20);
418 return selectLine(start.line);
451 selectLine(start.line);
419 } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) {
452 } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) {
453 type = "double";
420 lastDoubleClick = {time: now, pos: start};
454 lastDoubleClick = {time: now, pos: start};
421 e_preventDefault(e);
455 e_preventDefault(e);
422 return selectWordAt(start);
456 var word = findWordAt(start);
457 setSelectionUser(word.from, word.to);
423 } else { lastClick = {time: now, pos: start}; }
458 } else { lastClick = {time: now, pos: start}; }
424
459
460 function dragEnd(e2) {
461 if (webkit) scroller.draggable = false;
462 draggingText = false;
463 up(); drop();
464 if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
465 e_preventDefault(e2);
466 setCursor(start.line, start.ch, true);
467 focusInput();
468 }
469 }
425 var last = start, going;
470 var last = start, going;
426 if (options.dragDrop && dragAndDrop && !options.readOnly && !posEq(sel.from, sel.to) &&
471 if (options.dragDrop && dragAndDrop && !options.readOnly && !posEq(sel.from, sel.to) &&
427 !posLess(start, sel.from) && !posLess(sel.to, start)) {
472 !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") {
428 // Let the drag handler handle this.
473 // Let the drag handler handle this.
429 if (webkit) scroller.draggable = true;
474 if (webkit) scroller.draggable = true;
430 function dragEnd(e2) {
431 if (webkit) scroller.draggable = false;
432 draggingText = false;
433 up(); drop();
434 if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
435 e_preventDefault(e2);
436 setCursor(start.line, start.ch, true);
437 focusInput();
438 }
439 }
440 var up = connect(document, "mouseup", operation(dragEnd), true);
475 var up = connect(document, "mouseup", operation(dragEnd), true);
441 var drop = connect(scroller, "drop", operation(dragEnd), true);
476 var drop = connect(scroller, "drop", operation(dragEnd), true);
442 draggingText = true;
477 draggingText = true;
443 // IE's approach to draggable
478 // IE's approach to draggable
444 if (scroller.dragDrop) scroller.dragDrop();
479 if (scroller.dragDrop) scroller.dragDrop();
445 return;
480 return;
446 }
481 }
447 e_preventDefault(e);
482 e_preventDefault(e);
448 setCursor(start.line, start.ch, true);
483 if (type == "single") setCursor(start.line, start.ch, true);
484
485 var startstart = sel.from, startend = sel.to;
486
487 function doSelect(cur) {
488 if (type == "single") {
489 setSelectionUser(start, cur);
490 } else if (type == "double") {
491 var word = findWordAt(cur);
492 if (posLess(cur, startstart)) setSelectionUser(word.from, startend);
493 else setSelectionUser(startstart, word.to);
494 } else if (type == "triple") {
495 if (posLess(cur, startstart)) setSelectionUser(startend, clipPos({line: cur.line, ch: 0}));
496 else setSelectionUser(startstart, clipPos({line: cur.line + 1, ch: 0}));
497 }
498 }
449
499
450 function extend(e) {
500 function extend(e) {
451 var cur = posFromMouse(e, true);
501 var cur = posFromMouse(e, true);
452 if (cur && !posEq(cur, last)) {
502 if (cur && !posEq(cur, last)) {
453 if (!focused) onFocus();
503 if (!focused) onFocus();
454 last = cur;
504 last = cur;
455 setSelectionUser(start, cur);
505 doSelect(cur);
456 updateInput = false;
506 updateInput = false;
457 var visible = visibleLines();
507 var visible = visibleLines();
458 if (cur.line >= visible.to || cur.line < visible.from)
508 if (cur.line >= visible.to || cur.line < visible.from)
459 going = setTimeout(operation(function(){extend(e);}), 150);
509 going = setTimeout(operation(function(){extend(e);}), 150);
460 }
510 }
461 }
511 }
462
512
463 function done(e) {
513 function done(e) {
464 clearTimeout(going);
514 clearTimeout(going);
465 var cur = posFromMouse(e);
515 var cur = posFromMouse(e);
466 if (cur) setSelectionUser(start, cur);
516 if (cur) doSelect(cur);
467 e_preventDefault(e);
517 e_preventDefault(e);
468 focusInput();
518 focusInput();
469 updateInput = true;
519 updateInput = true;
470 move(); up();
520 move(); up();
471 }
521 }
472 var move = connect(document, "mousemove", operation(function(e) {
522 var move = connect(document, "mousemove", operation(function(e) {
473 clearTimeout(going);
523 clearTimeout(going);
474 e_preventDefault(e);
524 e_preventDefault(e);
475 if (!ie && !e_button(e)) done(e);
525 if (!ie && !e_button(e)) done(e);
476 else extend(e);
526 else extend(e);
477 }), true);
527 }), true);
478 var up = connect(document, "mouseup", operation(done), true);
528 var up = connect(document, "mouseup", operation(done), true);
479 }
529 }
480 function onDoubleClick(e) {
530 function onDoubleClick(e) {
481 for (var n = e_target(e); n != wrapper; n = n.parentNode)
531 for (var n = e_target(e); n != wrapper; n = n.parentNode)
482 if (n.parentNode == gutterText) return e_preventDefault(e);
532 if (n.parentNode == gutterText) return e_preventDefault(e);
483 var start = posFromMouse(e);
484 if (!start) return;
485 lastDoubleClick = {time: +new Date, pos: start};
486 e_preventDefault(e);
533 e_preventDefault(e);
487 selectWordAt(start);
488 }
534 }
489 function onDrop(e) {
535 function onDrop(e) {
490 if (options.onDragEvent && options.onDragEvent(instance, addStop(e))) return;
536 if (options.onDragEvent && options.onDragEvent(instance, addStop(e))) return;
491 e.preventDefault();
537 e_preventDefault(e);
492 var pos = posFromMouse(e, true), files = e.dataTransfer.files;
538 var pos = posFromMouse(e, true), files = e.dataTransfer.files;
493 if (!pos || options.readOnly) return;
539 if (!pos || options.readOnly) return;
494 if (files && files.length && window.FileReader && window.File) {
540 if (files && files.length && window.FileReader && window.File) {
495 function loadFile(file, i) {
541 var n = files.length, text = Array(n), read = 0;
542 var loadFile = function(file, i) {
496 var reader = new FileReader;
543 var reader = new FileReader;
497 reader.onload = function() {
544 reader.onload = function() {
498 text[i] = reader.result;
545 text[i] = reader.result;
499 if (++read == n) {
546 if (++read == n) {
500 pos = clipPos(pos);
547 pos = clipPos(pos);
501 operation(function() {
548 operation(function() {
502 var end = replaceRange(text.join(""), pos, pos);
549 var end = replaceRange(text.join(""), pos, pos);
503 setSelectionUser(pos, end);
550 setSelectionUser(pos, end);
504 })();
551 })();
505 }
552 }
506 };
553 };
507 reader.readAsText(file);
554 reader.readAsText(file);
508 }
555 };
509 var n = files.length, text = Array(n), read = 0;
510 for (var i = 0; i < n; ++i) loadFile(files[i], i);
556 for (var i = 0; i < n; ++i) loadFile(files[i], i);
511 } else {
557 } else {
512 // Don't do a replace if the drop happened inside of the selected text.
558 // Don't do a replace if the drop happened inside of the selected text.
513 if (draggingText && !(posLess(pos, sel.from) || posLess(sel.to, pos))) return;
559 if (draggingText && !(posLess(pos, sel.from) || posLess(sel.to, pos))) return;
514 try {
560 try {
515 var text = e.dataTransfer.getData("Text");
561 var text = e.dataTransfer.getData("Text");
516 if (text) {
562 if (text) {
517 compoundChange(function() {
563 compoundChange(function() {
518 var curFrom = sel.from, curTo = sel.to;
564 var curFrom = sel.from, curTo = sel.to;
519 setSelectionUser(pos, pos);
565 setSelectionUser(pos, pos);
520 if (draggingText) replaceRange("", curFrom, curTo);
566 if (draggingText) replaceRange("", curFrom, curTo);
521 replaceSelection(text);
567 replaceSelection(text);
522 focusInput();
568 focusInput();
523 });
569 });
524 }
570 }
525 }
571 }
526 catch(e){}
572 catch(e){}
527 }
573 }
528 }
574 }
529 function onDragStart(e) {
575 function onDragStart(e) {
530 var txt = getSelection();
576 var txt = getSelection();
531 e.dataTransfer.setData("Text", txt);
577 e.dataTransfer.setData("Text", txt);
532
578
533 // Use dummy image instead of default browsers image.
579 // Use dummy image instead of default browsers image.
534 if (gecko || chrome || opera) {
580 if (e.dataTransfer.setDragImage)
535 var img = document.createElement('img');
581 e.dataTransfer.setDragImage(elt('img'), 0, 0);
536 img.scr = 'data:image/gif;base64,R0lGODdhAgACAIAAAAAAAP///ywAAAAAAgACAAACAoRRADs='; //1x1 image
537 e.dataTransfer.setDragImage(img, 0, 0);
538 }
539 }
582 }
540
583
541 function doHandleBinding(bound, dropShift) {
584 function doHandleBinding(bound, dropShift) {
542 if (typeof bound == "string") {
585 if (typeof bound == "string") {
543 bound = commands[bound];
586 bound = commands[bound];
544 if (!bound) return false;
587 if (!bound) return false;
545 }
588 }
546 var prevShift = shiftSelecting;
589 var prevShift = shiftSelecting;
547 try {
590 try {
548 if (options.readOnly) suppressEdits = true;
591 if (options.readOnly) suppressEdits = true;
549 if (dropShift) shiftSelecting = null;
592 if (dropShift) shiftSelecting = null;
550 bound(instance);
593 bound(instance);
551 } catch(e) {
594 } catch(e) {
552 if (e != Pass) throw e;
595 if (e != Pass) throw e;
553 return false;
596 return false;
554 } finally {
597 } finally {
555 shiftSelecting = prevShift;
598 shiftSelecting = prevShift;
556 suppressEdits = false;
599 suppressEdits = false;
557 }
600 }
558 return true;
601 return true;
559 }
602 }
603 var maybeTransition;
560 function handleKeyBinding(e) {
604 function handleKeyBinding(e) {
561 // Handle auto keymap transitions
605 // Handle auto keymap transitions
562 var startMap = getKeyMap(options.keyMap), next = startMap.auto;
606 var startMap = getKeyMap(options.keyMap), next = startMap.auto;
563 clearTimeout(maybeTransition);
607 clearTimeout(maybeTransition);
564 if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
608 if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
565 if (getKeyMap(options.keyMap) == startMap) {
609 if (getKeyMap(options.keyMap) == startMap) {
566 options.keyMap = (next.call ? next.call(null, instance) : next);
610 options.keyMap = (next.call ? next.call(null, instance) : next);
567 }
611 }
568 }, 50);
612 }, 50);
569
613
570 var name = keyNames[e_prop(e, "keyCode")], handled = false;
614 var name = keyNames[e_prop(e, "keyCode")], handled = false;
615 var flipCtrlCmd = opera && mac;
571 if (name == null || e.altGraphKey) return false;
616 if (name == null || e.altGraphKey) return false;
572 if (e_prop(e, "altKey")) name = "Alt-" + name;
617 if (e_prop(e, "altKey")) name = "Alt-" + name;
573 if (e_prop(e, "ctrlKey")) name = "Ctrl-" + name;
618 if (e_prop(e, flipCtrlCmd ? "metaKey" : "ctrlKey")) name = "Ctrl-" + name;
574 if (e_prop(e, "metaKey")) name = "Cmd-" + name;
619 if (e_prop(e, flipCtrlCmd ? "ctrlKey" : "metaKey")) name = "Cmd-" + name;
575
620
576 var stopped = false;
621 var stopped = false;
577 function stop() { stopped = true; }
622 function stop() { stopped = true; }
578
623
579 if (e_prop(e, "shiftKey")) {
624 if (e_prop(e, "shiftKey")) {
580 handled = lookupKey("Shift-" + name, options.extraKeys, options.keyMap,
625 handled = lookupKey("Shift-" + name, options.extraKeys, options.keyMap,
581 function(b) {return doHandleBinding(b, true);}, stop)
626 function(b) {return doHandleBinding(b, true);}, stop)
582 || lookupKey(name, options.extraKeys, options.keyMap, function(b) {
627 || lookupKey(name, options.extraKeys, options.keyMap, function(b) {
583 if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(b);
628 if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(b);
584 }, stop);
629 }, stop);
585 } else {
630 } else {
586 handled = lookupKey(name, options.extraKeys, options.keyMap, doHandleBinding, stop);
631 handled = lookupKey(name, options.extraKeys, options.keyMap, doHandleBinding, stop);
587 }
632 }
588 if (stopped) handled = false;
633 if (stopped) handled = false;
589 if (handled) {
634 if (handled) {
590 e_preventDefault(e);
635 e_preventDefault(e);
591 restartBlink();
636 restartBlink();
592 if (ie) { e.oldKeyCode = e.keyCode; e.keyCode = 0; }
637 if (ie) { e.oldKeyCode = e.keyCode; e.keyCode = 0; }
593 }
638 }
594 return handled;
639 return handled;
595 }
640 }
596 function handleCharBinding(e, ch) {
641 function handleCharBinding(e, ch) {
597 var handled = lookupKey("'" + ch + "'", options.extraKeys,
642 var handled = lookupKey("'" + ch + "'", options.extraKeys,
598 options.keyMap, function(b) { return doHandleBinding(b, true); });
643 options.keyMap, function(b) { return doHandleBinding(b, true); });
599 if (handled) {
644 if (handled) {
600 e_preventDefault(e);
645 e_preventDefault(e);
601 restartBlink();
646 restartBlink();
602 }
647 }
603 return handled;
648 return handled;
604 }
649 }
605
650
606 var lastStoppedKey = null, maybeTransition;
651 var lastStoppedKey = null;
607 function onKeyDown(e) {
652 function onKeyDown(e) {
608 if (!focused) onFocus();
653 if (!focused) onFocus();
609 if (ie && e.keyCode == 27) { e.returnValue = false; }
654 if (ie && e.keyCode == 27) { e.returnValue = false; }
610 if (pollingFast) { if (readInput()) pollingFast = false; }
655 if (pollingFast) { if (readInput()) pollingFast = false; }
611 if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
656 if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
612 var code = e_prop(e, "keyCode");
657 var code = e_prop(e, "keyCode");
613 // IE does strange things with escape.
658 // IE does strange things with escape.
614 setShift(code == 16 || e_prop(e, "shiftKey"));
659 setShift(code == 16 || e_prop(e, "shiftKey"));
615 // First give onKeyEvent option a chance to handle this.
660 // First give onKeyEvent option a chance to handle this.
616 var handled = handleKeyBinding(e);
661 var handled = handleKeyBinding(e);
617 if (opera) {
662 if (opera) {
618 lastStoppedKey = handled ? code : null;
663 lastStoppedKey = handled ? code : null;
619 // Opera has no cut event... we try to at least catch the key combo
664 // Opera has no cut event... we try to at least catch the key combo
620 if (!handled && code == 88 && e_prop(e, mac ? "metaKey" : "ctrlKey"))
665 if (!handled && code == 88 && e_prop(e, mac ? "metaKey" : "ctrlKey"))
621 replaceSelection("");
666 replaceSelection("");
622 }
667 }
623 }
668 }
624 function onKeyPress(e) {
669 function onKeyPress(e) {
625 if (pollingFast) readInput();
670 if (pollingFast) readInput();
626 if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
671 if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
627 var keyCode = e_prop(e, "keyCode"), charCode = e_prop(e, "charCode");
672 var keyCode = e_prop(e, "keyCode"), charCode = e_prop(e, "charCode");
628 if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
673 if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
629 if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(e)) return;
674 if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(e)) return;
630 var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
675 var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
631 if (options.electricChars && mode.electricChars && options.smartIndent && !options.readOnly) {
676 if (options.electricChars && mode.electricChars && options.smartIndent && !options.readOnly) {
632 if (mode.electricChars.indexOf(ch) > -1)
677 if (mode.electricChars.indexOf(ch) > -1)
633 setTimeout(operation(function() {indentLine(sel.to.line, "smart");}), 75);
678 setTimeout(operation(function() {indentLine(sel.to.line, "smart");}), 75);
634 }
679 }
635 if (handleCharBinding(e, ch)) return;
680 if (handleCharBinding(e, ch)) return;
636 fastPoll();
681 fastPoll();
637 }
682 }
638 function onKeyUp(e) {
683 function onKeyUp(e) {
639 if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
684 if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
640 if (e_prop(e, "keyCode") == 16) shiftSelecting = null;
685 if (e_prop(e, "keyCode") == 16) shiftSelecting = null;
641 }
686 }
642
687
643 function onFocus() {
688 function onFocus() {
644 if (options.readOnly == "nocursor") return;
689 if (options.readOnly == "nocursor") return;
645 if (!focused) {
690 if (!focused) {
646 if (options.onFocus) options.onFocus(instance);
691 if (options.onFocus) options.onFocus(instance);
647 focused = true;
692 focused = true;
648 if (scroller.className.search(/\bCodeMirror-focused\b/) == -1)
693 if (scroller.className.search(/\bCodeMirror-focused\b/) == -1)
649 scroller.className += " CodeMirror-focused";
694 scroller.className += " CodeMirror-focused";
650 if (!leaveInputAlone) resetInput(true);
651 }
695 }
652 slowPoll();
696 slowPoll();
653 restartBlink();
697 restartBlink();
654 }
698 }
655 function onBlur() {
699 function onBlur() {
656 if (focused) {
700 if (focused) {
657 if (options.onBlur) options.onBlur(instance);
701 if (options.onBlur) options.onBlur(instance);
658 focused = false;
702 focused = false;
659 if (bracketHighlighted)
703 if (bracketHighlighted)
660 operation(function(){
704 operation(function(){
661 if (bracketHighlighted) { bracketHighlighted(); bracketHighlighted = null; }
705 if (bracketHighlighted) { bracketHighlighted(); bracketHighlighted = null; }
662 })();
706 })();
663 scroller.className = scroller.className.replace(" CodeMirror-focused", "");
707 scroller.className = scroller.className.replace(" CodeMirror-focused", "");
664 }
708 }
665 clearInterval(blinker);
709 clearInterval(blinker);
666 setTimeout(function() {if (!focused) shiftSelecting = null;}, 150);
710 setTimeout(function() {if (!focused) shiftSelecting = null;}, 150);
667 }
711 }
668
712
669 function chopDelta(delta) {
670 // Make sure we always scroll a little bit for any nonzero delta.
671 if (delta > 0.0 && delta < 1.0) return 1;
672 else if (delta > -1.0 && delta < 0.0) return -1;
673 else return Math.round(delta);
674 }
675
676 function onMouseWheel(e) {
677 var deltaX = 0, deltaY = 0;
678 if (e.type == "DOMMouseScroll") { // Firefox
679 var delta = -e.detail * 8.0;
680 if (e.axis == e.HORIZONTAL_AXIS) deltaX = delta;
681 else if (e.axis == e.VERTICAL_AXIS) deltaY = delta;
682 } else if (e.wheelDeltaX !== undefined && e.wheelDeltaY !== undefined) { // WebKit
683 deltaX = e.wheelDeltaX / 3.0;
684 deltaY = e.wheelDeltaY / 3.0;
685 } else if (e.wheelDelta !== undefined) { // IE or Opera
686 deltaY = e.wheelDelta / 3.0;
687 }
688
689 var scrolled = false;
690 deltaX = chopDelta(deltaX);
691 deltaY = chopDelta(deltaY);
692 if ((deltaX > 0 && scroller.scrollLeft > 0) ||
693 (deltaX < 0 && scroller.scrollLeft + scroller.clientWidth < scroller.scrollWidth)) {
694 scroller.scrollLeft -= deltaX;
695 scrolled = true;
696 }
697 if ((deltaY > 0 && scrollbar.scrollTop > 0) ||
698 (deltaY < 0 && scrollbar.scrollTop + scrollbar.clientHeight < scrollbar.scrollHeight)) {
699 scrollbar.scrollTop -= deltaY;
700 scrolled = true;
701 }
702 if (scrolled) e_stop(e);
703 }
704
705 // Replace the range from from to to by the strings in newText.
713 // Replace the range from from to to by the strings in newText.
706 // Afterwards, set the selection to selFrom, selTo.
714 // Afterwards, set the selection to selFrom, selTo.
707 function updateLines(from, to, newText, selFrom, selTo) {
715 function updateLines(from, to, newText, selFrom, selTo) {
708 if (suppressEdits) return;
716 if (suppressEdits) return;
717 var old = [];
718 doc.iter(from.line, to.line + 1, function(line) {
719 old.push(newHL(line.text, line.markedSpans));
720 });
709 if (history) {
721 if (history) {
710 var old = [];
711 doc.iter(from.line, to.line + 1, function(line) { old.push(line.text); });
712 history.addChange(from.line, newText.length, old);
722 history.addChange(from.line, newText.length, old);
713 while (history.done.length > options.undoDepth) history.done.shift();
723 while (history.done.length > options.undoDepth) history.done.shift();
714 }
724 }
715 updateLinesNoUndo(from, to, newText, selFrom, selTo);
725 var lines = updateMarkedSpans(hlSpans(old[0]), hlSpans(lst(old)), from.ch, to.ch, newText);
726 updateLinesNoUndo(from, to, lines, selFrom, selTo);
716 }
727 }
717 function unredoHelper(from, to) {
728 function unredoHelper(from, to) {
718 if (!from.length) return;
729 if (!from.length) return;
719 var set = from.pop(), out = [];
730 var set = from.pop(), out = [];
720 for (var i = set.length - 1; i >= 0; i -= 1) {
731 for (var i = set.length - 1; i >= 0; i -= 1) {
721 var change = set[i];
732 var change = set[i];
722 var replaced = [], end = change.start + change.added;
733 var replaced = [], end = change.start + change.added;
723 doc.iter(change.start, end, function(line) { replaced.push(line.text); });
734 doc.iter(change.start, end, function(line) { replaced.push(newHL(line.text, line.markedSpans)); });
724 out.push({start: change.start, added: change.old.length, old: replaced});
735 out.push({start: change.start, added: change.old.length, old: replaced});
725 var pos = {line: change.start + change.old.length - 1,
736 var pos = {line: change.start + change.old.length - 1,
726 ch: editEnd(replaced[replaced.length-1], change.old[change.old.length-1])};
737 ch: editEnd(hlText(lst(replaced)), hlText(lst(change.old)))};
727 updateLinesNoUndo({line: change.start, ch: 0}, {line: end - 1, ch: getLine(end-1).text.length}, change.old, pos, pos);
738 updateLinesNoUndo({line: change.start, ch: 0}, {line: end - 1, ch: getLine(end-1).text.length},
739 change.old, pos, pos);
728 }
740 }
729 updateInput = true;
741 updateInput = true;
730 to.push(out);
742 to.push(out);
731 }
743 }
732 function undo() {unredoHelper(history.done, history.undone);}
744 function undo() {unredoHelper(history.done, history.undone);}
733 function redo() {unredoHelper(history.undone, history.done);}
745 function redo() {unredoHelper(history.undone, history.done);}
734
746
735 function updateLinesNoUndo(from, to, newText, selFrom, selTo) {
747 function updateLinesNoUndo(from, to, lines, selFrom, selTo) {
736 if (suppressEdits) return;
748 if (suppressEdits) return;
737 var recomputeMaxLength = false, maxLineLength = maxLine.length;
749 var recomputeMaxLength = false, maxLineLength = maxLine.text.length;
738 if (!options.lineWrapping)
750 if (!options.lineWrapping)
739 doc.iter(from.line, to.line + 1, function(line) {
751 doc.iter(from.line, to.line + 1, function(line) {
740 if (!line.hidden && line.text.length == maxLineLength) {recomputeMaxLength = true; return true;}
752 if (!line.hidden && line.text.length == maxLineLength) {recomputeMaxLength = true; return true;}
741 });
753 });
742 if (from.line != to.line || newText.length > 1) gutterDirty = true;
754 if (from.line != to.line || lines.length > 1) gutterDirty = true;
743
755
744 var nlines = to.line - from.line, firstLine = getLine(from.line), lastLine = getLine(to.line);
756 var nlines = to.line - from.line, firstLine = getLine(from.line), lastLine = getLine(to.line);
745 // First adjust the line structure, taking some care to leave highlighting intact.
757 var lastHL = lst(lines);
746 if (from.ch == 0 && to.ch == 0 && newText[newText.length - 1] == "") {
758
759 // First adjust the line structure
760 if (from.ch == 0 && to.ch == 0 && hlText(lastHL) == "") {
747 // This is a whole-line replace. Treated specially to make
761 // This is a whole-line replace. Treated specially to make
748 // sure line objects move the way they are supposed to.
762 // sure line objects move the way they are supposed to.
749 var added = [], prevLine = null;
763 var added = [], prevLine = null;
750 if (from.line) {
764 for (var i = 0, e = lines.length - 1; i < e; ++i)
751 prevLine = getLine(from.line - 1);
765 added.push(new Line(hlText(lines[i]), hlSpans(lines[i])));
752 prevLine.fixMarkEnds(lastLine);
766 lastLine.update(lastLine.text, hlSpans(lastHL));
753 } else lastLine.fixMarkStarts();
754 for (var i = 0, e = newText.length - 1; i < e; ++i)
755 added.push(Line.inheritMarks(newText[i], prevLine));
756 if (nlines) doc.remove(from.line, nlines, callbacks);
767 if (nlines) doc.remove(from.line, nlines, callbacks);
757 if (added.length) doc.insert(from.line, added);
768 if (added.length) doc.insert(from.line, added);
758 } else if (firstLine == lastLine) {
769 } else if (firstLine == lastLine) {
759 if (newText.length == 1)
770 if (lines.length == 1) {
760 firstLine.replace(from.ch, to.ch, newText[0]);
771 firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]) + firstLine.text.slice(to.ch), hlSpans(lines[0]));
761 else {
772 } else {
762 lastLine = firstLine.split(to.ch, newText[newText.length-1]);
773 for (var added = [], i = 1, e = lines.length - 1; i < e; ++i)
763 firstLine.replace(from.ch, null, newText[0]);
774 added.push(new Line(hlText(lines[i]), hlSpans(lines[i])));
764 firstLine.fixMarkEnds(lastLine);
775 added.push(new Line(hlText(lastHL) + firstLine.text.slice(to.ch), hlSpans(lastHL)));
765 var added = [];
776 firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0]));
766 for (var i = 1, e = newText.length - 1; i < e; ++i)
767 added.push(Line.inheritMarks(newText[i], firstLine));
768 added.push(lastLine);
769 doc.insert(from.line + 1, added);
777 doc.insert(from.line + 1, added);
770 }
778 }
771 } else if (newText.length == 1) {
779 } else if (lines.length == 1) {
772 firstLine.replace(from.ch, null, newText[0]);
780 firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]) + lastLine.text.slice(to.ch), hlSpans(lines[0]));
773 lastLine.replace(null, to.ch, "");
774 firstLine.append(lastLine);
775 doc.remove(from.line + 1, nlines, callbacks);
781 doc.remove(from.line + 1, nlines, callbacks);
776 } else {
782 } else {
777 var added = [];
783 var added = [];
778 firstLine.replace(from.ch, null, newText[0]);
784 firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0]));
779 lastLine.replace(null, to.ch, newText[newText.length-1]);
785 lastLine.update(hlText(lastHL) + lastLine.text.slice(to.ch), hlSpans(lastHL));
780 firstLine.fixMarkEnds(lastLine);
786 for (var i = 1, e = lines.length - 1; i < e; ++i)
781 for (var i = 1, e = newText.length - 1; i < e; ++i)
787 added.push(new Line(hlText(lines[i]), hlSpans(lines[i])));
782 added.push(Line.inheritMarks(newText[i], firstLine));
783 if (nlines > 1) doc.remove(from.line + 1, nlines - 1, callbacks);
788 if (nlines > 1) doc.remove(from.line + 1, nlines - 1, callbacks);
784 doc.insert(from.line + 1, added);
789 doc.insert(from.line + 1, added);
785 }
790 }
786 if (options.lineWrapping) {
791 if (options.lineWrapping) {
787 var perLine = Math.max(5, scroller.clientWidth / charWidth() - 3);
792 var perLine = Math.max(5, scroller.clientWidth / charWidth() - 3);
788 doc.iter(from.line, from.line + newText.length, function(line) {
793 doc.iter(from.line, from.line + lines.length, function(line) {
789 if (line.hidden) return;
794 if (line.hidden) return;
790 var guess = Math.ceil(line.text.length / perLine) || 1;
795 var guess = Math.ceil(line.text.length / perLine) || 1;
791 if (guess != line.height) updateLineHeight(line, guess);
796 if (guess != line.height) updateLineHeight(line, guess);
792 });
797 });
793 } else {
798 } else {
794 doc.iter(from.line, from.line + newText.length, function(line) {
799 doc.iter(from.line, from.line + lines.length, function(line) {
795 var l = line.text;
800 var l = line.text;
796 if (!line.hidden && l.length > maxLineLength) {
801 if (!line.hidden && l.length > maxLineLength) {
797 maxLine = l; maxLineLength = l.length; maxLineChanged = true;
802 maxLine = line; maxLineLength = l.length; maxLineChanged = true;
798 recomputeMaxLength = false;
803 recomputeMaxLength = false;
799 }
804 }
800 });
805 });
801 if (recomputeMaxLength) updateMaxLine = true;
806 if (recomputeMaxLength) updateMaxLine = true;
802 }
807 }
803
808
804 // Add these lines to the work array, so that they will be
809 // Adjust frontier, schedule worker
805 // highlighted. Adjust work lines if lines were added/removed.
810 frontier = Math.min(frontier, from.line);
806 var newWork = [], lendiff = newText.length - nlines - 1;
811 startWorker(400);
807 for (var i = 0, l = work.length; i < l; ++i) {
812
808 var task = work[i];
813 var lendiff = lines.length - nlines - 1;
809 if (task < from.line) newWork.push(task);
810 else if (task > to.line) newWork.push(task + lendiff);
811 }
812 var hlEnd = from.line + Math.min(newText.length, 500);
813 highlightLines(from.line, hlEnd);
814 newWork.push(hlEnd);
815 work = newWork;
816 startWorker(100);
817 // Remember that these lines changed, for updating the display
814 // Remember that these lines changed, for updating the display
818 changes.push({from: from.line, to: to.line + 1, diff: lendiff});
815 changes.push({from: from.line, to: to.line + 1, diff: lendiff});
819 var changeObj = {from: from, to: to, text: newText};
816 if (options.onChange) {
820 if (textChanged) {
817 // Normalize lines to contain only strings, since that's what
821 for (var cur = textChanged; cur.next; cur = cur.next) {}
818 // the change event handler expects
822 cur.next = changeObj;
819 for (var i = 0; i < lines.length; ++i)
823 } else textChanged = changeObj;
820 if (typeof lines[i] != "string") lines[i] = lines[i].text;
821 var changeObj = {from: from, to: to, text: lines};
822 if (textChanged) {
823 for (var cur = textChanged; cur.next; cur = cur.next) {}
824 cur.next = changeObj;
825 } else textChanged = changeObj;
826 }
824
827
825 // Update the selection
828 // Update the selection
826 function updateLine(n) {return n <= Math.min(to.line, to.line + lendiff) ? n : n + lendiff;}
829 function updateLine(n) {return n <= Math.min(to.line, to.line + lendiff) ? n : n + lendiff;}
827 setSelection(clipPos(selFrom), clipPos(selTo),
830 setSelection(clipPos(selFrom), clipPos(selTo),
828 updateLine(sel.from.line), updateLine(sel.to.line));
831 updateLine(sel.from.line), updateLine(sel.to.line));
829 }
832 }
830
833
831 function updateVerticalScroll(scrollTop) {
834 function needsScrollbar() {
832 var th = textHeight(), virtualHeight = Math.floor(doc.height * th + 2 * paddingTop()), scrollbarHeight = scroller.clientHeight;
835 var realHeight = doc.height * textHeight() + 2 * paddingTop();
833 scrollbar.style.height = scrollbarHeight + "px";
836 return realHeight * .99 > scroller.offsetHeight ? realHeight : false;
834 if (scroller.clientHeight)
835 scrollbarInner.style.height = virtualHeight + "px";
836 // Position the mover div to align with the current virtual scroll position
837 if (scrollTop != null) scrollbar.scrollTop = scrollTop;
838 mover.style.top = (displayOffset * th - scrollbar.scrollTop) + "px";
839 scrollbar.style.display = (virtualHeight > scrollbarHeight) ? "block" : "none";
840 }
837 }
841
842 // On Mac OS X Lion and up, detect whether the mouse is plugged in by measuring
843 // the width of a div with a scrollbar in it. If the width is <= 1, then
844 // the mouse isn't plugged in and scrollbars should overlap the content.
845 function overlapScrollbars() {
846 var tmpSb = document.createElement('div'),
847 tmpSbInner = document.createElement('div');
848 tmpSb.className = "CodeMirror-scrollbar";
849 tmpSb.style.cssText = "position: absolute; left: -9999px; height: 100px;";
850 tmpSbInner.className = "CodeMirror-scrollbar-inner";
851 tmpSbInner.style.height = "200px";
852 tmpSb.appendChild(tmpSbInner);
853
838
854 document.body.appendChild(tmpSb);
839 function updateVerticalScroll(scrollTop) {
855 var result = (tmpSb.offsetWidth <= 1);
840 var scrollHeight = needsScrollbar();
856 document.body.removeChild(tmpSb);
841 scrollbar.style.display = scrollHeight ? "block" : "none";
857 return result;
842 if (scrollHeight) {
843 scrollbarInner.style.height = sizer.style.minHeight = scrollHeight + "px";
844 scrollbar.style.height = scroller.clientHeight + "px";
845 if (scrollTop != null) {
846 scrollbar.scrollTop = scroller.scrollTop = scrollTop;
847 // 'Nudge' the scrollbar to work around a Webkit bug where,
848 // in some situations, we'd end up with a scrollbar that
849 // reported its scrollTop (and looked) as expected, but
850 // *behaved* as if it was still in a previous state (i.e.
851 // couldn't scroll up, even though it appeared to be at the
852 // bottom).
853 if (webkit) setTimeout(function() {
854 if (scrollbar.scrollTop != scrollTop) return;
855 scrollbar.scrollTop = scrollTop + (scrollTop ? -1 : 1);
856 scrollbar.scrollTop = scrollTop;
857 }, 0);
858 }
859 } else {
860 sizer.style.minHeight = "";
861 }
862 // Position the mover div to align with the current virtual scroll position
863 mover.style.top = displayOffset * textHeight() + "px";
858 }
864 }
859
865
860 function computeMaxLength() {
866 function computeMaxLength() {
861 var maxLineLength = 0;
867 maxLine = getLine(0); maxLineChanged = true;
862 maxLine = ""; maxLineChanged = true;
868 var maxLineLength = maxLine.text.length;
863 doc.iter(0, doc.size, function(line) {
869 doc.iter(1, doc.size, function(line) {
864 var l = line.text;
870 var l = line.text;
865 if (!line.hidden && l.length > maxLineLength) {
871 if (!line.hidden && l.length > maxLineLength) {
866 maxLineLength = l.length; maxLine = l;
872 maxLineLength = l.length; maxLine = line;
867 }
873 }
868 });
874 });
869 updateMaxLine = false;
875 updateMaxLine = false;
870 }
876 }
871
877
872 function replaceRange(code, from, to) {
878 function replaceRange(code, from, to) {
873 from = clipPos(from);
879 from = clipPos(from);
874 if (!to) to = from; else to = clipPos(to);
880 if (!to) to = from; else to = clipPos(to);
875 code = splitLines(code);
881 code = splitLines(code);
876 function adjustPos(pos) {
882 function adjustPos(pos) {
877 if (posLess(pos, from)) return pos;
883 if (posLess(pos, from)) return pos;
878 if (!posLess(to, pos)) return end;
884 if (!posLess(to, pos)) return end;
879 var line = pos.line + code.length - (to.line - from.line) - 1;
885 var line = pos.line + code.length - (to.line - from.line) - 1;
880 var ch = pos.ch;
886 var ch = pos.ch;
881 if (pos.line == to.line)
887 if (pos.line == to.line)
882 ch += code[code.length-1].length - (to.ch - (to.line == from.line ? from.ch : 0));
888 ch += lst(code).length - (to.ch - (to.line == from.line ? from.ch : 0));
883 return {line: line, ch: ch};
889 return {line: line, ch: ch};
884 }
890 }
885 var end;
891 var end;
886 replaceRange1(code, from, to, function(end1) {
892 replaceRange1(code, from, to, function(end1) {
887 end = end1;
893 end = end1;
888 return {from: adjustPos(sel.from), to: adjustPos(sel.to)};
894 return {from: adjustPos(sel.from), to: adjustPos(sel.to)};
889 });
895 });
890 return end;
896 return end;
891 }
897 }
892 function replaceSelection(code, collapse) {
898 function replaceSelection(code, collapse) {
893 replaceRange1(splitLines(code), sel.from, sel.to, function(end) {
899 replaceRange1(splitLines(code), sel.from, sel.to, function(end) {
894 if (collapse == "end") return {from: end, to: end};
900 if (collapse == "end") return {from: end, to: end};
895 else if (collapse == "start") return {from: sel.from, to: sel.from};
901 else if (collapse == "start") return {from: sel.from, to: sel.from};
896 else return {from: sel.from, to: end};
902 else return {from: sel.from, to: end};
897 });
903 });
898 }
904 }
899 function replaceRange1(code, from, to, computeSel) {
905 function replaceRange1(code, from, to, computeSel) {
900 var endch = code.length == 1 ? code[0].length + from.ch : code[code.length-1].length;
906 var endch = code.length == 1 ? code[0].length + from.ch : lst(code).length;
901 var newSel = computeSel({line: from.line + code.length - 1, ch: endch});
907 var newSel = computeSel({line: from.line + code.length - 1, ch: endch});
902 updateLines(from, to, code, newSel.from, newSel.to);
908 updateLines(from, to, code, newSel.from, newSel.to);
903 }
909 }
904
910
905 function getRange(from, to) {
911 function getRange(from, to, lineSep) {
906 var l1 = from.line, l2 = to.line;
912 var l1 = from.line, l2 = to.line;
907 if (l1 == l2) return getLine(l1).text.slice(from.ch, to.ch);
913 if (l1 == l2) return getLine(l1).text.slice(from.ch, to.ch);
908 var code = [getLine(l1).text.slice(from.ch)];
914 var code = [getLine(l1).text.slice(from.ch)];
909 doc.iter(l1 + 1, l2, function(line) { code.push(line.text); });
915 doc.iter(l1 + 1, l2, function(line) { code.push(line.text); });
910 code.push(getLine(l2).text.slice(0, to.ch));
916 code.push(getLine(l2).text.slice(0, to.ch));
911 return code.join("\n");
917 return code.join(lineSep || "\n");
912 }
918 }
913 function getSelection() {
919 function getSelection(lineSep) {
914 return getRange(sel.from, sel.to);
920 return getRange(sel.from, sel.to, lineSep);
915 }
921 }
916
922
917 var pollingFast = false; // Ensures slowPoll doesn't cancel fastPoll
918 function slowPoll() {
923 function slowPoll() {
919 if (pollingFast) return;
924 if (pollingFast) return;
920 poll.set(options.pollInterval, function() {
925 poll.set(options.pollInterval, function() {
921 startOperation();
922 readInput();
926 readInput();
923 if (focused) slowPoll();
927 if (focused) slowPoll();
924 endOperation();
925 });
928 });
926 }
929 }
927 function fastPoll() {
930 function fastPoll() {
928 var missed = false;
931 var missed = false;
929 pollingFast = true;
932 pollingFast = true;
930 function p() {
933 function p() {
931 startOperation();
932 var changed = readInput();
934 var changed = readInput();
933 if (!changed && !missed) {missed = true; poll.set(60, p);}
935 if (!changed && !missed) {missed = true; poll.set(60, p);}
934 else {pollingFast = false; slowPoll();}
936 else {pollingFast = false; slowPoll();}
935 endOperation();
936 }
937 }
937 poll.set(20, p);
938 poll.set(20, p);
938 }
939 }
939
940
940 // Previnput is a hack to work with IME. If we reset the textarea
941 // Previnput is a hack to work with IME. If we reset the textarea
941 // on every change, that breaks IME. So we look for changes
942 // on every change, that breaks IME. So we look for changes
942 // compared to the previous content instead. (Modern browsers have
943 // compared to the previous content instead. (Modern browsers have
943 // events that indicate IME taking place, but these are not widely
944 // events that indicate IME taking place, but these are not widely
944 // supported or compatible enough yet to rely on.)
945 // supported or compatible enough yet to rely on.)
945 var prevInput = "";
946 var prevInput = "";
946 function readInput() {
947 function readInput() {
947 if (leaveInputAlone || !focused || hasSelection(input) || options.readOnly) return false;
948 if (!focused || hasSelection(input) || options.readOnly) return false;
948 var text = input.value;
949 var text = input.value;
949 if (text == prevInput) return false;
950 if (text == prevInput) return false;
951 if (!nestedOperation) startOperation();
950 shiftSelecting = null;
952 shiftSelecting = null;
951 var same = 0, l = Math.min(prevInput.length, text.length);
953 var same = 0, l = Math.min(prevInput.length, text.length);
952 while (same < l && prevInput[same] == text[same]) ++same;
954 while (same < l && prevInput[same] == text[same]) ++same;
953 if (same < prevInput.length)
955 if (same < prevInput.length)
954 sel.from = {line: sel.from.line, ch: sel.from.ch - (prevInput.length - same)};
956 sel.from = {line: sel.from.line, ch: sel.from.ch - (prevInput.length - same)};
955 else if (overwrite && posEq(sel.from, sel.to))
957 else if (overwrite && posEq(sel.from, sel.to))
956 sel.to = {line: sel.to.line, ch: Math.min(getLine(sel.to.line).text.length, sel.to.ch + (text.length - same))};
958 sel.to = {line: sel.to.line, ch: Math.min(getLine(sel.to.line).text.length, sel.to.ch + (text.length - same))};
957 replaceSelection(text.slice(same), "end");
959 replaceSelection(text.slice(same), "end");
958 if (text.length > 1000) { input.value = prevInput = ""; }
960 if (text.length > 1000) { input.value = prevInput = ""; }
959 else prevInput = text;
961 else prevInput = text;
962 if (!nestedOperation) endOperation();
960 return true;
963 return true;
961 }
964 }
962 function resetInput(user) {
965 function resetInput(user) {
963 if (!posEq(sel.from, sel.to)) {
966 if (!posEq(sel.from, sel.to)) {
964 prevInput = "";
967 prevInput = "";
965 input.value = getSelection();
968 input.value = getSelection();
966 selectInput(input);
969 if (focused) selectInput(input);
967 } else if (user) prevInput = input.value = "";
970 } else if (user) prevInput = input.value = "";
968 }
971 }
969
972
970 function focusInput() {
973 function focusInput() {
971 if (options.readOnly != "nocursor") input.focus();
974 if (options.readOnly != "nocursor") input.focus();
972 }
975 }
973
976
974 function scrollEditorIntoView() {
975 if (!cursor.getBoundingClientRect) return;
976 var rect = cursor.getBoundingClientRect();
977 // IE returns bogus coordinates when the instance sits inside of an iframe and the cursor is hidden
978 if (ie && rect.top == rect.bottom) return;
979 var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
980 if (rect.top < 0 || rect.bottom > winH) scrollCursorIntoView();
981 }
982 function scrollCursorIntoView() {
977 function scrollCursorIntoView() {
983 var coords = calculateCursorCoords();
978 var coords = calculateCursorCoords();
984 return scrollIntoView(coords.x, coords.y, coords.x, coords.yBot);
979 scrollIntoView(coords.x, coords.y, coords.x, coords.yBot);
980 if (!focused) return;
981 var box = sizer.getBoundingClientRect(), doScroll = null;
982 if (coords.y + box.top < 0) doScroll = true;
983 else if (coords.y + box.top + textHeight() > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
984 if (doScroll != null) {
985 var hidden = cursor.style.display == "none";
986 if (hidden) {
987 cursor.style.display = "";
988 cursor.style.left = coords.x + "px";
989 cursor.style.top = (coords.y - displayOffset) + "px";
990 }
991 cursor.scrollIntoView(doScroll);
992 if (hidden) cursor.style.display = "none";
993 }
985 }
994 }
986 function calculateCursorCoords() {
995 function calculateCursorCoords() {
987 var cursor = localCoords(sel.inverted ? sel.from : sel.to);
996 var cursor = localCoords(sel.inverted ? sel.from : sel.to);
988 var x = options.lineWrapping ? Math.min(cursor.x, lineSpace.offsetWidth) : cursor.x;
997 var x = options.lineWrapping ? Math.min(cursor.x, lineSpace.offsetWidth) : cursor.x;
989 return {x: x, y: cursor.y, yBot: cursor.yBot};
998 return {x: x, y: cursor.y, yBot: cursor.yBot};
990 }
999 }
991 function scrollIntoView(x1, y1, x2, y2) {
1000 function scrollIntoView(x1, y1, x2, y2) {
992 var scrollPos = calculateScrollPos(x1, y1, x2, y2), scrolled = false;
1001 var scrollPos = calculateScrollPos(x1, y1, x2, y2);
993 if (scrollPos.scrollLeft != null) {scroller.scrollLeft = scrollPos.scrollLeft; scrolled = true;}
1002 if (scrollPos.scrollLeft != null) {scroller.scrollLeft = scrollPos.scrollLeft;}
994 if (scrollPos.scrollTop != null) {scrollbar.scrollTop = scrollPos.scrollTop; scrolled = true;}
1003 if (scrollPos.scrollTop != null) {scrollbar.scrollTop = scroller.scrollTop = scrollPos.scrollTop;}
995 if (scrolled && options.onScroll) options.onScroll(instance);
996 }
1004 }
997 function calculateScrollPos(x1, y1, x2, y2) {
1005 function calculateScrollPos(x1, y1, x2, y2) {
998 var pl = paddingLeft(), pt = paddingTop();
1006 var pl = paddingLeft(), pt = paddingTop();
999 y1 += pt; y2 += pt; x1 += pl; x2 += pl;
1007 y1 += pt; y2 += pt; x1 += pl; x2 += pl;
1000 var screen = scroller.clientHeight, screentop = scrollbar.scrollTop, result = {};
1008 var screen = scroller.clientHeight, screentop = scrollbar.scrollTop, result = {};
1001 var atTop = y1 < paddingTop() + 10;
1009 var docBottom = needsScrollbar() || Infinity;
1010 var atTop = y1 < pt + 10, atBottom = y2 + pt > docBottom - 10;
1002 if (y1 < screentop) result.scrollTop = atTop ? 0 : Math.max(0, y1);
1011 if (y1 < screentop) result.scrollTop = atTop ? 0 : Math.max(0, y1);
1003 else if (y2 > screentop + screen) result.scrollTop = y2 - screen;
1012 else if (y2 > screentop + screen) result.scrollTop = (atBottom ? docBottom : y2) - screen;
1004
1013
1005 var screenw = scroller.clientWidth, screenleft = scroller.scrollLeft;
1014 var screenw = scroller.clientWidth, screenleft = scroller.scrollLeft;
1006 var gutterw = options.fixedGutter ? gutter.clientWidth : 0;
1015 var gutterw = options.fixedGutter ? gutter.clientWidth : 0;
1007 var atLeft = x1 < gutterw + pl + 10;
1016 var atLeft = x1 < gutterw + pl + 10;
1008 if (x1 < screenleft + gutterw || atLeft) {
1017 if (x1 < screenleft + gutterw || atLeft) {
1009 if (atLeft) x1 = 0;
1018 if (atLeft) x1 = 0;
1010 result.scrollLeft = Math.max(0, x1 - 10 - gutterw);
1019 result.scrollLeft = Math.max(0, x1 - 10 - gutterw);
1011 } else if (x2 > screenw + screenleft - 3) {
1020 } else if (x2 > screenw + screenleft - 3) {
1012 result.scrollLeft = x2 + 10 - screenw;
1021 result.scrollLeft = x2 + 10 - screenw;
1013 }
1022 }
1014 return result;
1023 return result;
1015 }
1024 }
1016
1025
1017 function visibleLines(scrollTop) {
1026 function visibleLines(scrollTop) {
1018 var lh = textHeight(), top = (scrollTop != null ? scrollTop : scrollbar.scrollTop) - paddingTop();
1027 var lh = textHeight(), top = (scrollTop != null ? scrollTop : scrollbar.scrollTop) - paddingTop();
1019 var fromHeight = Math.max(0, Math.floor(top / lh));
1028 var fromHeight = Math.max(0, Math.floor(top / lh));
1020 var toHeight = Math.ceil((top + scroller.clientHeight) / lh);
1029 var toHeight = Math.ceil((top + scroller.clientHeight) / lh);
1021 return {from: lineAtHeight(doc, fromHeight),
1030 return {from: lineAtHeight(doc, fromHeight),
1022 to: lineAtHeight(doc, toHeight)};
1031 to: lineAtHeight(doc, toHeight)};
1023 }
1032 }
1024 // Uses a set of changes plus the current scroll position to
1033 // Uses a set of changes plus the current scroll position to
1025 // determine which DOM updates have to be made, and makes the
1034 // determine which DOM updates have to be made, and makes the
1026 // updates.
1035 // updates.
1027 function updateDisplay(changes, suppressCallback, scrollTop) {
1036 function updateDisplay(changes, suppressCallback, scrollTop) {
1028 if (!scroller.clientWidth) {
1037 if (!scroller.clientWidth) {
1029 showingFrom = showingTo = displayOffset = 0;
1038 showingFrom = showingTo = displayOffset = 0;
1030 return;
1039 return;
1031 }
1040 }
1032 // Compute the new visible window
1041 // Compute the new visible window
1033 // If scrollTop is specified, use that to determine which lines
1042 // If scrollTop is specified, use that to determine which lines
1034 // to render instead of the current scrollbar position.
1043 // to render instead of the current scrollbar position.
1035 var visible = visibleLines(scrollTop);
1044 var visible = visibleLines(scrollTop);
1036 // Bail out if the visible area is already rendered and nothing changed.
1045 // Bail out if the visible area is already rendered and nothing changed.
1037 if (changes !== true && changes.length == 0 && visible.from > showingFrom && visible.to < showingTo) {
1046 if (changes !== true && changes.length == 0 && visible.from > showingFrom && visible.to < showingTo) {
1038 updateVerticalScroll(scrollTop);
1047 updateVerticalScroll(scrollTop);
1039 return;
1048 return;
1040 }
1049 }
1041 var from = Math.max(visible.from - 100, 0), to = Math.min(doc.size, visible.to + 100);
1050 var from = Math.max(visible.from - 100, 0), to = Math.min(doc.size, visible.to + 100);
1042 if (showingFrom < from && from - showingFrom < 20) from = showingFrom;
1051 if (showingFrom < from && from - showingFrom < 20) from = showingFrom;
1043 if (showingTo > to && showingTo - to < 20) to = Math.min(doc.size, showingTo);
1052 if (showingTo > to && showingTo - to < 20) to = Math.min(doc.size, showingTo);
1044
1053
1045 // Create a range of theoretically intact lines, and punch holes
1054 // Create a range of theoretically intact lines, and punch holes
1046 // in that using the change info.
1055 // in that using the change info.
1047 var intact = changes === true ? [] :
1056 var intact = changes === true ? [] :
1048 computeIntact([{from: showingFrom, to: showingTo, domStart: 0}], changes);
1057 computeIntact([{from: showingFrom, to: showingTo, domStart: 0}], changes);
1049 // Clip off the parts that won't be visible
1058 // Clip off the parts that won't be visible
1050 var intactLines = 0;
1059 var intactLines = 0;
1051 for (var i = 0; i < intact.length; ++i) {
1060 for (var i = 0; i < intact.length; ++i) {
1052 var range = intact[i];
1061 var range = intact[i];
1053 if (range.from < from) {range.domStart += (from - range.from); range.from = from;}
1062 if (range.from < from) {range.domStart += (from - range.from); range.from = from;}
1054 if (range.to > to) range.to = to;
1063 if (range.to > to) range.to = to;
1055 if (range.from >= range.to) intact.splice(i--, 1);
1064 if (range.from >= range.to) intact.splice(i--, 1);
1056 else intactLines += range.to - range.from;
1065 else intactLines += range.to - range.from;
1057 }
1066 }
1058 if (intactLines == to - from && from == showingFrom && to == showingTo) {
1067 if (intactLines == to - from && from == showingFrom && to == showingTo) {
1059 updateVerticalScroll(scrollTop);
1068 updateVerticalScroll(scrollTop);
1060 return;
1069 return;
1061 }
1070 }
1062 intact.sort(function(a, b) {return a.domStart - b.domStart;});
1071 intact.sort(function(a, b) {return a.domStart - b.domStart;});
1063
1072
1064 var th = textHeight(), gutterDisplay = gutter.style.display;
1073 var th = textHeight(), gutterDisplay = gutter.style.display;
1065 lineDiv.style.display = "none";
1074 lineDiv.style.display = "none";
1066 patchDisplay(from, to, intact);
1075 patchDisplay(from, to, intact);
1067 lineDiv.style.display = gutter.style.display = "";
1076 lineDiv.style.display = gutter.style.display = "";
1068
1077
1069 var different = from != showingFrom || to != showingTo || lastSizeC != scroller.clientHeight + th;
1078 var different = from != showingFrom || to != showingTo || lastSizeC != scroller.clientHeight + th;
1070 // This is just a bogus formula that detects when the editor is
1079 // This is just a bogus formula that detects when the editor is
1071 // resized or the font size changes.
1080 // resized or the font size changes.
1072 if (different) lastSizeC = scroller.clientHeight + th;
1081 if (different) lastSizeC = scroller.clientHeight + th;
1082 if (from != showingFrom || to != showingTo && options.onViewportChange)
1083 setTimeout(function(){
1084 if (options.onViewportChange) options.onViewportChange(instance, from, to);
1085 });
1073 showingFrom = from; showingTo = to;
1086 showingFrom = from; showingTo = to;
1074 displayOffset = heightAtLine(doc, from);
1087 displayOffset = heightAtLine(doc, from);
1088 startWorker(100);
1075
1089
1076 // Since this is all rather error prone, it is honoured with the
1090 // Since this is all rather error prone, it is honoured with the
1077 // only assertion in the whole file.
1091 // only assertion in the whole file.
1078 if (lineDiv.childNodes.length != showingTo - showingFrom)
1092 if (lineDiv.childNodes.length != showingTo - showingFrom)
1079 throw new Error("BAD PATCH! " + JSON.stringify(intact) + " size=" + (showingTo - showingFrom) +
1093 throw new Error("BAD PATCH! " + JSON.stringify(intact) + " size=" + (showingTo - showingFrom) +
1080 " nodes=" + lineDiv.childNodes.length);
1094 " nodes=" + lineDiv.childNodes.length);
1081
1095
1082 function checkHeights() {
1096 function checkHeights() {
1083 var curNode = lineDiv.firstChild, heightChanged = false;
1097 var curNode = lineDiv.firstChild, heightChanged = false;
1084 doc.iter(showingFrom, showingTo, function(line) {
1098 doc.iter(showingFrom, showingTo, function(line) {
1099 // Work around bizarro IE7 bug where, sometimes, our curNode
1100 // is magically replaced with a new node in the DOM, leaving
1101 // us with a reference to an orphan (nextSibling-less) node.
1102 if (!curNode) return;
1085 if (!line.hidden) {
1103 if (!line.hidden) {
1086 var height = Math.round(curNode.offsetHeight / th) || 1;
1104 var height = Math.round(curNode.offsetHeight / th) || 1;
1087 if (line.height != height) {
1105 if (line.height != height) {
1088 updateLineHeight(line, height);
1106 updateLineHeight(line, height);
1089 gutterDirty = heightChanged = true;
1107 gutterDirty = heightChanged = true;
1090 }
1108 }
1091 }
1109 }
1092 curNode = curNode.nextSibling;
1110 curNode = curNode.nextSibling;
1093 });
1111 });
1094 return heightChanged;
1112 return heightChanged;
1095 }
1113 }
1096
1114
1097 if (options.lineWrapping) {
1115 if (options.lineWrapping) checkHeights();
1098 // Guess whether we're going to need the scrollbar, so that we don't end up changing the linewrapping
1099 // after the scrollbar appears (during updateVerticalScroll()). Only do this if the scrollbar is
1100 // appearing (if it's disappearing, we don't have to worry about the scroll position, and there are
1101 // issues on IE7 if we turn it off too early).
1102 var virtualHeight = Math.floor(doc.height * th + 2 * paddingTop()), scrollbarHeight = scroller.clientHeight;
1103 if (virtualHeight > scrollbarHeight) scrollbar.style.display = "block";
1104 checkHeights();
1105 }
1106
1116
1107 gutter.style.display = gutterDisplay;
1117 gutter.style.display = gutterDisplay;
1108 if (different || gutterDirty) {
1118 if (different || gutterDirty) {
1109 // If the gutter grew in size, re-check heights. If those changed, re-draw gutter.
1119 // If the gutter grew in size, re-check heights. If those changed, re-draw gutter.
1110 updateGutter() && options.lineWrapping && checkHeights() && updateGutter();
1120 updateGutter() && options.lineWrapping && checkHeights() && updateGutter();
1111 }
1121 }
1122 updateVerticalScroll(scrollTop);
1112 updateSelection();
1123 updateSelection();
1113 updateVerticalScroll(scrollTop);
1114 if (!suppressCallback && options.onUpdate) options.onUpdate(instance);
1124 if (!suppressCallback && options.onUpdate) options.onUpdate(instance);
1115 return true;
1125 return true;
1116 }
1126 }
1117
1127
1118 function computeIntact(intact, changes) {
1128 function computeIntact(intact, changes) {
1119 for (var i = 0, l = changes.length || 0; i < l; ++i) {
1129 for (var i = 0, l = changes.length || 0; i < l; ++i) {
1120 var change = changes[i], intact2 = [], diff = change.diff || 0;
1130 var change = changes[i], intact2 = [], diff = change.diff || 0;
1121 for (var j = 0, l2 = intact.length; j < l2; ++j) {
1131 for (var j = 0, l2 = intact.length; j < l2; ++j) {
1122 var range = intact[j];
1132 var range = intact[j];
1123 if (change.to <= range.from && change.diff)
1133 if (change.to <= range.from && change.diff)
1124 intact2.push({from: range.from + diff, to: range.to + diff,
1134 intact2.push({from: range.from + diff, to: range.to + diff,
1125 domStart: range.domStart});
1135 domStart: range.domStart});
1126 else if (change.to <= range.from || change.from >= range.to)
1136 else if (change.to <= range.from || change.from >= range.to)
1127 intact2.push(range);
1137 intact2.push(range);
1128 else {
1138 else {
1129 if (change.from > range.from)
1139 if (change.from > range.from)
1130 intact2.push({from: range.from, to: change.from, domStart: range.domStart});
1140 intact2.push({from: range.from, to: change.from, domStart: range.domStart});
1131 if (change.to < range.to)
1141 if (change.to < range.to)
1132 intact2.push({from: change.to + diff, to: range.to + diff,
1142 intact2.push({from: change.to + diff, to: range.to + diff,
1133 domStart: range.domStart + (change.to - range.from)});
1143 domStart: range.domStart + (change.to - range.from)});
1134 }
1144 }
1135 }
1145 }
1136 intact = intact2;
1146 intact = intact2;
1137 }
1147 }
1138 return intact;
1148 return intact;
1139 }
1149 }
1140
1150
1141 function patchDisplay(from, to, intact) {
1151 function patchDisplay(from, to, intact) {
1152 function killNode(node) {
1153 var tmp = node.nextSibling;
1154 node.parentNode.removeChild(node);
1155 return tmp;
1156 }
1142 // The first pass removes the DOM nodes that aren't intact.
1157 // The first pass removes the DOM nodes that aren't intact.
1143 if (!intact.length) lineDiv.innerHTML = "";
1158 if (!intact.length) removeChildren(lineDiv);
1144 else {
1159 else {
1145 function killNode(node) {
1146 var tmp = node.nextSibling;
1147 node.parentNode.removeChild(node);
1148 return tmp;
1149 }
1150 var domPos = 0, curNode = lineDiv.firstChild, n;
1160 var domPos = 0, curNode = lineDiv.firstChild, n;
1151 for (var i = 0; i < intact.length; ++i) {
1161 for (var i = 0; i < intact.length; ++i) {
1152 var cur = intact[i];
1162 var cur = intact[i];
1153 while (cur.domStart > domPos) {curNode = killNode(curNode); domPos++;}
1163 while (cur.domStart > domPos) {curNode = killNode(curNode); domPos++;}
1154 for (var j = 0, e = cur.to - cur.from; j < e; ++j) {curNode = curNode.nextSibling; domPos++;}
1164 for (var j = 0, e = cur.to - cur.from; j < e; ++j) {curNode = curNode.nextSibling; domPos++;}
1155 }
1165 }
1156 while (curNode) curNode = killNode(curNode);
1166 while (curNode) curNode = killNode(curNode);
1157 }
1167 }
1158 // This pass fills in the lines that actually changed.
1168 // This pass fills in the lines that actually changed.
1159 var nextIntact = intact.shift(), curNode = lineDiv.firstChild, j = from;
1169 var nextIntact = intact.shift(), curNode = lineDiv.firstChild, j = from;
1160 var scratch = document.createElement("div");
1161 doc.iter(from, to, function(line) {
1170 doc.iter(from, to, function(line) {
1162 if (nextIntact && nextIntact.to == j) nextIntact = intact.shift();
1171 if (nextIntact && nextIntact.to == j) nextIntact = intact.shift();
1163 if (!nextIntact || nextIntact.from > j) {
1172 if (!nextIntact || nextIntact.from > j) {
1164 if (line.hidden) var html = scratch.innerHTML = "<pre></pre>";
1173 if (line.hidden) var lineElement = elt("pre");
1165 else {
1174 else {
1166 var html = '<pre' + (line.className ? ' class="' + line.className + '"' : '') + '>'
1175 var lineElement = lineContent(line);
1167 + line.getHTML(makeTab) + '</pre>';
1176 if (line.className) lineElement.className = line.className;
1168 // Kludge to make sure the styled element lies behind the selection (by z-index)
1177 // Kludge to make sure the styled element lies behind the selection (by z-index)
1169 if (line.bgClassName)
1178 if (line.bgClassName) {
1170 html = '<div style="position: relative"><pre class="' + line.bgClassName +
1179 var pre = elt("pre", "\u00a0", line.bgClassName, "position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: -2");
1171 '" style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: -2">&#160;</pre>' + html + "</div>";
1180 lineElement = elt("div", [pre, lineElement], null, "position: relative");
1181 }
1172 }
1182 }
1173 scratch.innerHTML = html;
1183 lineDiv.insertBefore(lineElement, curNode);
1174 lineDiv.insertBefore(scratch.firstChild, curNode);
1175 } else {
1184 } else {
1176 curNode = curNode.nextSibling;
1185 curNode = curNode.nextSibling;
1177 }
1186 }
1178 ++j;
1187 ++j;
1179 });
1188 });
1180 }
1189 }
1181
1190
1182 function updateGutter() {
1191 function updateGutter() {
1183 if (!options.gutter && !options.lineNumbers) return;
1192 if (!options.gutter && !options.lineNumbers) return;
1184 var hText = mover.offsetHeight, hEditor = scroller.clientHeight;
1193 var hText = mover.offsetHeight, hEditor = scroller.clientHeight;
1185 gutter.style.height = (hText - hEditor < 2 ? hEditor : hText) + "px";
1194 gutter.style.height = (hText - hEditor < 2 ? hEditor : hText) + "px";
1186 var html = [], i = showingFrom, normalNode;
1195 var fragment = document.createDocumentFragment(), i = showingFrom, normalNode;
1187 doc.iter(showingFrom, Math.max(showingTo, showingFrom + 1), function(line) {
1196 doc.iter(showingFrom, Math.max(showingTo, showingFrom + 1), function(line) {
1188 if (line.hidden) {
1197 if (line.hidden) {
1189 html.push("<pre></pre>");
1198 fragment.appendChild(elt("pre"));
1190 } else {
1199 } else {
1191 var marker = line.gutterMarker;
1200 var marker = line.gutterMarker;
1192 var text = options.lineNumbers ? i + options.firstLineNumber : null;
1201 var text = options.lineNumbers ? options.lineNumberFormatter(i + options.firstLineNumber) : null;
1193 if (marker && marker.text)
1202 if (marker && marker.text)
1194 text = marker.text.replace("%N%", text != null ? text : "");
1203 text = marker.text.replace("%N%", text != null ? text : "");
1195 else if (text == null)
1204 else if (text == null)
1196 text = "\u00a0";
1205 text = "\u00a0";
1197 html.push((marker && marker.style ? '<pre class="' + marker.style + '">' : "<pre>"), text);
1206 var markerElement = fragment.appendChild(elt("pre", null, marker && marker.style));
1198 for (var j = 1; j < line.height; ++j) html.push("<br/>&#160;");
1207 markerElement.innerHTML = text;
1199 html.push("</pre>");
1208 for (var j = 1; j < line.height; ++j) {
1209 markerElement.appendChild(elt("br"));
1210 markerElement.appendChild(document.createTextNode("\u00a0"));
1211 }
1200 if (!marker) normalNode = i;
1212 if (!marker) normalNode = i;
1201 }
1213 }
1202 ++i;
1214 ++i;
1203 });
1215 });
1204 gutter.style.display = "none";
1216 gutter.style.display = "none";
1205 gutterText.innerHTML = html.join("");
1217 removeChildrenAndAdd(gutterText, fragment);
1206 // Make sure scrolling doesn't cause number gutter size to pop
1218 // Make sure scrolling doesn't cause number gutter size to pop
1207 if (normalNode != null && options.lineNumbers) {
1219 if (normalNode != null && options.lineNumbers) {
1208 var node = gutterText.childNodes[normalNode - showingFrom];
1220 var node = gutterText.childNodes[normalNode - showingFrom];
1209 var minwidth = String(doc.size).length, val = eltText(node.firstChild), pad = "";
1221 var minwidth = String(doc.size).length, val = eltText(node.firstChild), pad = "";
1210 while (val.length + pad.length < minwidth) pad += "\u00a0";
1222 while (val.length + pad.length < minwidth) pad += "\u00a0";
1211 if (pad) node.insertBefore(document.createTextNode(pad), node.firstChild);
1223 if (pad) node.insertBefore(document.createTextNode(pad), node.firstChild);
1212 }
1224 }
1213 gutter.style.display = "";
1225 gutter.style.display = "";
1214 var resized = Math.abs((parseInt(lineSpace.style.marginLeft) || 0) - gutter.offsetWidth) > 2;
1226 var resized = Math.abs((parseInt(lineSpace.style.marginLeft) || 0) - gutter.offsetWidth) > 2;
1215 lineSpace.style.marginLeft = gutter.offsetWidth + "px";
1227 lineSpace.style.marginLeft = gutter.offsetWidth + "px";
1216 gutterDirty = false;
1228 gutterDirty = false;
1217 return resized;
1229 return resized;
1218 }
1230 }
1219 function updateSelection() {
1231 function updateSelection() {
1220 var collapsed = posEq(sel.from, sel.to);
1232 var collapsed = posEq(sel.from, sel.to);
1221 var fromPos = localCoords(sel.from, true);
1233 var fromPos = localCoords(sel.from, true);
1222 var toPos = collapsed ? fromPos : localCoords(sel.to, true);
1234 var toPos = collapsed ? fromPos : localCoords(sel.to, true);
1223 var headPos = sel.inverted ? fromPos : toPos, th = textHeight();
1235 var headPos = sel.inverted ? fromPos : toPos, th = textHeight();
1224 var wrapOff = eltOffset(wrapper), lineOff = eltOffset(lineDiv);
1236 var wrapOff = eltOffset(wrapper), lineOff = eltOffset(lineDiv);
1225 inputDiv.style.top = Math.max(0, Math.min(scroller.offsetHeight, headPos.y + lineOff.top - wrapOff.top)) + "px";
1237 inputDiv.style.top = Math.max(0, Math.min(scroller.offsetHeight, headPos.y + lineOff.top - wrapOff.top)) + "px";
1226 inputDiv.style.left = Math.max(0, Math.min(scroller.offsetWidth, headPos.x + lineOff.left - wrapOff.left)) + "px";
1238 inputDiv.style.left = Math.max(0, Math.min(scroller.offsetWidth, headPos.x + lineOff.left - wrapOff.left)) + "px";
1227 if (collapsed) {
1239 if (collapsed) {
1228 cursor.style.top = headPos.y + "px";
1240 cursor.style.top = headPos.y + "px";
1229 cursor.style.left = (options.lineWrapping ? Math.min(headPos.x, lineSpace.offsetWidth) : headPos.x) + "px";
1241 cursor.style.left = (options.lineWrapping ? Math.min(headPos.x, lineSpace.offsetWidth) : headPos.x) + "px";
1230 cursor.style.display = "";
1242 cursor.style.display = "";
1231 selectionDiv.style.display = "none";
1243 selectionDiv.style.display = "none";
1232 } else {
1244 } else {
1233 var sameLine = fromPos.y == toPos.y, html = "";
1245 var sameLine = fromPos.y == toPos.y, fragment = document.createDocumentFragment();
1234 var clientWidth = lineSpace.clientWidth || lineSpace.offsetWidth;
1246 var clientWidth = lineSpace.clientWidth || lineSpace.offsetWidth;
1235 var clientHeight = lineSpace.clientHeight || lineSpace.offsetHeight;
1247 var clientHeight = lineSpace.clientHeight || lineSpace.offsetHeight;
1236 function add(left, top, right, height) {
1248 var add = function(left, top, right, height) {
1237 var rstyle = quirksMode ? "width: " + (!right ? clientWidth : clientWidth - right - left) + "px"
1249 var rstyle = quirksMode ? "width: " + (!right ? clientWidth : clientWidth - right - left) + "px"
1238 : "right: " + right + "px";
1250 : "right: " + right + "px";
1239 html += '<div class="CodeMirror-selected" style="position: absolute; left: ' + left +
1251 fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
1240 'px; top: ' + top + 'px; ' + rstyle + '; height: ' + height + 'px"></div>';
1252 "px; top: " + top + "px; " + rstyle + "; height: " + height + "px"));
1241 }
1253 };
1242 if (sel.from.ch && fromPos.y >= 0) {
1254 if (sel.from.ch && fromPos.y >= 0) {
1243 var right = sameLine ? clientWidth - toPos.x : 0;
1255 var right = sameLine ? clientWidth - toPos.x : 0;
1244 add(fromPos.x, fromPos.y, right, th);
1256 add(fromPos.x, fromPos.y, right, th);
1245 }
1257 }
1246 var middleStart = Math.max(0, fromPos.y + (sel.from.ch ? th : 0));
1258 var middleStart = Math.max(0, fromPos.y + (sel.from.ch ? th : 0));
1247 var middleHeight = Math.min(toPos.y, clientHeight) - middleStart;
1259 var middleHeight = Math.min(toPos.y, clientHeight) - middleStart;
1248 if (middleHeight > 0.2 * th)
1260 if (middleHeight > 0.2 * th)
1249 add(0, middleStart, 0, middleHeight);
1261 add(0, middleStart, 0, middleHeight);
1250 if ((!sameLine || !sel.from.ch) && toPos.y < clientHeight - .5 * th)
1262 if ((!sameLine || !sel.from.ch) && toPos.y < clientHeight - .5 * th)
1251 add(0, toPos.y, clientWidth - toPos.x, th);
1263 add(0, toPos.y, clientWidth - toPos.x, th);
1252 selectionDiv.innerHTML = html;
1264 removeChildrenAndAdd(selectionDiv, fragment);
1253 cursor.style.display = "none";
1265 cursor.style.display = "none";
1254 selectionDiv.style.display = "";
1266 selectionDiv.style.display = "";
1255 }
1267 }
1256 }
1268 }
1257
1269
1258 function setShift(val) {
1270 function setShift(val) {
1259 if (val) shiftSelecting = shiftSelecting || (sel.inverted ? sel.to : sel.from);
1271 if (val) shiftSelecting = shiftSelecting || (sel.inverted ? sel.to : sel.from);
1260 else shiftSelecting = null;
1272 else shiftSelecting = null;
1261 }
1273 }
1262 function setSelectionUser(from, to) {
1274 function setSelectionUser(from, to) {
1263 var sh = shiftSelecting && clipPos(shiftSelecting);
1275 var sh = shiftSelecting && clipPos(shiftSelecting);
1264 if (sh) {
1276 if (sh) {
1265 if (posLess(sh, from)) from = sh;
1277 if (posLess(sh, from)) from = sh;
1266 else if (posLess(to, sh)) to = sh;
1278 else if (posLess(to, sh)) to = sh;
1267 }
1279 }
1268 setSelection(from, to);
1280 setSelection(from, to);
1269 userSelChange = true;
1281 userSelChange = true;
1270 }
1282 }
1271 // Update the selection. Last two args are only used by
1283 // Update the selection. Last two args are only used by
1272 // updateLines, since they have to be expressed in the line
1284 // updateLines, since they have to be expressed in the line
1273 // numbers before the update.
1285 // numbers before the update.
1274 function setSelection(from, to, oldFrom, oldTo) {
1286 function setSelection(from, to, oldFrom, oldTo) {
1275 goalColumn = null;
1287 goalColumn = null;
1276 if (oldFrom == null) {oldFrom = sel.from.line; oldTo = sel.to.line;}
1288 if (oldFrom == null) {oldFrom = sel.from.line; oldTo = sel.to.line;}
1277 if (posEq(sel.from, from) && posEq(sel.to, to)) return;
1289 if (posEq(sel.from, from) && posEq(sel.to, to)) return;
1278 if (posLess(to, from)) {var tmp = to; to = from; from = tmp;}
1290 if (posLess(to, from)) {var tmp = to; to = from; from = tmp;}
1279
1291
1280 // Skip over hidden lines.
1292 // Skip over hidden lines.
1281 if (from.line != oldFrom) {
1293 if (from.line != oldFrom) {
1282 var from1 = skipHidden(from, oldFrom, sel.from.ch);
1294 var from1 = skipHidden(from, oldFrom, sel.from.ch);
1283 // If there is no non-hidden line left, force visibility on current line
1295 // If there is no non-hidden line left, force visibility on current line
1284 if (!from1) setLineHidden(from.line, false);
1296 if (!from1) setLineHidden(from.line, false);
1285 else from = from1;
1297 else from = from1;
1286 }
1298 }
1287 if (to.line != oldTo) to = skipHidden(to, oldTo, sel.to.ch);
1299 if (to.line != oldTo) to = skipHidden(to, oldTo, sel.to.ch);
1288
1300
1289 if (posEq(from, to)) sel.inverted = false;
1301 if (posEq(from, to)) sel.inverted = false;
1290 else if (posEq(from, sel.to)) sel.inverted = false;
1302 else if (posEq(from, sel.to)) sel.inverted = false;
1291 else if (posEq(to, sel.from)) sel.inverted = true;
1303 else if (posEq(to, sel.from)) sel.inverted = true;
1292
1304
1293 if (options.autoClearEmptyLines && posEq(sel.from, sel.to)) {
1305 if (options.autoClearEmptyLines && posEq(sel.from, sel.to)) {
1294 var head = sel.inverted ? from : to;
1306 var head = sel.inverted ? from : to;
1295 if (head.line != sel.from.line && sel.from.line < doc.size) {
1307 if (head.line != sel.from.line && sel.from.line < doc.size) {
1296 var oldLine = getLine(sel.from.line);
1308 var oldLine = getLine(sel.from.line);
1297 if (/^\s+$/.test(oldLine.text))
1309 if (/^\s+$/.test(oldLine.text))
1298 setTimeout(operation(function() {
1310 setTimeout(operation(function() {
1299 if (oldLine.parent && /^\s+$/.test(oldLine.text)) {
1311 if (oldLine.parent && /^\s+$/.test(oldLine.text)) {
1300 var no = lineNo(oldLine);
1312 var no = lineNo(oldLine);
1301 replaceRange("", {line: no, ch: 0}, {line: no, ch: oldLine.text.length});
1313 replaceRange("", {line: no, ch: 0}, {line: no, ch: oldLine.text.length});
1302 }
1314 }
1303 }, 10));
1315 }, 10));
1304 }
1316 }
1305 }
1317 }
1306
1318
1307 sel.from = from; sel.to = to;
1319 sel.from = from; sel.to = to;
1308 selectionChanged = true;
1320 selectionChanged = true;
1309 }
1321 }
1310 function skipHidden(pos, oldLine, oldCh) {
1322 function skipHidden(pos, oldLine, oldCh) {
1311 function getNonHidden(dir) {
1323 function getNonHidden(dir) {
1312 var lNo = pos.line + dir, end = dir == 1 ? doc.size : -1;
1324 var lNo = pos.line + dir, end = dir == 1 ? doc.size : -1;
1313 while (lNo != end) {
1325 while (lNo != end) {
1314 var line = getLine(lNo);
1326 var line = getLine(lNo);
1315 if (!line.hidden) {
1327 if (!line.hidden) {
1316 var ch = pos.ch;
1328 var ch = pos.ch;
1317 if (toEnd || ch > oldCh || ch > line.text.length) ch = line.text.length;
1329 if (toEnd || ch > oldCh || ch > line.text.length) ch = line.text.length;
1318 return {line: lNo, ch: ch};
1330 return {line: lNo, ch: ch};
1319 }
1331 }
1320 lNo += dir;
1332 lNo += dir;
1321 }
1333 }
1322 }
1334 }
1323 var line = getLine(pos.line);
1335 var line = getLine(pos.line);
1324 var toEnd = pos.ch == line.text.length && pos.ch != oldCh;
1336 var toEnd = pos.ch == line.text.length && pos.ch != oldCh;
1325 if (!line.hidden) return pos;
1337 if (!line.hidden) return pos;
1326 if (pos.line >= oldLine) return getNonHidden(1) || getNonHidden(-1);
1338 if (pos.line >= oldLine) return getNonHidden(1) || getNonHidden(-1);
1327 else return getNonHidden(-1) || getNonHidden(1);
1339 else return getNonHidden(-1) || getNonHidden(1);
1328 }
1340 }
1329 function setCursor(line, ch, user) {
1341 function setCursor(line, ch, user) {
1330 var pos = clipPos({line: line, ch: ch || 0});
1342 var pos = clipPos({line: line, ch: ch || 0});
1331 (user ? setSelectionUser : setSelection)(pos, pos);
1343 (user ? setSelectionUser : setSelection)(pos, pos);
1332 }
1344 }
1333
1345
1334 function clipLine(n) {return Math.max(0, Math.min(n, doc.size-1));}
1346 function clipLine(n) {return Math.max(0, Math.min(n, doc.size-1));}
1335 function clipPos(pos) {
1347 function clipPos(pos) {
1336 if (pos.line < 0) return {line: 0, ch: 0};
1348 if (pos.line < 0) return {line: 0, ch: 0};
1337 if (pos.line >= doc.size) return {line: doc.size-1, ch: getLine(doc.size-1).text.length};
1349 if (pos.line >= doc.size) return {line: doc.size-1, ch: getLine(doc.size-1).text.length};
1338 var ch = pos.ch, linelen = getLine(pos.line).text.length;
1350 var ch = pos.ch, linelen = getLine(pos.line).text.length;
1339 if (ch == null || ch > linelen) return {line: pos.line, ch: linelen};
1351 if (ch == null || ch > linelen) return {line: pos.line, ch: linelen};
1340 else if (ch < 0) return {line: pos.line, ch: 0};
1352 else if (ch < 0) return {line: pos.line, ch: 0};
1341 else return pos;
1353 else return pos;
1342 }
1354 }
1343
1355
1344 function findPosH(dir, unit) {
1356 function findPosH(dir, unit) {
1345 var end = sel.inverted ? sel.from : sel.to, line = end.line, ch = end.ch;
1357 var end = sel.inverted ? sel.from : sel.to, line = end.line, ch = end.ch;
1346 var lineObj = getLine(line);
1358 var lineObj = getLine(line);
1347 function findNextLine() {
1359 function findNextLine() {
1348 for (var l = line + dir, e = dir < 0 ? -1 : doc.size; l != e; l += dir) {
1360 for (var l = line + dir, e = dir < 0 ? -1 : doc.size; l != e; l += dir) {
1349 var lo = getLine(l);
1361 var lo = getLine(l);
1350 if (!lo.hidden) { line = l; lineObj = lo; return true; }
1362 if (!lo.hidden) { line = l; lineObj = lo; return true; }
1351 }
1363 }
1352 }
1364 }
1353 function moveOnce(boundToLine) {
1365 function moveOnce(boundToLine) {
1354 if (ch == (dir < 0 ? 0 : lineObj.text.length)) {
1366 if (ch == (dir < 0 ? 0 : lineObj.text.length)) {
1355 if (!boundToLine && findNextLine()) ch = dir < 0 ? lineObj.text.length : 0;
1367 if (!boundToLine && findNextLine()) ch = dir < 0 ? lineObj.text.length : 0;
1356 else return false;
1368 else return false;
1357 } else ch += dir;
1369 } else ch += dir;
1358 return true;
1370 return true;
1359 }
1371 }
1360 if (unit == "char") moveOnce();
1372 if (unit == "char") moveOnce();
1361 else if (unit == "column") moveOnce(true);
1373 else if (unit == "column") moveOnce(true);
1362 else if (unit == "word") {
1374 else if (unit == "word") {
1363 var sawWord = false;
1375 var sawWord = false;
1364 for (;;) {
1376 for (;;) {
1365 if (dir < 0) if (!moveOnce()) break;
1377 if (dir < 0) if (!moveOnce()) break;
1366 if (isWordChar(lineObj.text.charAt(ch))) sawWord = true;
1378 if (isWordChar(lineObj.text.charAt(ch))) sawWord = true;
1367 else if (sawWord) {if (dir < 0) {dir = 1; moveOnce();} break;}
1379 else if (sawWord) {if (dir < 0) {dir = 1; moveOnce();} break;}
1368 if (dir > 0) if (!moveOnce()) break;
1380 if (dir > 0) if (!moveOnce()) break;
1369 }
1381 }
1370 }
1382 }
1371 return {line: line, ch: ch};
1383 return {line: line, ch: ch};
1372 }
1384 }
1373 function moveH(dir, unit) {
1385 function moveH(dir, unit) {
1374 var pos = dir < 0 ? sel.from : sel.to;
1386 var pos = dir < 0 ? sel.from : sel.to;
1375 if (shiftSelecting || posEq(sel.from, sel.to)) pos = findPosH(dir, unit);
1387 if (shiftSelecting || posEq(sel.from, sel.to)) pos = findPosH(dir, unit);
1376 setCursor(pos.line, pos.ch, true);
1388 setCursor(pos.line, pos.ch, true);
1377 }
1389 }
1378 function deleteH(dir, unit) {
1390 function deleteH(dir, unit) {
1379 if (!posEq(sel.from, sel.to)) replaceRange("", sel.from, sel.to);
1391 if (!posEq(sel.from, sel.to)) replaceRange("", sel.from, sel.to);
1380 else if (dir < 0) replaceRange("", findPosH(dir, unit), sel.to);
1392 else if (dir < 0) replaceRange("", findPosH(dir, unit), sel.to);
1381 else replaceRange("", sel.from, findPosH(dir, unit));
1393 else replaceRange("", sel.from, findPosH(dir, unit));
1382 userSelChange = true;
1394 userSelChange = true;
1383 }
1395 }
1384 var goalColumn = null;
1385 function moveV(dir, unit) {
1396 function moveV(dir, unit) {
1386 var dist = 0, pos = localCoords(sel.inverted ? sel.from : sel.to, true);
1397 var dist = 0, pos = localCoords(sel.inverted ? sel.from : sel.to, true);
1387 if (goalColumn != null) pos.x = goalColumn;
1398 if (goalColumn != null) pos.x = goalColumn;
1388 if (unit == "page") dist = Math.min(scroller.clientHeight, window.innerHeight || document.documentElement.clientHeight);
1399 if (unit == "page") {
1389 else if (unit == "line") dist = textHeight();
1400 var screen = Math.min(scroller.clientHeight, window.innerHeight || document.documentElement.clientHeight);
1390 var target = coordsChar(pos.x, pos.y + dist * dir + 2);
1401 var target = coordsChar(pos.x, pos.y + screen * dir);
1402 } else if (unit == "line") {
1403 var th = textHeight();
1404 var target = coordsChar(pos.x, pos.y + .5 * th + dir * th);
1405 }
1391 if (unit == "page") scrollbar.scrollTop += localCoords(target, true).y - pos.y;
1406 if (unit == "page") scrollbar.scrollTop += localCoords(target, true).y - pos.y;
1392 setCursor(target.line, target.ch, true);
1407 setCursor(target.line, target.ch, true);
1393 goalColumn = pos.x;
1408 goalColumn = pos.x;
1394 }
1409 }
1395
1410
1396 function selectWordAt(pos) {
1411 function findWordAt(pos) {
1397 var line = getLine(pos.line).text;
1412 var line = getLine(pos.line).text;
1398 var start = pos.ch, end = pos.ch;
1413 var start = pos.ch, end = pos.ch;
1399 while (start > 0 && isWordChar(line.charAt(start - 1))) --start;
1414 if (line) {
1400 while (end < line.length && isWordChar(line.charAt(end))) ++end;
1415 if (pos.after === false || end == line.length) --start; else ++end;
1401 setSelectionUser({line: pos.line, ch: start}, {line: pos.line, ch: end});
1416 var startChar = line.charAt(start);
1417 var check = isWordChar(startChar) ? isWordChar :
1418 /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} :
1419 function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
1420 while (start > 0 && check(line.charAt(start - 1))) --start;
1421 while (end < line.length && check(line.charAt(end))) ++end;
1422 }
1423 return {from: {line: pos.line, ch: start}, to: {line: pos.line, ch: end}};
1402 }
1424 }
1403 function selectLine(line) {
1425 function selectLine(line) {
1404 setSelectionUser({line: line, ch: 0}, clipPos({line: line + 1, ch: 0}));
1426 setSelectionUser({line: line, ch: 0}, clipPos({line: line + 1, ch: 0}));
1405 }
1427 }
1406 function indentSelected(mode) {
1428 function indentSelected(mode) {
1407 if (posEq(sel.from, sel.to)) return indentLine(sel.from.line, mode);
1429 if (posEq(sel.from, sel.to)) return indentLine(sel.from.line, mode);
1408 var e = sel.to.line - (sel.to.ch ? 0 : 1);
1430 var e = sel.to.line - (sel.to.ch ? 0 : 1);
1409 for (var i = sel.from.line; i <= e; ++i) indentLine(i, mode);
1431 for (var i = sel.from.line; i <= e; ++i) indentLine(i, mode);
1410 }
1432 }
1411
1433
1412 function indentLine(n, how) {
1434 function indentLine(n, how) {
1413 if (!how) how = "add";
1435 if (!how) how = "add";
1414 if (how == "smart") {
1436 if (how == "smart") {
1415 if (!mode.indent) how = "prev";
1437 if (!mode.indent) how = "prev";
1416 else var state = getStateBefore(n);
1438 else var state = getStateBefore(n);
1417 }
1439 }
1418
1440
1419 var line = getLine(n), curSpace = line.indentation(options.tabSize),
1441 var line = getLine(n), curSpace = line.indentation(options.tabSize),
1420 curSpaceString = line.text.match(/^\s*/)[0], indentation;
1442 curSpaceString = line.text.match(/^\s*/)[0], indentation;
1421 if (how == "smart") {
1443 if (how == "smart") {
1422 indentation = mode.indent(state, line.text.slice(curSpaceString.length), line.text);
1444 indentation = mode.indent(state, line.text.slice(curSpaceString.length), line.text);
1423 if (indentation == Pass) how = "prev";
1445 if (indentation == Pass) how = "prev";
1424 }
1446 }
1425 if (how == "prev") {
1447 if (how == "prev") {
1426 if (n) indentation = getLine(n-1).indentation(options.tabSize);
1448 if (n) indentation = getLine(n-1).indentation(options.tabSize);
1427 else indentation = 0;
1449 else indentation = 0;
1428 }
1450 }
1429 else if (how == "add") indentation = curSpace + options.indentUnit;
1451 else if (how == "add") indentation = curSpace + options.indentUnit;
1430 else if (how == "subtract") indentation = curSpace - options.indentUnit;
1452 else if (how == "subtract") indentation = curSpace - options.indentUnit;
1431 indentation = Math.max(0, indentation);
1453 indentation = Math.max(0, indentation);
1432 var diff = indentation - curSpace;
1454 var diff = indentation - curSpace;
1433
1455
1434 if (!diff) {
1456 var indentString = "", pos = 0;
1435 if (sel.from.line != n && sel.to.line != n) return;
1457 if (options.indentWithTabs)
1436 var indentString = curSpaceString;
1458 for (var i = Math.floor(indentation / options.tabSize); i; --i) {pos += options.tabSize; indentString += "\t";}
1437 } else {
1459 if (pos < indentation) indentString += spaceStr(indentation - pos);
1438 var indentString = "", pos = 0;
1439 if (options.indentWithTabs)
1440 for (var i = Math.floor(indentation / options.tabSize); i; --i) {pos += options.tabSize; indentString += "\t";}
1441 while (pos < indentation) {++pos; indentString += " ";}
1442 }
1443
1460
1444 replaceRange(indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length});
1461 if (indentString != curSpaceString)
1462 replaceRange(indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length});
1445 }
1463 }
1446
1464
1447 function loadMode() {
1465 function loadMode() {
1448 mode = CodeMirror.getMode(options, options.mode);
1466 mode = CodeMirror.getMode(options, options.mode);
1449 doc.iter(0, doc.size, function(line) { line.stateAfter = null; });
1467 doc.iter(0, doc.size, function(line) { line.stateAfter = null; });
1450 work = [0];
1468 frontier = 0;
1451 startWorker();
1469 startWorker(100);
1452 }
1470 }
1453 function gutterChanged() {
1471 function gutterChanged() {
1454 var visible = options.gutter || options.lineNumbers;
1472 var visible = options.gutter || options.lineNumbers;
1455 gutter.style.display = visible ? "" : "none";
1473 gutter.style.display = visible ? "" : "none";
1456 if (visible) gutterDirty = true;
1474 if (visible) gutterDirty = true;
1457 else lineDiv.parentNode.style.marginLeft = 0;
1475 else lineDiv.parentNode.style.marginLeft = 0;
1458 }
1476 }
1459 function wrappingChanged(from, to) {
1477 function wrappingChanged(from, to) {
1460 if (options.lineWrapping) {
1478 if (options.lineWrapping) {
1461 wrapper.className += " CodeMirror-wrap";
1479 wrapper.className += " CodeMirror-wrap";
1462 var perLine = scroller.clientWidth / charWidth() - 3;
1480 var perLine = scroller.clientWidth / charWidth() - 3;
1463 doc.iter(0, doc.size, function(line) {
1481 doc.iter(0, doc.size, function(line) {
1464 if (line.hidden) return;
1482 if (line.hidden) return;
1465 var guess = Math.ceil(line.text.length / perLine) || 1;
1483 var guess = Math.ceil(line.text.length / perLine) || 1;
1466 if (guess != 1) updateLineHeight(line, guess);
1484 if (guess != 1) updateLineHeight(line, guess);
1467 });
1485 });
1468 lineSpace.style.width = code.style.width = "";
1486 lineSpace.style.minWidth = widthForcer.style.left = "";
1469 widthForcer.style.left = "";
1470 } else {
1487 } else {
1471 wrapper.className = wrapper.className.replace(" CodeMirror-wrap", "");
1488 wrapper.className = wrapper.className.replace(" CodeMirror-wrap", "");
1472 maxLine = ""; maxLineChanged = true;
1489 computeMaxLength();
1473 doc.iter(0, doc.size, function(line) {
1490 doc.iter(0, doc.size, function(line) {
1474 if (line.height != 1 && !line.hidden) updateLineHeight(line, 1);
1491 if (line.height != 1 && !line.hidden) updateLineHeight(line, 1);
1475 if (line.text.length > maxLine.length) maxLine = line.text;
1476 });
1492 });
1477 }
1493 }
1478 changes.push({from: 0, to: doc.size});
1494 changes.push({from: 0, to: doc.size});
1479 }
1495 }
1480 function makeTab(col) {
1481 var w = options.tabSize - col % options.tabSize, cached = tabCache[w];
1482 if (cached) return cached;
1483 for (var str = '<span class="cm-tab">', i = 0; i < w; ++i) str += " ";
1484 return (tabCache[w] = {html: str + "</span>", width: w});
1485 }
1486 function themeChanged() {
1496 function themeChanged() {
1487 scroller.className = scroller.className.replace(/\s*cm-s-\S+/g, "") +
1497 scroller.className = scroller.className.replace(/\s*cm-s-\S+/g, "") +
1488 options.theme.replace(/(^|\s)\s*/g, " cm-s-");
1498 options.theme.replace(/(^|\s)\s*/g, " cm-s-");
1489 }
1499 }
1490 function keyMapChanged() {
1500 function keyMapChanged() {
1491 var style = keyMap[options.keyMap].style;
1501 var style = keyMap[options.keyMap].style;
1492 wrapper.className = wrapper.className.replace(/\s*cm-keymap-\S+/g, "") +
1502 wrapper.className = wrapper.className.replace(/\s*cm-keymap-\S+/g, "") +
1493 (style ? " cm-keymap-" + style : "");
1503 (style ? " cm-keymap-" + style : "");
1494 }
1504 }
1495
1505
1496 function TextMarker() { this.set = []; }
1506 function TextMarker(type, style) { this.lines = []; this.type = type; if (style) this.style = style; }
1497 TextMarker.prototype.clear = operation(function() {
1507 TextMarker.prototype.clear = operation(function() {
1498 var min = Infinity, max = -Infinity;
1508 var min = Infinity, max = -Infinity;
1499 for (var i = 0, e = this.set.length; i < e; ++i) {
1509 for (var i = 0; i < this.lines.length; ++i) {
1500 var line = this.set[i], mk = line.marked;
1510 var line = this.lines[i];
1501 if (!mk || !line.parent) continue;
1511 var span = getMarkedSpanFor(line.markedSpans, this, true);
1502 var lineN = lineNo(line);
1512 if (span.from != null || span.to != null) {
1503 min = Math.min(min, lineN); max = Math.max(max, lineN);
1513 var lineN = lineNo(line);
1504 for (var j = 0; j < mk.length; ++j)
1514 min = Math.min(min, lineN); max = Math.max(max, lineN);
1505 if (mk[j].marker == this) mk.splice(j--, 1);
1515 }
1506 }
1516 }
1507 if (min != Infinity)
1517 if (min != Infinity)
1508 changes.push({from: min, to: max + 1});
1518 changes.push({from: min, to: max + 1});
1519 this.lines.length = 0;
1509 });
1520 });
1510 TextMarker.prototype.find = function() {
1521 TextMarker.prototype.find = function() {
1511 var from, to;
1522 var from, to;
1512 for (var i = 0, e = this.set.length; i < e; ++i) {
1523 for (var i = 0; i < this.lines.length; ++i) {
1513 var line = this.set[i], mk = line.marked;
1524 var line = this.lines[i];
1514 for (var j = 0; j < mk.length; ++j) {
1525 var span = getMarkedSpanFor(line.markedSpans, this);
1515 var mark = mk[j];
1526 if (span.from != null || span.to != null) {
1516 if (mark.marker == this) {
1527 var found = lineNo(line);
1517 if (mark.from != null || mark.to != null) {
1528 if (span.from != null) from = {line: found, ch: span.from};
1518 var found = lineNo(line);
1529 if (span.to != null) to = {line: found, ch: span.to};
1519 if (found != null) {
1520 if (mark.from != null) from = {line: found, ch: mark.from};
1521 if (mark.to != null) to = {line: found, ch: mark.to};
1522 }
1523 }
1524 }
1525 }
1530 }
1526 }
1531 }
1527 return {from: from, to: to};
1532 if (this.type == "bookmark") return from;
1533 return from && {from: from, to: to};
1528 };
1534 };
1529
1535
1530 function markText(from, to, className) {
1536 function markText(from, to, className, options) {
1531 from = clipPos(from); to = clipPos(to);
1537 from = clipPos(from); to = clipPos(to);
1532 var tm = new TextMarker();
1538 var marker = new TextMarker("range", className);
1533 if (!posLess(from, to)) return tm;
1539 if (options) for (var opt in options) if (options.hasOwnProperty(opt))
1534 function add(line, from, to, className) {
1540 marker[opt] = options[opt];
1535 getLine(line).addMark(new MarkedText(from, to, className, tm));
1541 var curLine = from.line;
1536 }
1542 doc.iter(curLine, to.line + 1, function(line) {
1537 if (from.line == to.line) add(from.line, from.ch, to.ch, className);
1543 var span = {from: curLine == from.line ? from.ch : null,
1538 else {
1544 to: curLine == to.line ? to.ch : null,
1539 add(from.line, from.ch, null, className);
1545 marker: marker};
1540 for (var i = from.line + 1, e = to.line; i < e; ++i)
1546 (line.markedSpans || (line.markedSpans = [])).push(span);
1541 add(i, null, null, className);
1547 marker.lines.push(line);
1542 add(to.line, null, to.ch, className);
1548 ++curLine;
1543 }
1549 });
1544 changes.push({from: from.line, to: to.line + 1});
1550 changes.push({from: from.line, to: to.line + 1});
1545 return tm;
1551 return marker;
1546 }
1552 }
1547
1553
1548 function setBookmark(pos) {
1554 function setBookmark(pos) {
1549 pos = clipPos(pos);
1555 pos = clipPos(pos);
1550 var bm = new Bookmark(pos.ch);
1556 var marker = new TextMarker("bookmark"), line = getLine(pos.line);
1551 getLine(pos.line).addMark(bm);
1557 var span = {from: pos.ch, to: pos.ch, marker: marker};
1552 return bm;
1558 (line.markedSpans || (line.markedSpans = [])).push(span);
1559 marker.lines.push(line);
1560 return marker;
1553 }
1561 }
1554
1562
1555 function findMarksAt(pos) {
1563 function findMarksAt(pos) {
1556 pos = clipPos(pos);
1564 pos = clipPos(pos);
1557 var markers = [], marked = getLine(pos.line).marked;
1565 var markers = [], spans = getLine(pos.line).markedSpans;
1558 if (!marked) return markers;
1566 if (spans) for (var i = 0; i < spans.length; ++i) {
1559 for (var i = 0, e = marked.length; i < e; ++i) {
1567 var span = spans[i];
1560 var m = marked[i];
1568 if ((span.from == null || span.from <= pos.ch) &&
1561 if ((m.from == null || m.from <= pos.ch) &&
1569 (span.to == null || span.to >= pos.ch))
1562 (m.to == null || m.to >= pos.ch))
1570 markers.push(span.marker);
1563 markers.push(m.marker || m);
1564 }
1571 }
1565 return markers;
1572 return markers;
1566 }
1573 }
1567
1574
1568 function addGutterMarker(line, text, className) {
1575 function addGutterMarker(line, text, className) {
1569 if (typeof line == "number") line = getLine(clipLine(line));
1576 if (typeof line == "number") line = getLine(clipLine(line));
1570 line.gutterMarker = {text: text, style: className};
1577 line.gutterMarker = {text: text, style: className};
1571 gutterDirty = true;
1578 gutterDirty = true;
1572 return line;
1579 return line;
1573 }
1580 }
1574 function removeGutterMarker(line) {
1581 function removeGutterMarker(line) {
1575 if (typeof line == "number") line = getLine(clipLine(line));
1582 if (typeof line == "number") line = getLine(clipLine(line));
1576 line.gutterMarker = null;
1583 line.gutterMarker = null;
1577 gutterDirty = true;
1584 gutterDirty = true;
1578 }
1585 }
1579
1586
1580 function changeLine(handle, op) {
1587 function changeLine(handle, op) {
1581 var no = handle, line = handle;
1588 var no = handle, line = handle;
1582 if (typeof handle == "number") line = getLine(clipLine(handle));
1589 if (typeof handle == "number") line = getLine(clipLine(handle));
1583 else no = lineNo(handle);
1590 else no = lineNo(handle);
1584 if (no == null) return null;
1591 if (no == null) return null;
1585 if (op(line, no)) changes.push({from: no, to: no + 1});
1592 if (op(line, no)) changes.push({from: no, to: no + 1});
1586 else return null;
1593 else return null;
1587 return line;
1594 return line;
1588 }
1595 }
1589 function setLineClass(handle, className, bgClassName) {
1596 function setLineClass(handle, className, bgClassName) {
1590 return changeLine(handle, function(line) {
1597 return changeLine(handle, function(line) {
1591 if (line.className != className || line.bgClassName != bgClassName) {
1598 if (line.className != className || line.bgClassName != bgClassName) {
1592 line.className = className;
1599 line.className = className;
1593 line.bgClassName = bgClassName;
1600 line.bgClassName = bgClassName;
1594 return true;
1601 return true;
1595 }
1602 }
1596 });
1603 });
1597 }
1604 }
1598 function setLineHidden(handle, hidden) {
1605 function setLineHidden(handle, hidden) {
1599 return changeLine(handle, function(line, no) {
1606 return changeLine(handle, function(line, no) {
1600 if (line.hidden != hidden) {
1607 if (line.hidden != hidden) {
1601 line.hidden = hidden;
1608 line.hidden = hidden;
1602 if (!options.lineWrapping) {
1609 if (!options.lineWrapping) {
1603 var l = line.text;
1610 if (hidden && line.text.length == maxLine.text.length) {
1604 if (hidden && l.length == maxLine.length) {
1605 updateMaxLine = true;
1611 updateMaxLine = true;
1606 } else if (!hidden && l.length > maxLine.length) {
1612 } else if (!hidden && line.text.length > maxLine.text.length) {
1607 maxLine = l; maxWidth = null; updateMaxLine = false;
1613 maxLine = line; updateMaxLine = false;
1608 }
1614 }
1609 }
1615 }
1610 updateLineHeight(line, hidden ? 0 : 1);
1616 updateLineHeight(line, hidden ? 0 : 1);
1611 var fline = sel.from.line, tline = sel.to.line;
1617 var fline = sel.from.line, tline = sel.to.line;
1612 if (hidden && (fline == no || tline == no)) {
1618 if (hidden && (fline == no || tline == no)) {
1613 var from = fline == no ? skipHidden({line: fline, ch: 0}, fline, 0) : sel.from;
1619 var from = fline == no ? skipHidden({line: fline, ch: 0}, fline, 0) : sel.from;
1614 var to = tline == no ? skipHidden({line: tline, ch: 0}, tline, 0) : sel.to;
1620 var to = tline == no ? skipHidden({line: tline, ch: 0}, tline, 0) : sel.to;
1615 // Can't hide the last visible line, we'd have no place to put the cursor
1621 // Can't hide the last visible line, we'd have no place to put the cursor
1616 if (!to) return;
1622 if (!to) return;
1617 setSelection(from, to);
1623 setSelection(from, to);
1618 }
1624 }
1619 return (gutterDirty = true);
1625 return (gutterDirty = true);
1620 }
1626 }
1621 });
1627 });
1622 }
1628 }
1623
1629
1624 function lineInfo(line) {
1630 function lineInfo(line) {
1625 if (typeof line == "number") {
1631 if (typeof line == "number") {
1626 if (!isLine(line)) return null;
1632 if (!isLine(line)) return null;
1627 var n = line;
1633 var n = line;
1628 line = getLine(line);
1634 line = getLine(line);
1629 if (!line) return null;
1635 if (!line) return null;
1630 } else {
1636 } else {
1631 var n = lineNo(line);
1637 var n = lineNo(line);
1632 if (n == null) return null;
1638 if (n == null) return null;
1633 }
1639 }
1634 var marker = line.gutterMarker;
1640 var marker = line.gutterMarker;
1635 return {line: n, handle: line, text: line.text, markerText: marker && marker.text,
1641 return {line: n, handle: line, text: line.text, markerText: marker && marker.text,
1636 markerClass: marker && marker.style, lineClass: line.className, bgClass: line.bgClassName};
1642 markerClass: marker && marker.style, lineClass: line.className, bgClass: line.bgClassName};
1637 }
1643 }
1638
1644
1639 function stringWidth(str) {
1640 measure.innerHTML = "<pre><span>x</span></pre>";
1641 measure.firstChild.firstChild.firstChild.nodeValue = str;
1642 return measure.firstChild.firstChild.offsetWidth || 10;
1643 }
1644 // These are used to go from pixel positions to character
1645 // positions, taking varying character widths into account.
1646 function charFromX(line, x) {
1647 if (x <= 0) return 0;
1648 var lineObj = getLine(line), text = lineObj.text;
1649 function getX(len) {
1650 return measureLine(lineObj, len).left;
1651 }
1652 var from = 0, fromX = 0, to = text.length, toX;
1653 // Guess a suitable upper bound for our search.
1654 var estimated = Math.min(to, Math.ceil(x / charWidth()));
1655 for (;;) {
1656 var estX = getX(estimated);
1657 if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));
1658 else {toX = estX; to = estimated; break;}
1659 }
1660 if (x > toX) return to;
1661 // Try to guess a suitable lower bound as well.
1662 estimated = Math.floor(to * 0.8); estX = getX(estimated);
1663 if (estX < x) {from = estimated; fromX = estX;}
1664 // Do a binary search between these bounds.
1665 for (;;) {
1666 if (to - from <= 1) return (toX - x > x - fromX) ? from : to;
1667 var middle = Math.ceil((from + to) / 2), middleX = getX(middle);
1668 if (middleX > x) {to = middle; toX = middleX;}
1669 else {from = middle; fromX = middleX;}
1670 }
1671 }
1672
1673 var tempId = "CodeMirror-temp-" + Math.floor(Math.random() * 0xffffff).toString(16);
1674 function measureLine(line, ch) {
1645 function measureLine(line, ch) {
1675 if (ch == 0) return {top: 0, left: 0};
1646 if (ch == 0) return {top: 0, left: 0};
1676 var wbr = options.lineWrapping && ch < line.text.length &&
1647 var wbr = options.lineWrapping && ch < line.text.length &&
1677 spanAffectsWrapping.test(line.text.slice(ch - 1, ch + 1));
1648 spanAffectsWrapping.test(line.text.slice(ch - 1, ch + 1));
1678 measure.innerHTML = "<pre>" + line.getHTML(makeTab, ch, tempId, wbr) + "</pre>";
1649 var pre = lineContent(line, ch);
1679 var elt = document.getElementById(tempId);
1650 removeChildrenAndAdd(measure, pre);
1680 var top = elt.offsetTop, left = elt.offsetLeft;
1651 var anchor = pre.anchor;
1652 var top = anchor.offsetTop, left = anchor.offsetLeft;
1681 // Older IEs report zero offsets for spans directly after a wrap
1653 // Older IEs report zero offsets for spans directly after a wrap
1682 if (ie && top == 0 && left == 0) {
1654 if (ie && top == 0 && left == 0) {
1683 var backup = document.createElement("span");
1655 var backup = elt("span", "x");
1684 backup.innerHTML = "x";
1656 anchor.parentNode.insertBefore(backup, anchor.nextSibling);
1685 elt.parentNode.insertBefore(backup, elt.nextSibling);
1686 top = backup.offsetTop;
1657 top = backup.offsetTop;
1687 }
1658 }
1688 return {top: top, left: left};
1659 return {top: top, left: left};
1689 }
1660 }
1690 function localCoords(pos, inLineWrap) {
1661 function localCoords(pos, inLineWrap) {
1691 var x, lh = textHeight(), y = lh * (heightAtLine(doc, pos.line) - (inLineWrap ? displayOffset : 0));
1662 var x, lh = textHeight(), y = lh * (heightAtLine(doc, pos.line) - (inLineWrap ? displayOffset : 0));
1692 if (pos.ch == 0) x = 0;
1663 if (pos.ch == 0) x = 0;
1693 else {
1664 else {
1694 var sp = measureLine(getLine(pos.line), pos.ch);
1665 var sp = measureLine(getLine(pos.line), pos.ch);
1695 x = sp.left;
1666 x = sp.left;
1696 if (options.lineWrapping) y += Math.max(0, sp.top);
1667 if (options.lineWrapping) y += Math.max(0, sp.top);
1697 }
1668 }
1698 return {x: x, y: y, yBot: y + lh};
1669 return {x: x, y: y, yBot: y + lh};
1699 }
1670 }
1700 // Coords must be lineSpace-local
1671 // Coords must be lineSpace-local
1701 function coordsChar(x, y) {
1672 function coordsChar(x, y) {
1702 if (y < 0) y = 0;
1703 var th = textHeight(), cw = charWidth(), heightPos = displayOffset + Math.floor(y / th);
1673 var th = textHeight(), cw = charWidth(), heightPos = displayOffset + Math.floor(y / th);
1674 if (heightPos < 0) return {line: 0, ch: 0};
1704 var lineNo = lineAtHeight(doc, heightPos);
1675 var lineNo = lineAtHeight(doc, heightPos);
1705 if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc.size - 1).text.length};
1676 if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc.size - 1).text.length};
1706 var lineObj = getLine(lineNo), text = lineObj.text;
1677 var lineObj = getLine(lineNo), text = lineObj.text;
1707 var tw = options.lineWrapping, innerOff = tw ? heightPos - heightAtLine(doc, lineNo) : 0;
1678 var tw = options.lineWrapping, innerOff = tw ? heightPos - heightAtLine(doc, lineNo) : 0;
1708 if (x <= 0 && innerOff == 0) return {line: lineNo, ch: 0};
1679 if (x <= 0 && innerOff == 0) return {line: lineNo, ch: 0};
1680 var wrongLine = false;
1709 function getX(len) {
1681 function getX(len) {
1710 var sp = measureLine(lineObj, len);
1682 var sp = measureLine(lineObj, len);
1711 if (tw) {
1683 if (tw) {
1712 var off = Math.round(sp.top / th);
1684 var off = Math.round(sp.top / th);
1685 wrongLine = off != innerOff;
1713 return Math.max(0, sp.left + (off - innerOff) * scroller.clientWidth);
1686 return Math.max(0, sp.left + (off - innerOff) * scroller.clientWidth);
1714 }
1687 }
1715 return sp.left;
1688 return sp.left;
1716 }
1689 }
1717 var from = 0, fromX = 0, to = text.length, toX;
1690 var from = 0, fromX = 0, to = text.length, toX;
1718 // Guess a suitable upper bound for our search.
1691 // Guess a suitable upper bound for our search.
1719 var estimated = Math.min(to, Math.ceil((x + innerOff * scroller.clientWidth * .9) / cw));
1692 var estimated = Math.min(to, Math.ceil((x + innerOff * scroller.clientWidth * .9) / cw));
1720 for (;;) {
1693 for (;;) {
1721 var estX = getX(estimated);
1694 var estX = getX(estimated);
1722 if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));
1695 if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));
1723 else {toX = estX; to = estimated; break;}
1696 else {toX = estX; to = estimated; break;}
1724 }
1697 }
1725 if (x > toX) return {line: lineNo, ch: to};
1698 if (x > toX) return {line: lineNo, ch: to};
1726 // Try to guess a suitable lower bound as well.
1699 // Try to guess a suitable lower bound as well.
1727 estimated = Math.floor(to * 0.8); estX = getX(estimated);
1700 estimated = Math.floor(to * 0.8); estX = getX(estimated);
1728 if (estX < x) {from = estimated; fromX = estX;}
1701 if (estX < x) {from = estimated; fromX = estX;}
1729 // Do a binary search between these bounds.
1702 // Do a binary search between these bounds.
1730 for (;;) {
1703 for (;;) {
1731 if (to - from <= 1) return {line: lineNo, ch: (toX - x > x - fromX) ? from : to};
1704 if (to - from <= 1) {
1705 var after = x - fromX < toX - x;
1706 return {line: lineNo, ch: after ? from : to, after: after};
1707 }
1732 var middle = Math.ceil((from + to) / 2), middleX = getX(middle);
1708 var middle = Math.ceil((from + to) / 2), middleX = getX(middle);
1733 if (middleX > x) {to = middle; toX = middleX;}
1709 if (middleX > x) {to = middle; toX = middleX; if (wrongLine) toX += 1000; }
1734 else {from = middle; fromX = middleX;}
1710 else {from = middle; fromX = middleX;}
1735 }
1711 }
1736 }
1712 }
1737 function pageCoords(pos) {
1713 function pageCoords(pos) {
1738 var local = localCoords(pos, true), off = eltOffset(lineSpace);
1714 var local = localCoords(pos, true), off = eltOffset(lineSpace);
1739 return {x: off.left + local.x, y: off.top + local.y, yBot: off.top + local.yBot};
1715 return {x: off.left + local.x, y: off.top + local.y, yBot: off.top + local.yBot};
1740 }
1716 }
1741
1717
1742 var cachedHeight, cachedHeightFor, measureText;
1718 var cachedHeight, cachedHeightFor, measurePre;
1743 function textHeight() {
1719 function textHeight() {
1744 if (measureText == null) {
1720 if (measurePre == null) {
1745 measureText = "<pre>";
1721 measurePre = elt("pre");
1746 for (var i = 0; i < 49; ++i) measureText += "x<br/>";
1722 for (var i = 0; i < 49; ++i) {
1747 measureText += "x</pre>";
1723 measurePre.appendChild(document.createTextNode("x"));
1724 measurePre.appendChild(elt("br"));
1725 }
1726 measurePre.appendChild(document.createTextNode("x"));
1748 }
1727 }
1749 var offsetHeight = lineDiv.clientHeight;
1728 var offsetHeight = lineDiv.clientHeight;
1750 if (offsetHeight == cachedHeightFor) return cachedHeight;
1729 if (offsetHeight == cachedHeightFor) return cachedHeight;
1751 cachedHeightFor = offsetHeight;
1730 cachedHeightFor = offsetHeight;
1752 measure.innerHTML = measureText;
1731 removeChildrenAndAdd(measure, measurePre.cloneNode(true));
1753 cachedHeight = measure.firstChild.offsetHeight / 50 || 1;
1732 cachedHeight = measure.firstChild.offsetHeight / 50 || 1;
1754 measure.innerHTML = "";
1733 removeChildren(measure);
1755 return cachedHeight;
1734 return cachedHeight;
1756 }
1735 }
1757 var cachedWidth, cachedWidthFor = 0;
1736 var cachedWidth, cachedWidthFor = 0;
1758 function charWidth() {
1737 function charWidth() {
1759 if (scroller.clientWidth == cachedWidthFor) return cachedWidth;
1738 if (scroller.clientWidth == cachedWidthFor) return cachedWidth;
1760 cachedWidthFor = scroller.clientWidth;
1739 cachedWidthFor = scroller.clientWidth;
1761 return (cachedWidth = stringWidth("x"));
1740 var anchor = elt("span", "x");
1741 var pre = elt("pre", [anchor]);
1742 removeChildrenAndAdd(measure, pre);
1743 return (cachedWidth = anchor.offsetWidth || 10);
1762 }
1744 }
1763 function paddingTop() {return lineSpace.offsetTop;}
1745 function paddingTop() {return lineSpace.offsetTop;}
1764 function paddingLeft() {return lineSpace.offsetLeft;}
1746 function paddingLeft() {return lineSpace.offsetLeft;}
1765
1747
1766 function posFromMouse(e, liberal) {
1748 function posFromMouse(e, liberal) {
1767 var offW = eltOffset(scroller, true), x, y;
1749 var offW = eltOffset(scroller, true), x, y;
1768 // Fails unpredictably on IE[67] when mouse is dragged around quickly.
1750 // Fails unpredictably on IE[67] when mouse is dragged around quickly.
1769 try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
1751 try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
1770 // This is a mess of a heuristic to try and determine whether a
1752 // This is a mess of a heuristic to try and determine whether a
1771 // scroll-bar was clicked or not, and to return null if one was
1753 // scroll-bar was clicked or not, and to return null if one was
1772 // (and !liberal).
1754 // (and !liberal).
1773 if (!liberal && (x - offW.left > scroller.clientWidth || y - offW.top > scroller.clientHeight))
1755 if (!liberal && (x - offW.left > scroller.clientWidth || y - offW.top > scroller.clientHeight))
1774 return null;
1756 return null;
1775 var offL = eltOffset(lineSpace, true);
1757 var offL = eltOffset(lineSpace, true);
1776 return coordsChar(x - offL.left, y - offL.top);
1758 return coordsChar(x - offL.left, y - offL.top);
1777 }
1759 }
1760 var detectingSelectAll;
1778 function onContextMenu(e) {
1761 function onContextMenu(e) {
1779 var pos = posFromMouse(e), scrollPos = scrollbar.scrollTop;
1762 var pos = posFromMouse(e), scrollPos = scrollbar.scrollTop;
1780 if (!pos || opera) return; // Opera is difficult.
1763 if (!pos || opera) return; // Opera is difficult.
1781 if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
1764 if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
1782 operation(setCursor)(pos.line, pos.ch);
1765 operation(setCursor)(pos.line, pos.ch);
1783
1766
1784 var oldCSS = input.style.cssText;
1767 var oldCSS = input.style.cssText;
1785 inputDiv.style.position = "absolute";
1768 inputDiv.style.position = "absolute";
1786 input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
1769 input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
1787 "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; " +
1770 "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; " +
1788 "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
1771 "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
1789 leaveInputAlone = true;
1790 var val = input.value = getSelection();
1791 focusInput();
1772 focusInput();
1792 selectInput(input);
1773 resetInput(true);
1774 // Adds "Select all" to context menu in FF
1775 if (posEq(sel.from, sel.to)) input.value = prevInput = " ";
1776
1793 function rehide() {
1777 function rehide() {
1794 var newVal = splitLines(input.value).join("\n");
1795 if (newVal != val && !options.readOnly) operation(replaceSelection)(newVal, "end");
1796 inputDiv.style.position = "relative";
1778 inputDiv.style.position = "relative";
1797 input.style.cssText = oldCSS;
1779 input.style.cssText = oldCSS;
1798 if (ie_lt9) scrollbar.scrollTop = scrollPos;
1780 if (ie_lt9) scrollbar.scrollTop = scrollPos;
1799 leaveInputAlone = false;
1800 resetInput(true);
1801 slowPoll();
1781 slowPoll();
1782
1783 // Try to detect the user choosing select-all
1784 if (input.selectionStart != null) {
1785 clearTimeout(detectingSelectAll);
1786 var extval = input.value = " " + (posEq(sel.from, sel.to) ? "" : input.value), i = 0;
1787 prevInput = " ";
1788 input.selectionStart = 1; input.selectionEnd = extval.length;
1789 detectingSelectAll = setTimeout(function poll(){
1790 if (prevInput == " " && input.selectionStart == 0)
1791 operation(commands.selectAll)(instance);
1792 else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500);
1793 else resetInput();
1794 }, 200);
1795 }
1802 }
1796 }
1803
1797
1804 if (gecko) {
1798 if (gecko) {
1805 e_stop(e);
1799 e_stop(e);
1806 var mouseup = connect(window, "mouseup", function() {
1800 var mouseup = connect(window, "mouseup", function() {
1807 mouseup();
1801 mouseup();
1808 setTimeout(rehide, 20);
1802 setTimeout(rehide, 20);
1809 }, true);
1803 }, true);
1810 } else {
1804 } else {
1811 setTimeout(rehide, 50);
1805 setTimeout(rehide, 50);
1812 }
1806 }
1813 }
1807 }
1814
1808
1815 // Cursor-blinking
1809 // Cursor-blinking
1816 function restartBlink() {
1810 function restartBlink() {
1817 clearInterval(blinker);
1811 clearInterval(blinker);
1818 var on = true;
1812 var on = true;
1819 cursor.style.visibility = "";
1813 cursor.style.visibility = "";
1820 blinker = setInterval(function() {
1814 blinker = setInterval(function() {
1821 cursor.style.visibility = (on = !on) ? "" : "hidden";
1815 cursor.style.visibility = (on = !on) ? "" : "hidden";
1822 }, 650);
1816 }, options.cursorBlinkRate);
1823 }
1817 }
1824
1818
1825 var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
1819 var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
1826 function matchBrackets(autoclear) {
1820 function matchBrackets(autoclear) {
1827 var head = sel.inverted ? sel.from : sel.to, line = getLine(head.line), pos = head.ch - 1;
1821 var head = sel.inverted ? sel.from : sel.to, line = getLine(head.line), pos = head.ch - 1;
1828 var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
1822 var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
1829 if (!match) return;
1823 if (!match) return;
1830 var ch = match.charAt(0), forward = match.charAt(1) == ">", d = forward ? 1 : -1, st = line.styles;
1824 var ch = match.charAt(0), forward = match.charAt(1) == ">", d = forward ? 1 : -1, st = line.styles;
1831 for (var off = pos + 1, i = 0, e = st.length; i < e; i+=2)
1825 for (var off = pos + 1, i = 0, e = st.length; i < e; i+=2)
1832 if ((off -= st[i].length) <= 0) {var style = st[i+1]; break;}
1826 if ((off -= st[i].length) <= 0) {var style = st[i+1]; break;}
1833
1827
1834 var stack = [line.text.charAt(pos)], re = /[(){}[\]]/;
1828 var stack = [line.text.charAt(pos)], re = /[(){}[\]]/;
1835 function scan(line, from, to) {
1829 function scan(line, from, to) {
1836 if (!line.text) return;
1830 if (!line.text) return;
1837 var st = line.styles, pos = forward ? 0 : line.text.length - 1, cur;
1831 var st = line.styles, pos = forward ? 0 : line.text.length - 1, cur;
1838 for (var i = forward ? 0 : st.length - 2, e = forward ? st.length : -2; i != e; i += 2*d) {
1832 for (var i = forward ? 0 : st.length - 2, e = forward ? st.length : -2; i != e; i += 2*d) {
1839 var text = st[i];
1833 var text = st[i];
1840 if (st[i+1] != style) {pos += d * text.length; continue;}
1834 if (st[i+1] != style) {pos += d * text.length; continue;}
1841 for (var j = forward ? 0 : text.length - 1, te = forward ? text.length : -1; j != te; j += d, pos+=d) {
1835 for (var j = forward ? 0 : text.length - 1, te = forward ? text.length : -1; j != te; j += d, pos+=d) {
1842 if (pos >= from && pos < to && re.test(cur = text.charAt(j))) {
1836 if (pos >= from && pos < to && re.test(cur = text.charAt(j))) {
1843 var match = matching[cur];
1837 var match = matching[cur];
1844 if (match.charAt(1) == ">" == forward) stack.push(cur);
1838 if (match.charAt(1) == ">" == forward) stack.push(cur);
1845 else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false};
1839 else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false};
1846 else if (!stack.length) return {pos: pos, match: true};
1840 else if (!stack.length) return {pos: pos, match: true};
1847 }
1841 }
1848 }
1842 }
1849 }
1843 }
1850 }
1844 }
1851 for (var i = head.line, e = forward ? Math.min(i + 100, doc.size) : Math.max(-1, i - 100); i != e; i+=d) {
1845 for (var i = head.line, e = forward ? Math.min(i + 100, doc.size) : Math.max(-1, i - 100); i != e; i+=d) {
1852 var line = getLine(i), first = i == head.line;
1846 var line = getLine(i), first = i == head.line;
1853 var found = scan(line, first && forward ? pos + 1 : 0, first && !forward ? pos : line.text.length);
1847 var found = scan(line, first && forward ? pos + 1 : 0, first && !forward ? pos : line.text.length);
1854 if (found) break;
1848 if (found) break;
1855 }
1849 }
1856 if (!found) found = {pos: null, match: false};
1850 if (!found) found = {pos: null, match: false};
1857 var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
1851 var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
1858 var one = markText({line: head.line, ch: pos}, {line: head.line, ch: pos+1}, style),
1852 var one = markText({line: head.line, ch: pos}, {line: head.line, ch: pos+1}, style),
1859 two = found.pos != null && markText({line: i, ch: found.pos}, {line: i, ch: found.pos + 1}, style);
1853 two = found.pos != null && markText({line: i, ch: found.pos}, {line: i, ch: found.pos + 1}, style);
1860 var clear = operation(function(){one.clear(); two && two.clear();});
1854 var clear = operation(function(){one.clear(); two && two.clear();});
1861 if (autoclear) setTimeout(clear, 800);
1855 if (autoclear) setTimeout(clear, 800);
1862 else bracketHighlighted = clear;
1856 else bracketHighlighted = clear;
1863 }
1857 }
1864
1858
1865 // Finds the line to start with when starting a parse. Tries to
1859 // Finds the line to start with when starting a parse. Tries to
1866 // find a line with a stateAfter, so that it can start with a
1860 // find a line with a stateAfter, so that it can start with a
1867 // valid state. If that fails, it returns the line with the
1861 // valid state. If that fails, it returns the line with the
1868 // smallest indentation, which tends to need the least context to
1862 // smallest indentation, which tends to need the least context to
1869 // parse correctly.
1863 // parse correctly.
1870 function findStartLine(n) {
1864 function findStartLine(n) {
1871 var minindent, minline;
1865 var minindent, minline;
1872 for (var search = n, lim = n - 40; search > lim; --search) {
1866 for (var search = n, lim = n - 40; search > lim; --search) {
1873 if (search == 0) return 0;
1867 if (search == 0) return 0;
1874 var line = getLine(search-1);
1868 var line = getLine(search-1);
1875 if (line.stateAfter) return search;
1869 if (line.stateAfter) return search;
1876 var indented = line.indentation(options.tabSize);
1870 var indented = line.indentation(options.tabSize);
1877 if (minline == null || minindent > indented) {
1871 if (minline == null || minindent > indented) {
1878 minline = search - 1;
1872 minline = search - 1;
1879 minindent = indented;
1873 minindent = indented;
1880 }
1874 }
1881 }
1875 }
1882 return minline;
1876 return minline;
1883 }
1877 }
1884 function getStateBefore(n) {
1878 function getStateBefore(n) {
1885 var start = findStartLine(n), state = start && getLine(start-1).stateAfter;
1879 var pos = findStartLine(n), state = pos && getLine(pos-1).stateAfter;
1886 if (!state) state = startState(mode);
1880 if (!state) state = startState(mode);
1887 else state = copyState(mode, state);
1881 else state = copyState(mode, state);
1888 doc.iter(start, n, function(line) {
1882 doc.iter(pos, n, function(line) {
1889 line.highlight(mode, state, options.tabSize);
1883 line.process(mode, state, options.tabSize);
1890 line.stateAfter = copyState(mode, state);
1884 line.stateAfter = (pos == n - 1 || pos % 5 == 0) ? copyState(mode, state) : null;
1891 });
1885 });
1892 if (start < n) changes.push({from: start, to: n});
1893 if (n < doc.size && !getLine(n).stateAfter) work.push(n);
1894 return state;
1886 return state;
1895 }
1887 }
1896 function highlightLines(start, end) {
1897 var state = getStateBefore(start);
1898 doc.iter(start, end, function(line) {
1899 line.highlight(mode, state, options.tabSize);
1900 line.stateAfter = copyState(mode, state);
1901 });
1902 }
1903 function highlightWorker() {
1888 function highlightWorker() {
1904 var end = +new Date + options.workTime;
1889 if (frontier >= showingTo) return;
1905 var foundWork = work.length;
1890 var end = +new Date + options.workTime, state = copyState(mode, getStateBefore(frontier));
1906 while (work.length) {
1891 var startFrontier = frontier;
1907 if (!getLine(showingFrom).stateAfter) var task = showingFrom;
1892 doc.iter(frontier, showingTo, function(line) {
1908 else var task = work.pop();
1893 if (frontier >= showingFrom) { // Visible
1909 if (task >= doc.size) continue;
1894 line.highlight(mode, state, options.tabSize);
1910 var start = findStartLine(task), state = start && getLine(start-1).stateAfter;
1911 if (state) state = copyState(mode, state);
1912 else state = startState(mode);
1913
1914 var unchanged = 0, compare = mode.compareStates, realChange = false,
1915 i = start, bail = false;
1916 doc.iter(i, doc.size, function(line) {
1917 var hadState = line.stateAfter;
1918 if (+new Date > end) {
1919 work.push(i);
1920 startWorker(options.workDelay);
1921 if (realChange) changes.push({from: task, to: i + 1});
1922 return (bail = true);
1923 }
1924 var changed = line.highlight(mode, state, options.tabSize);
1925 if (changed) realChange = true;
1926 line.stateAfter = copyState(mode, state);
1895 line.stateAfter = copyState(mode, state);
1927 var done = null;
1896 } else {
1928 if (compare) {
1897 line.process(mode, state, options.tabSize);
1929 var same = hadState && compare(hadState, state);
1898 line.stateAfter = frontier % 5 == 0 ? copyState(mode, state) : null;
1930 if (same != Pass) done = !!same;
1899 }
1931 }
1900 ++frontier;
1932 if (done == null) {
1901 if (+new Date > end) {
1933 if (changed !== false || !hadState) unchanged = 0;
1902 startWorker(options.workDelay);
1934 else if (++unchanged > 3 && (!mode.indent || mode.indent(hadState, "") == mode.indent(state, "")))
1903 return true;
1935 done = true;
1904 }
1936 }
1905 });
1937 if (done) return true;
1906 if (showingTo > startFrontier && frontier >= showingFrom)
1938 ++i;
1907 operation(function() {changes.push({from: startFrontier, to: frontier});})();
1939 });
1940 if (bail) return;
1941 if (realChange) changes.push({from: task, to: i + 1});
1942 }
1943 if (foundWork && options.onHighlightComplete)
1944 options.onHighlightComplete(instance);
1945 }
1908 }
1946 function startWorker(time) {
1909 function startWorker(time) {
1947 if (!work.length) return;
1910 if (frontier < showingTo)
1948 highlight.set(time, operation(highlightWorker));
1911 highlight.set(time, highlightWorker);
1949 }
1912 }
1950
1913
1951 // Operations are used to wrap changes in such a way that each
1914 // Operations are used to wrap changes in such a way that each
1952 // change won't have to update the cursor and display (which would
1915 // change won't have to update the cursor and display (which would
1953 // be awkward, slow, and error-prone), but instead updates are
1916 // be awkward, slow, and error-prone), but instead updates are
1954 // batched and then all combined and executed at once.
1917 // batched and then all combined and executed at once.
1955 function startOperation() {
1918 function startOperation() {
1956 updateInput = userSelChange = textChanged = null;
1919 updateInput = userSelChange = textChanged = null;
1957 changes = []; selectionChanged = false; callbacks = [];
1920 changes = []; selectionChanged = false; callbacks = [];
1958 }
1921 }
1959 function endOperation() {
1922 function endOperation() {
1960 if (updateMaxLine) computeMaxLength();
1923 if (updateMaxLine) computeMaxLength();
1961 if (maxLineChanged && !options.lineWrapping) {
1924 if (maxLineChanged && !options.lineWrapping) {
1962 widthForcer.style.left = stringWidth(maxLine) + "px";
1925 var cursorWidth = widthForcer.offsetWidth, left = measureLine(maxLine, maxLine.text.length).left;
1926 if (!ie_lt8) {
1927 widthForcer.style.left = left + "px";
1928 lineSpace.style.minWidth = (left + cursorWidth) + "px";
1929 }
1963 maxLineChanged = false;
1930 maxLineChanged = false;
1964 }
1931 }
1965 var newScrollPos, updated;
1932 var newScrollPos, updated;
1966 if (selectionChanged) {
1933 if (selectionChanged) {
1967 var coords = calculateCursorCoords();
1934 var coords = calculateCursorCoords();
1968 newScrollPos = calculateScrollPos(coords.x, coords.y, coords.x, coords.yBot);
1935 newScrollPos = calculateScrollPos(coords.x, coords.y, coords.x, coords.yBot);
1969 }
1936 }
1970 if (changes.length) updated = updateDisplay(changes, true, (newScrollPos ? newScrollPos.scrollTop : null));
1937 if (changes.length || newScrollPos && newScrollPos.scrollTop != null)
1971 else {
1938 updated = updateDisplay(changes, true, newScrollPos && newScrollPos.scrollTop);
1939 if (!updated) {
1972 if (selectionChanged) updateSelection();
1940 if (selectionChanged) updateSelection();
1973 if (gutterDirty) updateGutter();
1941 if (gutterDirty) updateGutter();
1974 }
1942 }
1975 if (newScrollPos) scrollCursorIntoView();
1943 if (newScrollPos) scrollCursorIntoView();
1976 if (selectionChanged) {scrollEditorIntoView(); restartBlink();}
1944 if (selectionChanged) restartBlink();
1977
1945
1978 if (focused && !leaveInputAlone &&
1946 if (focused && (updateInput === true || (updateInput !== false && selectionChanged)))
1979 (updateInput === true || (updateInput !== false && selectionChanged)))
1980 resetInput(userSelChange);
1947 resetInput(userSelChange);
1981
1948
1982 if (selectionChanged && options.matchBrackets)
1949 if (selectionChanged && options.matchBrackets)
1983 setTimeout(operation(function() {
1950 setTimeout(operation(function() {
1984 if (bracketHighlighted) {bracketHighlighted(); bracketHighlighted = null;}
1951 if (bracketHighlighted) {bracketHighlighted(); bracketHighlighted = null;}
1985 if (posEq(sel.from, sel.to)) matchBrackets(false);
1952 if (posEq(sel.from, sel.to)) matchBrackets(false);
1986 }), 20);
1953 }), 20);
1987 var sc = selectionChanged, cbs = callbacks; // these can be reset by callbacks
1954 var sc = selectionChanged, cbs = callbacks; // these can be reset by callbacks
1988 if (textChanged && options.onChange && instance)
1955 if (textChanged && options.onChange && instance)
1989 options.onChange(instance, textChanged);
1956 options.onChange(instance, textChanged);
1990 if (sc && options.onCursorActivity)
1957 if (sc && options.onCursorActivity)
1991 options.onCursorActivity(instance);
1958 options.onCursorActivity(instance);
1992 for (var i = 0; i < cbs.length; ++i) cbs[i](instance);
1959 for (var i = 0; i < cbs.length; ++i) cbs[i](instance);
1993 if (updated && options.onUpdate) options.onUpdate(instance);
1960 if (updated && options.onUpdate) options.onUpdate(instance);
1994 }
1961 }
1995 var nestedOperation = 0;
1962 var nestedOperation = 0;
1996 function operation(f) {
1963 function operation(f) {
1997 return function() {
1964 return function() {
1998 if (!nestedOperation++) startOperation();
1965 if (!nestedOperation++) startOperation();
1999 try {var result = f.apply(this, arguments);}
1966 try {var result = f.apply(this, arguments);}
2000 finally {if (!--nestedOperation) endOperation();}
1967 finally {if (!--nestedOperation) endOperation();}
2001 return result;
1968 return result;
2002 };
1969 };
2003 }
1970 }
2004
1971
2005 function compoundChange(f) {
1972 function compoundChange(f) {
2006 history.startCompound();
1973 history.startCompound();
2007 try { return f(); } finally { history.endCompound(); }
1974 try { return f(); } finally { history.endCompound(); }
2008 }
1975 }
2009
1976
2010 for (var ext in extensions)
1977 for (var ext in extensions)
2011 if (extensions.propertyIsEnumerable(ext) &&
1978 if (extensions.propertyIsEnumerable(ext) &&
2012 !instance.propertyIsEnumerable(ext))
1979 !instance.propertyIsEnumerable(ext))
2013 instance[ext] = extensions[ext];
1980 instance[ext] = extensions[ext];
2014 return instance;
1981 return instance;
2015 } // (end of function CodeMirror)
1982 } // (end of function CodeMirror)
2016
1983
2017 // The default configuration options.
1984 // The default configuration options.
2018 CodeMirror.defaults = {
1985 CodeMirror.defaults = {
2019 value: "",
1986 value: "",
2020 mode: null,
1987 mode: null,
2021 theme: "default",
1988 theme: "default",
2022 indentUnit: 2,
1989 indentUnit: 2,
2023 indentWithTabs: false,
1990 indentWithTabs: false,
2024 smartIndent: true,
1991 smartIndent: true,
2025 tabSize: 4,
1992 tabSize: 4,
2026 keyMap: "default",
1993 keyMap: "default",
2027 extraKeys: null,
1994 extraKeys: null,
2028 electricChars: true,
1995 electricChars: true,
2029 autoClearEmptyLines: false,
1996 autoClearEmptyLines: false,
2030 onKeyEvent: null,
1997 onKeyEvent: null,
2031 onDragEvent: null,
1998 onDragEvent: null,
2032 lineWrapping: false,
1999 lineWrapping: false,
2033 lineNumbers: false,
2000 lineNumbers: false,
2034 gutter: false,
2001 gutter: false,
2035 fixedGutter: false,
2002 fixedGutter: false,
2036 firstLineNumber: 1,
2003 firstLineNumber: 1,
2037 readOnly: false,
2004 readOnly: false,
2038 dragDrop: true,
2005 dragDrop: true,
2039 onChange: null,
2006 onChange: null,
2040 onCursorActivity: null,
2007 onCursorActivity: null,
2008 onViewportChange: null,
2041 onGutterClick: null,
2009 onGutterClick: null,
2042 onHighlightComplete: null,
2043 onUpdate: null,
2010 onUpdate: null,
2044 onFocus: null, onBlur: null, onScroll: null,
2011 onFocus: null, onBlur: null, onScroll: null,
2045 matchBrackets: false,
2012 matchBrackets: false,
2013 cursorBlinkRate: 530,
2046 workTime: 100,
2014 workTime: 100,
2047 workDelay: 200,
2015 workDelay: 200,
2048 pollInterval: 100,
2016 pollInterval: 100,
2049 undoDepth: 40,
2017 undoDepth: 40,
2050 tabindex: null,
2018 tabindex: null,
2051 autofocus: null
2019 autofocus: null,
2020 lineNumberFormatter: function(integer) { return integer; }
2052 };
2021 };
2053
2022
2054 var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
2023 var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
2055 var mac = ios || /Mac/.test(navigator.platform);
2024 var mac = ios || /Mac/.test(navigator.platform);
2056 var win = /Win/.test(navigator.platform);
2025 var win = /Win/.test(navigator.platform);
2057
2026
2058 // Known modes, by name and by MIME
2027 // Known modes, by name and by MIME
2059 var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
2028 var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
2060 CodeMirror.defineMode = function(name, mode) {
2029 CodeMirror.defineMode = function(name, mode) {
2061 if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
2030 if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
2062 if (arguments.length > 2) {
2031 if (arguments.length > 2) {
2063 mode.dependencies = [];
2032 mode.dependencies = [];
2064 for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
2033 for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
2065 }
2034 }
2066 modes[name] = mode;
2035 modes[name] = mode;
2067 };
2036 };
2068 CodeMirror.defineMIME = function(mime, spec) {
2037 CodeMirror.defineMIME = function(mime, spec) {
2069 mimeModes[mime] = spec;
2038 mimeModes[mime] = spec;
2070 };
2039 };
2071 CodeMirror.resolveMode = function(spec) {
2040 CodeMirror.resolveMode = function(spec) {
2072 if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
2041 if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
2073 spec = mimeModes[spec];
2042 spec = mimeModes[spec];
2074 else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec))
2043 else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec))
2075 return CodeMirror.resolveMode("application/xml");
2044 return CodeMirror.resolveMode("application/xml");
2076 if (typeof spec == "string") return {name: spec};
2045 if (typeof spec == "string") return {name: spec};
2077 else return spec || {name: "null"};
2046 else return spec || {name: "null"};
2078 };
2047 };
2079 CodeMirror.getMode = function(options, spec) {
2048 CodeMirror.getMode = function(options, spec) {
2080 var spec = CodeMirror.resolveMode(spec);
2049 var spec = CodeMirror.resolveMode(spec);
2081 var mfactory = modes[spec.name];
2050 var mfactory = modes[spec.name];
2082 if (!mfactory) return CodeMirror.getMode(options, "text/plain");
2051 if (!mfactory) return CodeMirror.getMode(options, "text/plain");
2083 return mfactory(options, spec);
2052 var modeObj = mfactory(options, spec);
2053 if (modeExtensions.hasOwnProperty(spec.name)) {
2054 var exts = modeExtensions[spec.name];
2055 for (var prop in exts) if (exts.hasOwnProperty(prop)) modeObj[prop] = exts[prop];
2056 }
2057 modeObj.name = spec.name;
2058 return modeObj;
2084 };
2059 };
2085 CodeMirror.listModes = function() {
2060 CodeMirror.listModes = function() {
2086 var list = [];
2061 var list = [];
2087 for (var m in modes)
2062 for (var m in modes)
2088 if (modes.propertyIsEnumerable(m)) list.push(m);
2063 if (modes.propertyIsEnumerable(m)) list.push(m);
2089 return list;
2064 return list;
2090 };
2065 };
2091 CodeMirror.listMIMEs = function() {
2066 CodeMirror.listMIMEs = function() {
2092 var list = [];
2067 var list = [];
2093 for (var m in mimeModes)
2068 for (var m in mimeModes)
2094 if (mimeModes.propertyIsEnumerable(m)) list.push({mime: m, mode: mimeModes[m]});
2069 if (mimeModes.propertyIsEnumerable(m)) list.push({mime: m, mode: mimeModes[m]});
2095 return list;
2070 return list;
2096 };
2071 };
2097
2072
2098 var extensions = CodeMirror.extensions = {};
2073 var extensions = CodeMirror.extensions = {};
2099 CodeMirror.defineExtension = function(name, func) {
2074 CodeMirror.defineExtension = function(name, func) {
2100 extensions[name] = func;
2075 extensions[name] = func;
2101 };
2076 };
2102
2077
2078 var modeExtensions = CodeMirror.modeExtensions = {};
2079 CodeMirror.extendMode = function(mode, properties) {
2080 var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
2081 for (var prop in properties) if (properties.hasOwnProperty(prop))
2082 exts[prop] = properties[prop];
2083 };
2084
2103 var commands = CodeMirror.commands = {
2085 var commands = CodeMirror.commands = {
2104 selectAll: function(cm) {cm.setSelection({line: 0, ch: 0}, {line: cm.lineCount() - 1});},
2086 selectAll: function(cm) {cm.setSelection({line: 0, ch: 0}, {line: cm.lineCount() - 1});},
2105 killLine: function(cm) {
2087 killLine: function(cm) {
2106 var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
2088 var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
2107 if (!sel && cm.getLine(from.line).length == from.ch) cm.replaceRange("", from, {line: from.line + 1, ch: 0});
2089 if (!sel && cm.getLine(from.line).length == from.ch) cm.replaceRange("", from, {line: from.line + 1, ch: 0});
2108 else cm.replaceRange("", from, sel ? to : {line: from.line});
2090 else cm.replaceRange("", from, sel ? to : {line: from.line});
2109 },
2091 },
2110 deleteLine: function(cm) {var l = cm.getCursor().line; cm.replaceRange("", {line: l, ch: 0}, {line: l});},
2092 deleteLine: function(cm) {var l = cm.getCursor().line; cm.replaceRange("", {line: l, ch: 0}, {line: l});},
2111 undo: function(cm) {cm.undo();},
2093 undo: function(cm) {cm.undo();},
2112 redo: function(cm) {cm.redo();},
2094 redo: function(cm) {cm.redo();},
2113 goDocStart: function(cm) {cm.setCursor(0, 0, true);},
2095 goDocStart: function(cm) {cm.setCursor(0, 0, true);},
2114 goDocEnd: function(cm) {cm.setSelection({line: cm.lineCount() - 1}, null, true);},
2096 goDocEnd: function(cm) {cm.setSelection({line: cm.lineCount() - 1}, null, true);},
2115 goLineStart: function(cm) {cm.setCursor(cm.getCursor().line, 0, true);},
2097 goLineStart: function(cm) {cm.setCursor(cm.getCursor().line, 0, true);},
2116 goLineStartSmart: function(cm) {
2098 goLineStartSmart: function(cm) {
2117 var cur = cm.getCursor();
2099 var cur = cm.getCursor();
2118 var text = cm.getLine(cur.line), firstNonWS = Math.max(0, text.search(/\S/));
2100 var text = cm.getLine(cur.line), firstNonWS = Math.max(0, text.search(/\S/));
2119 cm.setCursor(cur.line, cur.ch <= firstNonWS && cur.ch ? 0 : firstNonWS, true);
2101 cm.setCursor(cur.line, cur.ch <= firstNonWS && cur.ch ? 0 : firstNonWS, true);
2120 },
2102 },
2121 goLineEnd: function(cm) {cm.setSelection({line: cm.getCursor().line}, null, true);},
2103 goLineEnd: function(cm) {cm.setSelection({line: cm.getCursor().line}, null, true);},
2122 goLineUp: function(cm) {cm.moveV(-1, "line");},
2104 goLineUp: function(cm) {cm.moveV(-1, "line");},
2123 goLineDown: function(cm) {cm.moveV(1, "line");},
2105 goLineDown: function(cm) {cm.moveV(1, "line");},
2124 goPageUp: function(cm) {cm.moveV(-1, "page");},
2106 goPageUp: function(cm) {cm.moveV(-1, "page");},
2125 goPageDown: function(cm) {cm.moveV(1, "page");},
2107 goPageDown: function(cm) {cm.moveV(1, "page");},
2126 goCharLeft: function(cm) {cm.moveH(-1, "char");},
2108 goCharLeft: function(cm) {cm.moveH(-1, "char");},
2127 goCharRight: function(cm) {cm.moveH(1, "char");},
2109 goCharRight: function(cm) {cm.moveH(1, "char");},
2128 goColumnLeft: function(cm) {cm.moveH(-1, "column");},
2110 goColumnLeft: function(cm) {cm.moveH(-1, "column");},
2129 goColumnRight: function(cm) {cm.moveH(1, "column");},
2111 goColumnRight: function(cm) {cm.moveH(1, "column");},
2130 goWordLeft: function(cm) {cm.moveH(-1, "word");},
2112 goWordLeft: function(cm) {cm.moveH(-1, "word");},
2131 goWordRight: function(cm) {cm.moveH(1, "word");},
2113 goWordRight: function(cm) {cm.moveH(1, "word");},
2132 delCharLeft: function(cm) {cm.deleteH(-1, "char");},
2114 delCharLeft: function(cm) {cm.deleteH(-1, "char");},
2133 delCharRight: function(cm) {cm.deleteH(1, "char");},
2115 delCharRight: function(cm) {cm.deleteH(1, "char");},
2134 delWordLeft: function(cm) {cm.deleteH(-1, "word");},
2116 delWordLeft: function(cm) {cm.deleteH(-1, "word");},
2135 delWordRight: function(cm) {cm.deleteH(1, "word");},
2117 delWordRight: function(cm) {cm.deleteH(1, "word");},
2136 indentAuto: function(cm) {cm.indentSelection("smart");},
2118 indentAuto: function(cm) {cm.indentSelection("smart");},
2137 indentMore: function(cm) {cm.indentSelection("add");},
2119 indentMore: function(cm) {cm.indentSelection("add");},
2138 indentLess: function(cm) {cm.indentSelection("subtract");},
2120 indentLess: function(cm) {cm.indentSelection("subtract");},
2139 insertTab: function(cm) {cm.replaceSelection("\t", "end");},
2121 insertTab: function(cm) {cm.replaceSelection("\t", "end");},
2140 defaultTab: function(cm) {
2122 defaultTab: function(cm) {
2141 if (cm.somethingSelected()) cm.indentSelection("add");
2123 if (cm.somethingSelected()) cm.indentSelection("add");
2142 else cm.replaceSelection("\t", "end");
2124 else cm.replaceSelection("\t", "end");
2143 },
2125 },
2144 transposeChars: function(cm) {
2126 transposeChars: function(cm) {
2145 var cur = cm.getCursor(), line = cm.getLine(cur.line);
2127 var cur = cm.getCursor(), line = cm.getLine(cur.line);
2146 if (cur.ch > 0 && cur.ch < line.length - 1)
2128 if (cur.ch > 0 && cur.ch < line.length - 1)
2147 cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1),
2129 cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1),
2148 {line: cur.line, ch: cur.ch - 1}, {line: cur.line, ch: cur.ch + 1});
2130 {line: cur.line, ch: cur.ch - 1}, {line: cur.line, ch: cur.ch + 1});
2149 },
2131 },
2150 newlineAndIndent: function(cm) {
2132 newlineAndIndent: function(cm) {
2151 cm.replaceSelection("\n", "end");
2133 cm.replaceSelection("\n", "end");
2152 cm.indentLine(cm.getCursor().line);
2134 cm.indentLine(cm.getCursor().line);
2153 },
2135 },
2154 toggleOverwrite: function(cm) {cm.toggleOverwrite();}
2136 toggleOverwrite: function(cm) {cm.toggleOverwrite();}
2155 };
2137 };
2156
2138
2157 var keyMap = CodeMirror.keyMap = {};
2139 var keyMap = CodeMirror.keyMap = {};
2158 keyMap.basic = {
2140 keyMap.basic = {
2159 "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
2141 "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
2160 "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
2142 "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
2161 "Delete": "delCharRight", "Backspace": "delCharLeft", "Tab": "defaultTab", "Shift-Tab": "indentAuto",
2143 "Delete": "delCharRight", "Backspace": "delCharLeft", "Tab": "defaultTab", "Shift-Tab": "indentAuto",
2162 "Enter": "newlineAndIndent", "Insert": "toggleOverwrite"
2144 "Enter": "newlineAndIndent", "Insert": "toggleOverwrite"
2163 };
2145 };
2164 // Note that the save and find-related commands aren't defined by
2146 // Note that the save and find-related commands aren't defined by
2165 // default. Unknown commands are simply ignored.
2147 // default. Unknown commands are simply ignored.
2166 keyMap.pcDefault = {
2148 keyMap.pcDefault = {
2167 "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
2149 "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
2168 "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
2150 "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
2169 "Ctrl-Left": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
2151 "Ctrl-Left": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
2170 "Ctrl-Backspace": "delWordLeft", "Ctrl-Delete": "delWordRight", "Ctrl-S": "save", "Ctrl-F": "find",
2152 "Ctrl-Backspace": "delWordLeft", "Ctrl-Delete": "delWordRight", "Ctrl-S": "save", "Ctrl-F": "find",
2171 "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
2153 "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
2172 "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
2154 "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
2173 fallthrough: "basic"
2155 fallthrough: "basic"
2174 };
2156 };
2175 keyMap.macDefault = {
2157 keyMap.macDefault = {
2176 "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
2158 "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
2177 "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goWordLeft",
2159 "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goWordLeft",
2178 "Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordLeft",
2160 "Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordLeft",
2179 "Ctrl-Alt-Backspace": "delWordRight", "Alt-Delete": "delWordRight", "Cmd-S": "save", "Cmd-F": "find",
2161 "Ctrl-Alt-Backspace": "delWordRight", "Alt-Delete": "delWordRight", "Cmd-S": "save", "Cmd-F": "find",
2180 "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
2162 "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
2181 "Cmd-[": "indentLess", "Cmd-]": "indentMore",
2163 "Cmd-[": "indentLess", "Cmd-]": "indentMore",
2182 fallthrough: ["basic", "emacsy"]
2164 fallthrough: ["basic", "emacsy"]
2183 };
2165 };
2184 keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
2166 keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
2185 keyMap.emacsy = {
2167 keyMap.emacsy = {
2186 "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
2168 "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
2187 "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
2169 "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
2188 "Ctrl-V": "goPageUp", "Shift-Ctrl-V": "goPageDown", "Ctrl-D": "delCharRight", "Ctrl-H": "delCharLeft",
2170 "Ctrl-V": "goPageUp", "Shift-Ctrl-V": "goPageDown", "Ctrl-D": "delCharRight", "Ctrl-H": "delCharLeft",
2189 "Alt-D": "delWordRight", "Alt-Backspace": "delWordLeft", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
2171 "Alt-D": "delWordRight", "Alt-Backspace": "delWordLeft", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
2190 };
2172 };
2191
2173
2192 function getKeyMap(val) {
2174 function getKeyMap(val) {
2193 if (typeof val == "string") return keyMap[val];
2175 if (typeof val == "string") return keyMap[val];
2194 else return val;
2176 else return val;
2195 }
2177 }
2196 function lookupKey(name, extraMap, map, handle, stop) {
2178 function lookupKey(name, extraMap, map, handle, stop) {
2197 function lookup(map) {
2179 function lookup(map) {
2198 map = getKeyMap(map);
2180 map = getKeyMap(map);
2199 var found = map[name];
2181 var found = map[name];
2182 if (found === false) {
2183 if (stop) stop();
2184 return true;
2185 }
2200 if (found != null && handle(found)) return true;
2186 if (found != null && handle(found)) return true;
2201 if (map.nofallthrough) {
2187 if (map.nofallthrough) {
2202 if (stop) stop();
2188 if (stop) stop();
2203 return true;
2189 return true;
2204 }
2190 }
2205 var fallthrough = map.fallthrough;
2191 var fallthrough = map.fallthrough;
2206 if (fallthrough == null) return false;
2192 if (fallthrough == null) return false;
2207 if (Object.prototype.toString.call(fallthrough) != "[object Array]")
2193 if (Object.prototype.toString.call(fallthrough) != "[object Array]")
2208 return lookup(fallthrough);
2194 return lookup(fallthrough);
2209 for (var i = 0, e = fallthrough.length; i < e; ++i) {
2195 for (var i = 0, e = fallthrough.length; i < e; ++i) {
2210 if (lookup(fallthrough[i])) return true;
2196 if (lookup(fallthrough[i])) return true;
2211 }
2197 }
2212 return false;
2198 return false;
2213 }
2199 }
2214 if (extraMap && lookup(extraMap)) return true;
2200 if (extraMap && lookup(extraMap)) return true;
2215 return lookup(map);
2201 return lookup(map);
2216 }
2202 }
2217 function isModifierKey(event) {
2203 function isModifierKey(event) {
2218 var name = keyNames[e_prop(event, "keyCode")];
2204 var name = keyNames[e_prop(event, "keyCode")];
2219 return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
2205 return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
2220 }
2206 }
2221
2207
2222 CodeMirror.fromTextArea = function(textarea, options) {
2208 CodeMirror.fromTextArea = function(textarea, options) {
2223 if (!options) options = {};
2209 if (!options) options = {};
2224 options.value = textarea.value;
2210 options.value = textarea.value;
2225 if (!options.tabindex && textarea.tabindex)
2211 if (!options.tabindex && textarea.tabindex)
2226 options.tabindex = textarea.tabindex;
2212 options.tabindex = textarea.tabindex;
2227 if (options.autofocus == null && textarea.getAttribute("autofocus") != null)
2213 // Set autofocus to true if this textarea is focused, or if it has
2228 options.autofocus = true;
2214 // autofocus and no other element is focused.
2215 if (options.autofocus == null) {
2216 var hasFocus = document.body;
2217 // doc.activeElement occasionally throws on IE
2218 try { hasFocus = document.activeElement; } catch(e) {}
2219 options.autofocus = hasFocus == textarea ||
2220 textarea.getAttribute("autofocus") != null && hasFocus == document.body;
2221 }
2229
2222
2230 function save() {textarea.value = instance.getValue();}
2223 function save() {textarea.value = instance.getValue();}
2231 if (textarea.form) {
2224 if (textarea.form) {
2232 // Deplorable hack to make the submit method do the right thing.
2225 // Deplorable hack to make the submit method do the right thing.
2233 var rmSubmit = connect(textarea.form, "submit", save, true);
2226 var rmSubmit = connect(textarea.form, "submit", save, true);
2234 if (typeof textarea.form.submit == "function") {
2227 if (typeof textarea.form.submit == "function") {
2235 var realSubmit = textarea.form.submit;
2228 var realSubmit = textarea.form.submit;
2236 function wrappedSubmit() {
2229 textarea.form.submit = function wrappedSubmit() {
2237 save();
2230 save();
2238 textarea.form.submit = realSubmit;
2231 textarea.form.submit = realSubmit;
2239 textarea.form.submit();
2232 textarea.form.submit();
2240 textarea.form.submit = wrappedSubmit;
2233 textarea.form.submit = wrappedSubmit;
2241 }
2234 };
2242 textarea.form.submit = wrappedSubmit;
2243 }
2235 }
2244 }
2236 }
2245
2237
2246 textarea.style.display = "none";
2238 textarea.style.display = "none";
2247 var instance = CodeMirror(function(node) {
2239 var instance = CodeMirror(function(node) {
2248 textarea.parentNode.insertBefore(node, textarea.nextSibling);
2240 textarea.parentNode.insertBefore(node, textarea.nextSibling);
2249 }, options);
2241 }, options);
2250 instance.save = save;
2242 instance.save = save;
2251 instance.getTextArea = function() { return textarea; };
2243 instance.getTextArea = function() { return textarea; };
2252 instance.toTextArea = function() {
2244 instance.toTextArea = function() {
2253 save();
2245 save();
2254 textarea.parentNode.removeChild(instance.getWrapperElement());
2246 textarea.parentNode.removeChild(instance.getWrapperElement());
2255 textarea.style.display = "";
2247 textarea.style.display = "";
2256 if (textarea.form) {
2248 if (textarea.form) {
2257 rmSubmit();
2249 rmSubmit();
2258 if (typeof textarea.form.submit == "function")
2250 if (typeof textarea.form.submit == "function")
2259 textarea.form.submit = realSubmit;
2251 textarea.form.submit = realSubmit;
2260 }
2252 }
2261 };
2253 };
2262 return instance;
2254 return instance;
2263 };
2255 };
2264
2256
2257 var gecko = /gecko\/\d{7}/i.test(navigator.userAgent);
2258 var ie = /MSIE \d/.test(navigator.userAgent);
2259 var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent);
2260 var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent);
2261 var quirksMode = ie && document.documentMode == 5;
2262 var webkit = /WebKit\//.test(navigator.userAgent);
2263 var chrome = /Chrome\//.test(navigator.userAgent);
2264 var opera = /Opera\//.test(navigator.userAgent);
2265 var safari = /Apple Computer/.test(navigator.vendor);
2266 var khtml = /KHTML\//.test(navigator.userAgent);
2267 var mac_geLion = /Mac OS X 10\D([7-9]|\d\d)\D/.test(navigator.userAgent);
2268
2265 // Utility functions for working with state. Exported because modes
2269 // Utility functions for working with state. Exported because modes
2266 // sometimes need to do this.
2270 // sometimes need to do this.
2267 function copyState(mode, state) {
2271 function copyState(mode, state) {
2268 if (state === true) return state;
2272 if (state === true) return state;
2269 if (mode.copyState) return mode.copyState(state);
2273 if (mode.copyState) return mode.copyState(state);
2270 var nstate = {};
2274 var nstate = {};
2271 for (var n in state) {
2275 for (var n in state) {
2272 var val = state[n];
2276 var val = state[n];
2273 if (val instanceof Array) val = val.concat([]);
2277 if (val instanceof Array) val = val.concat([]);
2274 nstate[n] = val;
2278 nstate[n] = val;
2275 }
2279 }
2276 return nstate;
2280 return nstate;
2277 }
2281 }
2278 CodeMirror.copyState = copyState;
2282 CodeMirror.copyState = copyState;
2279 function startState(mode, a1, a2) {
2283 function startState(mode, a1, a2) {
2280 return mode.startState ? mode.startState(a1, a2) : true;
2284 return mode.startState ? mode.startState(a1, a2) : true;
2281 }
2285 }
2282 CodeMirror.startState = startState;
2286 CodeMirror.startState = startState;
2287 CodeMirror.innerMode = function(mode, state) {
2288 while (mode.innerMode) {
2289 var info = mode.innerMode(state);
2290 state = info.state;
2291 mode = info.mode;
2292 }
2293 return info || {mode: mode, state: state};
2294 };
2283
2295
2284 // The character stream used by a mode's parser.
2296 // The character stream used by a mode's parser.
2285 function StringStream(string, tabSize) {
2297 function StringStream(string, tabSize) {
2286 this.pos = this.start = 0;
2298 this.pos = this.start = 0;
2287 this.string = string;
2299 this.string = string;
2288 this.tabSize = tabSize || 8;
2300 this.tabSize = tabSize || 8;
2289 }
2301 }
2290 StringStream.prototype = {
2302 StringStream.prototype = {
2291 eol: function() {return this.pos >= this.string.length;},
2303 eol: function() {return this.pos >= this.string.length;},
2292 sol: function() {return this.pos == 0;},
2304 sol: function() {return this.pos == 0;},
2293 peek: function() {return this.string.charAt(this.pos);},
2305 peek: function() {return this.string.charAt(this.pos) || undefined;},
2294 next: function() {
2306 next: function() {
2295 if (this.pos < this.string.length)
2307 if (this.pos < this.string.length)
2296 return this.string.charAt(this.pos++);
2308 return this.string.charAt(this.pos++);
2297 },
2309 },
2298 eat: function(match) {
2310 eat: function(match) {
2299 var ch = this.string.charAt(this.pos);
2311 var ch = this.string.charAt(this.pos);
2300 if (typeof match == "string") var ok = ch == match;
2312 if (typeof match == "string") var ok = ch == match;
2301 else var ok = ch && (match.test ? match.test(ch) : match(ch));
2313 else var ok = ch && (match.test ? match.test(ch) : match(ch));
2302 if (ok) {++this.pos; return ch;}
2314 if (ok) {++this.pos; return ch;}
2303 },
2315 },
2304 eatWhile: function(match) {
2316 eatWhile: function(match) {
2305 var start = this.pos;
2317 var start = this.pos;
2306 while (this.eat(match)){}
2318 while (this.eat(match)){}
2307 return this.pos > start;
2319 return this.pos > start;
2308 },
2320 },
2309 eatSpace: function() {
2321 eatSpace: function() {
2310 var start = this.pos;
2322 var start = this.pos;
2311 while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
2323 while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
2312 return this.pos > start;
2324 return this.pos > start;
2313 },
2325 },
2314 skipToEnd: function() {this.pos = this.string.length;},
2326 skipToEnd: function() {this.pos = this.string.length;},
2315 skipTo: function(ch) {
2327 skipTo: function(ch) {
2316 var found = this.string.indexOf(ch, this.pos);
2328 var found = this.string.indexOf(ch, this.pos);
2317 if (found > -1) {this.pos = found; return true;}
2329 if (found > -1) {this.pos = found; return true;}
2318 },
2330 },
2319 backUp: function(n) {this.pos -= n;},
2331 backUp: function(n) {this.pos -= n;},
2320 column: function() {return countColumn(this.string, this.start, this.tabSize);},
2332 column: function() {return countColumn(this.string, this.start, this.tabSize);},
2321 indentation: function() {return countColumn(this.string, null, this.tabSize);},
2333 indentation: function() {return countColumn(this.string, null, this.tabSize);},
2322 match: function(pattern, consume, caseInsensitive) {
2334 match: function(pattern, consume, caseInsensitive) {
2323 if (typeof pattern == "string") {
2335 if (typeof pattern == "string") {
2324 function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}
2336 var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
2325 if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
2337 if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
2326 if (consume !== false) this.pos += pattern.length;
2338 if (consume !== false) this.pos += pattern.length;
2327 return true;
2339 return true;
2328 }
2340 }
2329 } else {
2341 } else {
2330 var match = this.string.slice(this.pos).match(pattern);
2342 var match = this.string.slice(this.pos).match(pattern);
2343 if (match && match.index > 0) return null;
2331 if (match && consume !== false) this.pos += match[0].length;
2344 if (match && consume !== false) this.pos += match[0].length;
2332 return match;
2345 return match;
2333 }
2346 }
2334 },
2347 },
2335 current: function(){return this.string.slice(this.start, this.pos);}
2348 current: function(){return this.string.slice(this.start, this.pos);}
2336 };
2349 };
2337 CodeMirror.StringStream = StringStream;
2350 CodeMirror.StringStream = StringStream;
2338
2351
2339 function MarkedText(from, to, className, marker) {
2352 function MarkedSpan(from, to, marker) {
2340 this.from = from; this.to = to; this.style = className; this.marker = marker;
2353 this.from = from; this.to = to; this.marker = marker;
2341 }
2354 }
2342 MarkedText.prototype = {
2343 attach: function(line) { this.marker.set.push(line); },
2344 detach: function(line) {
2345 var ix = indexOf(this.marker.set, line);
2346 if (ix > -1) this.marker.set.splice(ix, 1);
2347 },
2348 split: function(pos, lenBefore) {
2349 if (this.to <= pos && this.to != null) return null;
2350 var from = this.from < pos || this.from == null ? null : this.from - pos + lenBefore;
2351 var to = this.to == null ? null : this.to - pos + lenBefore;
2352 return new MarkedText(from, to, this.style, this.marker);
2353 },
2354 dup: function() { return new MarkedText(null, null, this.style, this.marker); },
2355 clipTo: function(fromOpen, from, toOpen, to, diff) {
2356 if (fromOpen && to > this.from && (to < this.to || this.to == null))
2357 this.from = null;
2358 else if (this.from != null && this.from >= from)
2359 this.from = Math.max(to, this.from) + diff;
2360 if (toOpen && (from < this.to || this.to == null) && (from > this.from || this.from == null))
2361 this.to = null;
2362 else if (this.to != null && this.to > from)
2363 this.to = to < this.to ? this.to + diff : from;
2364 },
2365 isDead: function() { return this.from != null && this.to != null && this.from >= this.to; },
2366 sameSet: function(x) { return this.marker == x.marker; }
2367 };
2368
2355
2369 function Bookmark(pos) {
2356 function getMarkedSpanFor(spans, marker, del) {
2370 this.from = pos; this.to = pos; this.line = null;
2357 if (spans) for (var i = 0; i < spans.length; ++i) {
2371 }
2358 var span = spans[i];
2372 Bookmark.prototype = {
2359 if (span.marker == marker) {
2373 attach: function(line) { this.line = line; },
2360 if (del) spans.splice(i, 1);
2374 detach: function(line) { if (this.line == line) this.line = null; },
2361 return span;
2375 split: function(pos, lenBefore) {
2376 if (pos < this.from) {
2377 this.from = this.to = (this.from - pos) + lenBefore;
2378 return this;
2379 }
2362 }
2380 },
2363 }
2381 isDead: function() { return this.from > this.to; },
2364 }
2382 clipTo: function(fromOpen, from, toOpen, to, diff) {
2365
2383 if ((fromOpen || from < this.from) && (toOpen || to > this.to)) {
2366 function markedSpansBefore(old, startCh, endCh) {
2384 this.from = 0; this.to = -1;
2367 if (old) for (var i = 0, nw; i < old.length; ++i) {
2385 } else if (this.from > from) {
2368 var span = old[i], marker = span.marker;
2386 this.from = this.to = Math.max(to, this.from) + diff;
2369 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
2387 }
2370 if (startsBefore || marker.type == "bookmark" && span.from == startCh && span.from != endCh) {
2388 },
2371 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
2389 sameSet: function(x) { return false; },
2372 (nw || (nw = [])).push({from: span.from,
2390 find: function() {
2373 to: endsAfter ? null : span.to,
2391 if (!this.line || !this.line.parent) return null;
2374 marker: marker});
2392 return {line: lineNo(this.line), ch: this.from};
2393 },
2394 clear: function() {
2395 if (this.line) {
2396 var found = indexOf(this.line.marked, this);
2397 if (found != -1) this.line.marked.splice(found, 1);
2398 this.line = null;
2399 }
2375 }
2400 }
2376 }
2401 };
2377 return nw;
2378 }
2379
2380 function markedSpansAfter(old, endCh) {
2381 if (old) for (var i = 0, nw; i < old.length; ++i) {
2382 var span = old[i], marker = span.marker;
2383 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
2384 if (endsAfter || marker.type == "bookmark" && span.from == endCh) {
2385 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
2386 (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh,
2387 to: span.to == null ? null : span.to - endCh,
2388 marker: marker});
2389 }
2390 }
2391 return nw;
2392 }
2402
2393
2403 // Line objects. These hold state related to a line, including
2394 function updateMarkedSpans(oldFirst, oldLast, startCh, endCh, newText) {
2404 // highlighting info (the styles array).
2395 if (!oldFirst && !oldLast) return newText;
2405 function Line(text, styles) {
2396 // Get the spans that 'stick out' on both sides
2406 this.styles = styles || [text, null];
2397 var first = markedSpansBefore(oldFirst, startCh);
2407 this.text = text;
2398 var last = markedSpansAfter(oldLast, endCh);
2408 this.height = 1;
2399
2409 this.marked = this.gutterMarker = this.className = this.bgClassName = this.handlers = null;
2400 // Next, merge those two ends
2410 this.stateAfter = this.parent = this.hidden = null;
2401 var sameLine = newText.length == 1, offset = lst(newText).length + (sameLine ? startCh : 0);
2411 }
2402 if (first) {
2412 Line.inheritMarks = function(text, orig) {
2403 // Fix up .to properties of first
2413 var ln = new Line(text), mk = orig && orig.marked;
2404 for (var i = 0; i < first.length; ++i) {
2414 if (mk) {
2405 var span = first[i];
2415 for (var i = 0; i < mk.length; ++i) {
2406 if (span.to == null) {
2416 if (mk[i].to == null && mk[i].style) {
2407 var found = getMarkedSpanFor(last, span.marker);
2417 var newmk = ln.marked || (ln.marked = []), mark = mk[i];
2408 if (!found) span.to = startCh;
2418 var nmark = mark.dup(); newmk.push(nmark); nmark.attach(ln);
2409 else if (sameLine) span.to = found.to == null ? null : found.to + offset;
2419 }
2410 }
2420 }
2411 }
2421 }
2412 }
2422 return ln;
2413 if (last) {
2423 }
2414 // Fix up .from in last (or move them into first in case of sameLine)
2424 Line.prototype = {
2415 for (var i = 0; i < last.length; ++i) {
2425 // Replace a piece of a line, keeping the styles around it intact.
2416 var span = last[i];
2426 replace: function(from, to_, text) {
2417 if (span.to != null) span.to += offset;
2427 var st = [], mk = this.marked, to = to_ == null ? this.text.length : to_;
2418 if (span.from == null) {
2428 copyStyles(0, from, this.styles, st);
2419 var found = getMarkedSpanFor(first, span.marker);
2429 if (text) st.push(text, null);
2420 if (!found) {
2430 copyStyles(to, this.text.length, this.styles, st);
2421 span.from = offset;
2431 this.styles = st;
2422 if (sameLine) (first || (first = [])).push(span);
2432 this.text = this.text.slice(0, from) + text + this.text.slice(to);
2433 this.stateAfter = null;
2434 if (mk) {
2435 var diff = text.length - (to - from);
2436 for (var i = 0; i < mk.length; ++i) {
2437 var mark = mk[i];
2438 mark.clipTo(from == null, from || 0, to_ == null, to, diff);
2439 if (mark.isDead()) {mark.detach(this); mk.splice(i--, 1);}
2440 }
2441 }
2442 },
2443 // Split a part off a line, keeping styles and markers intact.
2444 split: function(pos, textBefore) {
2445 var st = [textBefore, null], mk = this.marked;
2446 copyStyles(pos, this.text.length, this.styles, st);
2447 var taken = new Line(textBefore + this.text.slice(pos), st);
2448 if (mk) {
2449 for (var i = 0; i < mk.length; ++i) {
2450 var mark = mk[i];
2451 var newmark = mark.split(pos, textBefore.length);
2452 if (newmark) {
2453 if (!taken.marked) taken.marked = [];
2454 taken.marked.push(newmark); newmark.attach(taken);
2455 if (newmark == mark) mk.splice(i--, 1);
2456 }
2423 }
2424 } else {
2425 span.from += offset;
2426 if (sameLine) (first || (first = [])).push(span);
2457 }
2427 }
2458 }
2428 }
2459 return taken;
2429 }
2460 },
2430
2461 append: function(line) {
2431 var newMarkers = [newHL(newText[0], first)];
2462 var mylen = this.text.length, mk = line.marked, mymk = this.marked;
2432 if (!sameLine) {
2463 this.text += line.text;
2433 // Fill gap with whole-line-spans
2464 copyStyles(0, line.text.length, line.styles, this.styles);
2434 var gap = newText.length - 2, gapMarkers;
2465 if (mymk) {
2435 if (gap > 0 && first)
2466 for (var i = 0; i < mymk.length; ++i)
2436 for (var i = 0; i < first.length; ++i)
2467 if (mymk[i].to == null) mymk[i].to = mylen;
2437 if (first[i].to == null)
2468 }
2438 (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker});
2469 if (mk && mk.length) {
2439 for (var i = 0; i < gap; ++i)
2470 if (!mymk) this.marked = mymk = [];
2440 newMarkers.push(newHL(newText[i+1], gapMarkers));
2471 outer: for (var i = 0; i < mk.length; ++i) {
2441 newMarkers.push(newHL(lst(newText), last));
2472 var mark = mk[i];
2442 }
2473 if (!mark.from) {
2443 return newMarkers;
2474 for (var j = 0; j < mymk.length; ++j) {
2444 }
2475 var mymark = mymk[j];
2445
2476 if (mymark.to == mylen && mymark.sameSet(mark)) {
2446 // hl stands for history-line, a data structure that can be either a
2477 mymark.to = mark.to == null ? null : mark.to + mylen;
2447 // string (line without markers) or a {text, markedSpans} object.
2478 if (mymark.isDead()) {
2448 function hlText(val) { return typeof val == "string" ? val : val.text; }
2479 mymark.detach(this);
2449 function hlSpans(val) { return typeof val == "string" ? null : val.markedSpans; }
2480 mk.splice(i--, 1);
2450 function newHL(text, spans) { return spans ? {text: text, markedSpans: spans} : text; }
2481 }
2451
2482 continue outer;
2452 function detachMarkedSpans(line) {
2483 }
2453 var spans = line.markedSpans;
2484 }
2454 if (!spans) return;
2485 }
2455 for (var i = 0; i < spans.length; ++i) {
2486 mymk.push(mark);
2456 var lines = spans[i].marker.lines;
2487 mark.attach(this);
2457 var ix = indexOf(lines, line);
2488 mark.from += mylen;
2458 lines.splice(ix, 1);
2489 if (mark.to != null) mark.to += mylen;
2459 }
2490 }
2460 line.markedSpans = null;
2491 }
2461 }
2492 },
2462
2493 fixMarkEnds: function(other) {
2463 function attachMarkedSpans(line, spans) {
2494 var mk = this.marked, omk = other.marked;
2464 if (!spans) return;
2495 if (!mk) return;
2465 for (var i = 0; i < spans.length; ++i)
2496 for (var i = 0; i < mk.length; ++i) {
2466 var marker = spans[i].marker.lines.push(line);
2497 var mark = mk[i], close = mark.to == null;
2467 line.markedSpans = spans;
2498 if (close && omk) {
2468 }
2499 for (var j = 0; j < omk.length; ++j)
2469
2500 if (omk[j].sameSet(mark)) {close = false; break;}
2470 // When measuring the position of the end of a line, different
2501 }
2471 // browsers require different approaches. If an empty span is added,
2502 if (close) mark.to = this.text.length;
2472 // many browsers report bogus offsets. Of those, some (Webkit,
2503 }
2473 // recent IE) will accept a space without moving the whole span to
2504 },
2474 // the next line when wrapping it, others work with a zero-width
2505 fixMarkStarts: function() {
2475 // space.
2506 var mk = this.marked;
2476 var eolSpanContent = " ";
2507 if (!mk) return;
2477 if (gecko || (ie && !ie_lt8)) eolSpanContent = "\u200b";
2508 for (var i = 0; i < mk.length; ++i)
2478 else if (opera) eolSpanContent = "";
2509 if (mk[i].from == null) mk[i].from = 0;
2479
2510 },
2480 // Line objects. These hold state related to a line, including
2511 addMark: function(mark) {
2481 // highlighting info (the styles array).
2512 mark.attach(this);
2482 function Line(text, markedSpans) {
2513 if (this.marked == null) this.marked = [];
2483 this.text = text;
2514 this.marked.push(mark);
2484 this.height = 1;
2515 this.marked.sort(function(a, b){return (a.from || 0) - (b.from || 0);});
2485 attachMarkedSpans(this, markedSpans);
2486 }
2487 Line.prototype = {
2488 update: function(text, markedSpans) {
2489 this.text = text;
2490 this.stateAfter = this.styles = null;
2491 detachMarkedSpans(this);
2492 attachMarkedSpans(this, markedSpans);
2516 },
2493 },
2517 // Run the given mode's parser over a line, update the styles
2494 // Run the given mode's parser over a line, update the styles
2518 // array, which contains alternating fragments of text and CSS
2495 // array, which contains alternating fragments of text and CSS
2519 // classes.
2496 // classes.
2520 highlight: function(mode, state, tabSize) {
2497 highlight: function(mode, state, tabSize) {
2521 var stream = new StringStream(this.text, tabSize), st = this.styles, pos = 0;
2498 var stream = new StringStream(this.text, tabSize), st = this.styles || (this.styles = []);
2522 var changed = false, curWord = st[0], prevWord;
2499 var pos = st.length = 0;
2523 if (this.text == "" && mode.blankLine) mode.blankLine(state);
2500 if (this.text == "" && mode.blankLine) mode.blankLine(state);
2524 while (!stream.eol()) {
2501 while (!stream.eol()) {
2525 var style = mode.token(stream, state);
2502 var style = mode.token(stream, state), substr = stream.current();
2526 var substr = this.text.slice(stream.start, stream.pos);
2527 stream.start = stream.pos;
2503 stream.start = stream.pos;
2528 if (pos && st[pos-1] == style)
2504 if (pos && st[pos-1] == style) {
2529 st[pos-2] += substr;
2505 st[pos-2] += substr;
2530 else if (substr) {
2506 } else if (substr) {
2531 if (!changed && (st[pos+1] != style || (pos && st[pos-2] != prevWord))) changed = true;
2532 st[pos++] = substr; st[pos++] = style;
2507 st[pos++] = substr; st[pos++] = style;
2533 prevWord = curWord; curWord = st[pos];
2534 }
2508 }
2535 // Give up when line is ridiculously long
2509 // Give up when line is ridiculously long
2536 if (stream.pos > 5000) {
2510 if (stream.pos > 5000) {
2537 st[pos++] = this.text.slice(stream.pos); st[pos++] = null;
2511 st[pos++] = this.text.slice(stream.pos); st[pos++] = null;
2538 break;
2512 break;
2539 }
2513 }
2540 }
2514 }
2541 if (st.length != pos) {st.length = pos; changed = true;}
2515 },
2542 if (pos && st[pos-2] != prevWord) changed = true;
2516 process: function(mode, state, tabSize) {
2543 // Short lines with simple highlights return null, and are
2517 var stream = new StringStream(this.text, tabSize);
2544 // counted as changed by the driver because they are likely to
2518 if (this.text == "" && mode.blankLine) mode.blankLine(state);
2545 // highlight the same way in various contexts.
2519 while (!stream.eol() && stream.pos <= 5000) {
2546 return changed || (st.length < 5 && this.text.length < 10 ? null : false);
2520 mode.token(stream, state);
2521 stream.start = stream.pos;
2522 }
2547 },
2523 },
2548 // Fetch the parser token for a given character. Useful for hacks
2524 // Fetch the parser token for a given character. Useful for hacks
2549 // that want to inspect the mode state (say, for completion).
2525 // that want to inspect the mode state (say, for completion).
2550 getTokenAt: function(mode, state, ch) {
2526 getTokenAt: function(mode, state, tabSize, ch) {
2551 var txt = this.text, stream = new StringStream(txt);
2527 var txt = this.text, stream = new StringStream(txt, tabSize);
2552 while (stream.pos < ch && !stream.eol()) {
2528 while (stream.pos < ch && !stream.eol()) {
2553 stream.start = stream.pos;
2529 stream.start = stream.pos;
2554 var style = mode.token(stream, state);
2530 var style = mode.token(stream, state);
2555 }
2531 }
2556 return {start: stream.start,
2532 return {start: stream.start,
2557 end: stream.pos,
2533 end: stream.pos,
2558 string: stream.current(),
2534 string: stream.current(),
2559 className: style || null,
2535 className: style || null,
2560 state: state};
2536 state: state};
2561 },
2537 },
2562 indentation: function(tabSize) {return countColumn(this.text, null, tabSize);},
2538 indentation: function(tabSize) {return countColumn(this.text, null, tabSize);},
2563 // Produces an HTML fragment for the line, taking selection,
2539 // Produces an HTML fragment for the line, taking selection,
2564 // marking, and highlighting into account.
2540 // marking, and highlighting into account.
2565 getHTML: function(makeTab, wrapAt, wrapId, wrapWBR) {
2541 getContent: function(tabSize, wrapAt, compensateForWrapping) {
2566 var html = [], first = true, col = 0;
2542 var first = true, col = 0, specials = /[\t\u0000-\u0019\u200b\u2028\u2029\uFEFF]/g;
2567 function span_(text, style) {
2543 var pre = elt("pre");
2544 function span_(html, text, style) {
2568 if (!text) return;
2545 if (!text) return;
2569 // Work around a bug where, in some compat modes, IE ignores leading spaces
2546 // Work around a bug where, in some compat modes, IE ignores leading spaces
2570 if (first && ie && text.charAt(0) == " ") text = "\u00a0" + text.slice(1);
2547 if (first && ie && text.charAt(0) == " ") text = "\u00a0" + text.slice(1);
2571 first = false;
2548 first = false;
2572 if (text.indexOf("\t") == -1) {
2549 if (!specials.test(text)) {
2573 col += text.length;
2550 col += text.length;
2574 var escaped = htmlEscape(text);
2551 var content = document.createTextNode(text);
2575 } else {
2552 } else {
2576 var escaped = "";
2553 var content = document.createDocumentFragment(), pos = 0;
2577 for (var pos = 0;;) {
2554 while (true) {
2578 var idx = text.indexOf("\t", pos);
2555 specials.lastIndex = pos;
2579 if (idx == -1) {
2556 var m = specials.exec(text);
2580 escaped += htmlEscape(text.slice(pos));
2557 var skipped = m ? m.index - pos : text.length - pos;
2581 col += text.length - pos;
2558 if (skipped) {
2582 break;
2559 content.appendChild(document.createTextNode(text.slice(pos, pos + skipped)));
2560 col += skipped;
2561 }
2562 if (!m) break;
2563 pos += skipped + 1;
2564 if (m[0] == "\t") {
2565 var tabWidth = tabSize - col % tabSize;
2566 content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
2567 col += tabWidth;
2583 } else {
2568 } else {
2584 col += idx - pos;
2569 var token = elt("span", "\u2022", "cm-invalidchar");
2585 var tab = makeTab(col);
2570 token.title = "\\u" + m[0].charCodeAt(0).toString(16);
2586 escaped += htmlEscape(text.slice(pos, idx)) + tab.html;
2571 content.appendChild(token);
2587 col += tab.width;
2572 col += 1;
2588 pos = idx + 1;
2589 }
2573 }
2590 }
2574 }
2591 }
2575 }
2592 if (style) html.push('<span class="', style, '">', escaped, "</span>");
2576 if (style) html.appendChild(elt("span", [content], style));
2593 else html.push(escaped);
2577 else html.appendChild(content);
2594 }
2578 }
2595 var span = span_;
2579 var span = span_;
2596 if (wrapAt != null) {
2580 if (wrapAt != null) {
2597 var outPos = 0, open = "<span id=\"" + wrapId + "\">";
2581 var outPos = 0, anchor = pre.anchor = elt("span");
2598 span = function(text, style) {
2582 span = function(html, text, style) {
2599 var l = text.length;
2583 var l = text.length;
2600 if (wrapAt >= outPos && wrapAt < outPos + l) {
2584 if (wrapAt >= outPos && wrapAt < outPos + l) {
2601 if (wrapAt > outPos) {
2585 if (wrapAt > outPos) {
2602 span_(text.slice(0, wrapAt - outPos), style);
2586 span_(html, text.slice(0, wrapAt - outPos), style);
2603 // See comment at the definition of spanAffectsWrapping
2587 // See comment at the definition of spanAffectsWrapping
2604 if (wrapWBR) html.push("<wbr>");
2588 if (compensateForWrapping) html.appendChild(elt("wbr"));
2605 }
2589 }
2606 html.push(open);
2590 html.appendChild(anchor);
2607 var cut = wrapAt - outPos;
2591 var cut = wrapAt - outPos;
2608 span_(opera ? text.slice(cut, cut + 1) : text.slice(cut), style);
2592 span_(anchor, opera ? text.slice(cut, cut + 1) : text.slice(cut), style);
2609 html.push("</span>");
2593 if (opera) span_(html, text.slice(cut + 1), style);
2610 if (opera) span_(text.slice(cut + 1), style);
2611 wrapAt--;
2594 wrapAt--;
2612 outPos += l;
2595 outPos += l;
2613 } else {
2596 } else {
2614 outPos += l;
2597 outPos += l;
2615 span_(text, style);
2598 span_(html, text, style);
2616 // Output empty wrapper when at end of line
2599 if (outPos == wrapAt && outPos == len) {
2617 if (outPos == wrapAt && outPos == len) html.push(open + " </span>");
2600 setTextContent(anchor, eolSpanContent);
2601 html.appendChild(anchor);
2602 }
2618 // Stop outputting HTML when gone sufficiently far beyond measure
2603 // Stop outputting HTML when gone sufficiently far beyond measure
2619 else if (outPos > wrapAt + 10 && /\s/.test(text)) span = function(){};
2604 else if (outPos > wrapAt + 10 && /\s/.test(text)) span = function(){};
2620 }
2605 }
2621 }
2606 };
2622 }
2607 }
2623
2608
2624 var st = this.styles, allText = this.text, marked = this.marked;
2609 var st = this.styles, allText = this.text, marked = this.markedSpans;
2625 var len = allText.length;
2610 var len = allText.length;
2626 function styleToClass(style) {
2611 function styleToClass(style) {
2627 if (!style) return null;
2612 if (!style) return null;
2628 return "cm-" + style.replace(/ +/g, " cm-");
2613 return "cm-" + style.replace(/ +/g, " cm-");
2629 }
2614 }
2630
2631 if (!allText && wrapAt == null) {
2615 if (!allText && wrapAt == null) {
2632 span(" ");
2616 span(pre, " ");
2633 } else if (!marked || !marked.length) {
2617 } else if (!marked || !marked.length) {
2634 for (var i = 0, ch = 0; ch < len; i+=2) {
2618 for (var i = 0, ch = 0; ch < len; i+=2) {
2635 var str = st[i], style = st[i+1], l = str.length;
2619 var str = st[i], style = st[i+1], l = str.length;
2636 if (ch + l > len) str = str.slice(0, len - ch);
2620 if (ch + l > len) str = str.slice(0, len - ch);
2637 ch += l;
2621 ch += l;
2638 span(str, styleToClass(style));
2622 span(pre, str, styleToClass(style));
2639 }
2623 }
2640 } else {
2624 } else {
2625 marked.sort(function(a, b) { return a.from - b.from; });
2641 var pos = 0, i = 0, text = "", style, sg = 0;
2626 var pos = 0, i = 0, text = "", style, sg = 0;
2642 var nextChange = marked[0].from || 0, marks = [], markpos = 0;
2627 var nextChange = marked[0].from || 0, marks = [], markpos = 0;
2643 function advanceMarks() {
2628 var advanceMarks = function() {
2644 var m;
2629 var m;
2645 while (markpos < marked.length &&
2630 while (markpos < marked.length &&
2646 ((m = marked[markpos]).from == pos || m.from == null)) {
2631 ((m = marked[markpos]).from == pos || m.from == null)) {
2647 if (m.style != null) marks.push(m);
2632 if (m.marker.type == "range") marks.push(m);
2648 ++markpos;
2633 ++markpos;
2649 }
2634 }
2650 nextChange = markpos < marked.length ? marked[markpos].from : Infinity;
2635 nextChange = markpos < marked.length ? marked[markpos].from : Infinity;
2651 for (var i = 0; i < marks.length; ++i) {
2636 for (var i = 0; i < marks.length; ++i) {
2652 var to = marks[i].to || Infinity;
2637 var to = marks[i].to;
2638 if (to == null) to = Infinity;
2653 if (to == pos) marks.splice(i--, 1);
2639 if (to == pos) marks.splice(i--, 1);
2654 else nextChange = Math.min(to, nextChange);
2640 else nextChange = Math.min(to, nextChange);
2655 }
2641 }
2656 }
2642 };
2657 var m = 0;
2643 var m = 0;
2658 while (pos < len) {
2644 while (pos < len) {
2659 if (nextChange == pos) advanceMarks();
2645 if (nextChange == pos) advanceMarks();
2660 var upto = Math.min(len, nextChange);
2646 var upto = Math.min(len, nextChange);
2661 while (true) {
2647 while (true) {
2662 if (text) {
2648 if (text) {
2663 var end = pos + text.length;
2649 var end = pos + text.length;
2664 var appliedStyle = style;
2650 var appliedStyle = style;
2665 for (var j = 0; j < marks.length; ++j)
2651 for (var j = 0; j < marks.length; ++j) {
2666 appliedStyle = (appliedStyle ? appliedStyle + " " : "") + marks[j].style;
2652 var mark = marks[j];
2667 span(end > upto ? text.slice(0, upto - pos) : text, appliedStyle);
2653 appliedStyle = (appliedStyle ? appliedStyle + " " : "") + mark.marker.style;
2654 if (mark.marker.endStyle && mark.to === Math.min(end, upto)) appliedStyle += " " + mark.marker.endStyle;
2655 if (mark.marker.startStyle && mark.from === pos) appliedStyle += " " + mark.marker.startStyle;
2656 }
2657 span(pre, end > upto ? text.slice(0, upto - pos) : text, appliedStyle);
2668 if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
2658 if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
2669 pos = end;
2659 pos = end;
2670 }
2660 }
2671 text = st[i++]; style = styleToClass(st[i++]);
2661 text = st[i++]; style = styleToClass(st[i++]);
2672 }
2662 }
2673 }
2663 }
2674 }
2664 }
2675 return html.join("");
2665 return pre;
2676 },
2666 },
2677 cleanUp: function() {
2667 cleanUp: function() {
2678 this.parent = null;
2668 this.parent = null;
2679 if (this.marked)
2669 detachMarkedSpans(this);
2680 for (var i = 0, e = this.marked.length; i < e; ++i) this.marked[i].detach(this);
2681 }
2670 }
2682 };
2671 };
2683 // Utility used by replace and split above
2684 function copyStyles(from, to, source, dest) {
2685 for (var i = 0, pos = 0, state = 0; pos < to; i+=2) {
2686 var part = source[i], end = pos + part.length;
2687 if (state == 0) {
2688 if (end > from) dest.push(part.slice(from - pos, Math.min(part.length, to - pos)), source[i+1]);
2689 if (end >= from) state = 1;
2690 } else if (state == 1) {
2691 if (end > to) dest.push(part.slice(0, to - pos), source[i+1]);
2692 else dest.push(part, source[i+1]);
2693 }
2694 pos = end;
2695 }
2696 }
2697
2672
2698 // Data structure that holds the sequence of lines.
2673 // Data structure that holds the sequence of lines.
2699 function LeafChunk(lines) {
2674 function LeafChunk(lines) {
2700 this.lines = lines;
2675 this.lines = lines;
2701 this.parent = null;
2676 this.parent = null;
2702 for (var i = 0, e = lines.length, height = 0; i < e; ++i) {
2677 for (var i = 0, e = lines.length, height = 0; i < e; ++i) {
2703 lines[i].parent = this;
2678 lines[i].parent = this;
2704 height += lines[i].height;
2679 height += lines[i].height;
2705 }
2680 }
2706 this.height = height;
2681 this.height = height;
2707 }
2682 }
2708 LeafChunk.prototype = {
2683 LeafChunk.prototype = {
2709 chunkSize: function() { return this.lines.length; },
2684 chunkSize: function() { return this.lines.length; },
2710 remove: function(at, n, callbacks) {
2685 remove: function(at, n, callbacks) {
2711 for (var i = at, e = at + n; i < e; ++i) {
2686 for (var i = at, e = at + n; i < e; ++i) {
2712 var line = this.lines[i];
2687 var line = this.lines[i];
2713 this.height -= line.height;
2688 this.height -= line.height;
2714 line.cleanUp();
2689 line.cleanUp();
2715 if (line.handlers)
2690 if (line.handlers)
2716 for (var j = 0; j < line.handlers.length; ++j) callbacks.push(line.handlers[j]);
2691 for (var j = 0; j < line.handlers.length; ++j) callbacks.push(line.handlers[j]);
2717 }
2692 }
2718 this.lines.splice(at, n);
2693 this.lines.splice(at, n);
2719 },
2694 },
2720 collapse: function(lines) {
2695 collapse: function(lines) {
2721 lines.splice.apply(lines, [lines.length, 0].concat(this.lines));
2696 lines.splice.apply(lines, [lines.length, 0].concat(this.lines));
2722 },
2697 },
2723 insertHeight: function(at, lines, height) {
2698 insertHeight: function(at, lines, height) {
2724 this.height += height;
2699 this.height += height;
2725 this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
2700 this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
2726 for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this;
2701 for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this;
2727 },
2702 },
2728 iterN: function(at, n, op) {
2703 iterN: function(at, n, op) {
2729 for (var e = at + n; at < e; ++at)
2704 for (var e = at + n; at < e; ++at)
2730 if (op(this.lines[at])) return true;
2705 if (op(this.lines[at])) return true;
2731 }
2706 }
2732 };
2707 };
2733 function BranchChunk(children) {
2708 function BranchChunk(children) {
2734 this.children = children;
2709 this.children = children;
2735 var size = 0, height = 0;
2710 var size = 0, height = 0;
2736 for (var i = 0, e = children.length; i < e; ++i) {
2711 for (var i = 0, e = children.length; i < e; ++i) {
2737 var ch = children[i];
2712 var ch = children[i];
2738 size += ch.chunkSize(); height += ch.height;
2713 size += ch.chunkSize(); height += ch.height;
2739 ch.parent = this;
2714 ch.parent = this;
2740 }
2715 }
2741 this.size = size;
2716 this.size = size;
2742 this.height = height;
2717 this.height = height;
2743 this.parent = null;
2718 this.parent = null;
2744 }
2719 }
2745 BranchChunk.prototype = {
2720 BranchChunk.prototype = {
2746 chunkSize: function() { return this.size; },
2721 chunkSize: function() { return this.size; },
2747 remove: function(at, n, callbacks) {
2722 remove: function(at, n, callbacks) {
2748 this.size -= n;
2723 this.size -= n;
2749 for (var i = 0; i < this.children.length; ++i) {
2724 for (var i = 0; i < this.children.length; ++i) {
2750 var child = this.children[i], sz = child.chunkSize();
2725 var child = this.children[i], sz = child.chunkSize();
2751 if (at < sz) {
2726 if (at < sz) {
2752 var rm = Math.min(n, sz - at), oldHeight = child.height;
2727 var rm = Math.min(n, sz - at), oldHeight = child.height;
2753 child.remove(at, rm, callbacks);
2728 child.remove(at, rm, callbacks);
2754 this.height -= oldHeight - child.height;
2729 this.height -= oldHeight - child.height;
2755 if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
2730 if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
2756 if ((n -= rm) == 0) break;
2731 if ((n -= rm) == 0) break;
2757 at = 0;
2732 at = 0;
2758 } else at -= sz;
2733 } else at -= sz;
2759 }
2734 }
2760 if (this.size - n < 25) {
2735 if (this.size - n < 25) {
2761 var lines = [];
2736 var lines = [];
2762 this.collapse(lines);
2737 this.collapse(lines);
2763 this.children = [new LeafChunk(lines)];
2738 this.children = [new LeafChunk(lines)];
2764 this.children[0].parent = this;
2739 this.children[0].parent = this;
2765 }
2740 }
2766 },
2741 },
2767 collapse: function(lines) {
2742 collapse: function(lines) {
2768 for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines);
2743 for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines);
2769 },
2744 },
2770 insert: function(at, lines) {
2745 insert: function(at, lines) {
2771 var height = 0;
2746 var height = 0;
2772 for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height;
2747 for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height;
2773 this.insertHeight(at, lines, height);
2748 this.insertHeight(at, lines, height);
2774 },
2749 },
2775 insertHeight: function(at, lines, height) {
2750 insertHeight: function(at, lines, height) {
2776 this.size += lines.length;
2751 this.size += lines.length;
2777 this.height += height;
2752 this.height += height;
2778 for (var i = 0, e = this.children.length; i < e; ++i) {
2753 for (var i = 0, e = this.children.length; i < e; ++i) {
2779 var child = this.children[i], sz = child.chunkSize();
2754 var child = this.children[i], sz = child.chunkSize();
2780 if (at <= sz) {
2755 if (at <= sz) {
2781 child.insertHeight(at, lines, height);
2756 child.insertHeight(at, lines, height);
2782 if (child.lines && child.lines.length > 50) {
2757 if (child.lines && child.lines.length > 50) {
2783 while (child.lines.length > 50) {
2758 while (child.lines.length > 50) {
2784 var spilled = child.lines.splice(child.lines.length - 25, 25);
2759 var spilled = child.lines.splice(child.lines.length - 25, 25);
2785 var newleaf = new LeafChunk(spilled);
2760 var newleaf = new LeafChunk(spilled);
2786 child.height -= newleaf.height;
2761 child.height -= newleaf.height;
2787 this.children.splice(i + 1, 0, newleaf);
2762 this.children.splice(i + 1, 0, newleaf);
2788 newleaf.parent = this;
2763 newleaf.parent = this;
2789 }
2764 }
2790 this.maybeSpill();
2765 this.maybeSpill();
2791 }
2766 }
2792 break;
2767 break;
2793 }
2768 }
2794 at -= sz;
2769 at -= sz;
2795 }
2770 }
2796 },
2771 },
2797 maybeSpill: function() {
2772 maybeSpill: function() {
2798 if (this.children.length <= 10) return;
2773 if (this.children.length <= 10) return;
2799 var me = this;
2774 var me = this;
2800 do {
2775 do {
2801 var spilled = me.children.splice(me.children.length - 5, 5);
2776 var spilled = me.children.splice(me.children.length - 5, 5);
2802 var sibling = new BranchChunk(spilled);
2777 var sibling = new BranchChunk(spilled);
2803 if (!me.parent) { // Become the parent node
2778 if (!me.parent) { // Become the parent node
2804 var copy = new BranchChunk(me.children);
2779 var copy = new BranchChunk(me.children);
2805 copy.parent = me;
2780 copy.parent = me;
2806 me.children = [copy, sibling];
2781 me.children = [copy, sibling];
2807 me = copy;
2782 me = copy;
2808 } else {
2783 } else {
2809 me.size -= sibling.size;
2784 me.size -= sibling.size;
2810 me.height -= sibling.height;
2785 me.height -= sibling.height;
2811 var myIndex = indexOf(me.parent.children, me);
2786 var myIndex = indexOf(me.parent.children, me);
2812 me.parent.children.splice(myIndex + 1, 0, sibling);
2787 me.parent.children.splice(myIndex + 1, 0, sibling);
2813 }
2788 }
2814 sibling.parent = me.parent;
2789 sibling.parent = me.parent;
2815 } while (me.children.length > 10);
2790 } while (me.children.length > 10);
2816 me.parent.maybeSpill();
2791 me.parent.maybeSpill();
2817 },
2792 },
2818 iter: function(from, to, op) { this.iterN(from, to - from, op); },
2793 iter: function(from, to, op) { this.iterN(from, to - from, op); },
2819 iterN: function(at, n, op) {
2794 iterN: function(at, n, op) {
2820 for (var i = 0, e = this.children.length; i < e; ++i) {
2795 for (var i = 0, e = this.children.length; i < e; ++i) {
2821 var child = this.children[i], sz = child.chunkSize();
2796 var child = this.children[i], sz = child.chunkSize();
2822 if (at < sz) {
2797 if (at < sz) {
2823 var used = Math.min(n, sz - at);
2798 var used = Math.min(n, sz - at);
2824 if (child.iterN(at, used, op)) return true;
2799 if (child.iterN(at, used, op)) return true;
2825 if ((n -= used) == 0) break;
2800 if ((n -= used) == 0) break;
2826 at = 0;
2801 at = 0;
2827 } else at -= sz;
2802 } else at -= sz;
2828 }
2803 }
2829 }
2804 }
2830 };
2805 };
2831
2806
2832 function getLineAt(chunk, n) {
2807 function getLineAt(chunk, n) {
2833 while (!chunk.lines) {
2808 while (!chunk.lines) {
2834 for (var i = 0;; ++i) {
2809 for (var i = 0;; ++i) {
2835 var child = chunk.children[i], sz = child.chunkSize();
2810 var child = chunk.children[i], sz = child.chunkSize();
2836 if (n < sz) { chunk = child; break; }
2811 if (n < sz) { chunk = child; break; }
2837 n -= sz;
2812 n -= sz;
2838 }
2813 }
2839 }
2814 }
2840 return chunk.lines[n];
2815 return chunk.lines[n];
2841 }
2816 }
2842 function lineNo(line) {
2817 function lineNo(line) {
2843 if (line.parent == null) return null;
2818 if (line.parent == null) return null;
2844 var cur = line.parent, no = indexOf(cur.lines, line);
2819 var cur = line.parent, no = indexOf(cur.lines, line);
2845 for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
2820 for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
2846 for (var i = 0, e = chunk.children.length; ; ++i) {
2821 for (var i = 0, e = chunk.children.length; ; ++i) {
2847 if (chunk.children[i] == cur) break;
2822 if (chunk.children[i] == cur) break;
2848 no += chunk.children[i].chunkSize();
2823 no += chunk.children[i].chunkSize();
2849 }
2824 }
2850 }
2825 }
2851 return no;
2826 return no;
2852 }
2827 }
2853 function lineAtHeight(chunk, h) {
2828 function lineAtHeight(chunk, h) {
2854 var n = 0;
2829 var n = 0;
2855 outer: do {
2830 outer: do {
2856 for (var i = 0, e = chunk.children.length; i < e; ++i) {
2831 for (var i = 0, e = chunk.children.length; i < e; ++i) {
2857 var child = chunk.children[i], ch = child.height;
2832 var child = chunk.children[i], ch = child.height;
2858 if (h < ch) { chunk = child; continue outer; }
2833 if (h < ch) { chunk = child; continue outer; }
2859 h -= ch;
2834 h -= ch;
2860 n += child.chunkSize();
2835 n += child.chunkSize();
2861 }
2836 }
2862 return n;
2837 return n;
2863 } while (!chunk.lines);
2838 } while (!chunk.lines);
2864 for (var i = 0, e = chunk.lines.length; i < e; ++i) {
2839 for (var i = 0, e = chunk.lines.length; i < e; ++i) {
2865 var line = chunk.lines[i], lh = line.height;
2840 var line = chunk.lines[i], lh = line.height;
2866 if (h < lh) break;
2841 if (h < lh) break;
2867 h -= lh;
2842 h -= lh;
2868 }
2843 }
2869 return n + i;
2844 return n + i;
2870 }
2845 }
2871 function heightAtLine(chunk, n) {
2846 function heightAtLine(chunk, n) {
2872 var h = 0;
2847 var h = 0;
2873 outer: do {
2848 outer: do {
2874 for (var i = 0, e = chunk.children.length; i < e; ++i) {
2849 for (var i = 0, e = chunk.children.length; i < e; ++i) {
2875 var child = chunk.children[i], sz = child.chunkSize();
2850 var child = chunk.children[i], sz = child.chunkSize();
2876 if (n < sz) { chunk = child; continue outer; }
2851 if (n < sz) { chunk = child; continue outer; }
2877 n -= sz;
2852 n -= sz;
2878 h += child.height;
2853 h += child.height;
2879 }
2854 }
2880 return h;
2855 return h;
2881 } while (!chunk.lines);
2856 } while (!chunk.lines);
2882 for (var i = 0; i < n; ++i) h += chunk.lines[i].height;
2857 for (var i = 0; i < n; ++i) h += chunk.lines[i].height;
2883 return h;
2858 return h;
2884 }
2859 }
2885
2860
2886 // The history object 'chunks' changes that are made close together
2861 // The history object 'chunks' changes that are made close together
2887 // and at almost the same time into bigger undoable units.
2862 // and at almost the same time into bigger undoable units.
2888 function History() {
2863 function History() {
2889 this.time = 0;
2864 this.time = 0;
2890 this.done = []; this.undone = [];
2865 this.done = []; this.undone = [];
2891 this.compound = 0;
2866 this.compound = 0;
2892 this.closed = false;
2867 this.closed = false;
2893 }
2868 }
2894 History.prototype = {
2869 History.prototype = {
2895 addChange: function(start, added, old) {
2870 addChange: function(start, added, old) {
2896 this.undone.length = 0;
2871 this.undone.length = 0;
2897 var time = +new Date, cur = this.done[this.done.length - 1], last = cur && cur[cur.length - 1];
2872 var time = +new Date, cur = lst(this.done), last = cur && lst(cur);
2898 var dtime = time - this.time;
2873 var dtime = time - this.time;
2899
2874
2900 if (this.compound && cur && !this.closed) {
2875 if (this.compound && cur && !this.closed) {
2901 cur.push({start: start, added: added, old: old});
2876 cur.push({start: start, added: added, old: old});
2902 } else if (dtime > 400 || !last || this.closed ||
2877 } else if (dtime > 400 || !last || this.closed ||
2903 last.start > start + old.length || last.start + last.added < start) {
2878 last.start > start + old.length || last.start + last.added < start) {
2904 this.done.push([{start: start, added: added, old: old}]);
2879 this.done.push([{start: start, added: added, old: old}]);
2905 this.closed = false;
2880 this.closed = false;
2906 } else {
2881 } else {
2907 var startBefore = Math.max(0, last.start - start),
2882 var startBefore = Math.max(0, last.start - start),
2908 endAfter = Math.max(0, (start + old.length) - (last.start + last.added));
2883 endAfter = Math.max(0, (start + old.length) - (last.start + last.added));
2909 for (var i = startBefore; i > 0; --i) last.old.unshift(old[i - 1]);
2884 for (var i = startBefore; i > 0; --i) last.old.unshift(old[i - 1]);
2910 for (var i = endAfter; i > 0; --i) last.old.push(old[old.length - i]);
2885 for (var i = endAfter; i > 0; --i) last.old.push(old[old.length - i]);
2911 if (startBefore) last.start = start;
2886 if (startBefore) last.start = start;
2912 last.added += added - (old.length - startBefore - endAfter);
2887 last.added += added - (old.length - startBefore - endAfter);
2913 }
2888 }
2914 this.time = time;
2889 this.time = time;
2915 },
2890 },
2916 startCompound: function() {
2891 startCompound: function() {
2917 if (!this.compound++) this.closed = true;
2892 if (!this.compound++) this.closed = true;
2918 },
2893 },
2919 endCompound: function() {
2894 endCompound: function() {
2920 if (!--this.compound) this.closed = true;
2895 if (!--this.compound) this.closed = true;
2921 }
2896 }
2922 };
2897 };
2923
2898
2924 function stopMethod() {e_stop(this);}
2899 function stopMethod() {e_stop(this);}
2925 // Ensure an event has a stop method.
2900 // Ensure an event has a stop method.
2926 function addStop(event) {
2901 function addStop(event) {
2927 if (!event.stop) event.stop = stopMethod;
2902 if (!event.stop) event.stop = stopMethod;
2928 return event;
2903 return event;
2929 }
2904 }
2930
2905
2931 function e_preventDefault(e) {
2906 function e_preventDefault(e) {
2932 if (e.preventDefault) e.preventDefault();
2907 if (e.preventDefault) e.preventDefault();
2933 else e.returnValue = false;
2908 else e.returnValue = false;
2934 }
2909 }
2935 function e_stopPropagation(e) {
2910 function e_stopPropagation(e) {
2936 if (e.stopPropagation) e.stopPropagation();
2911 if (e.stopPropagation) e.stopPropagation();
2937 else e.cancelBubble = true;
2912 else e.cancelBubble = true;
2938 }
2913 }
2939 function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
2914 function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
2940 CodeMirror.e_stop = e_stop;
2915 CodeMirror.e_stop = e_stop;
2941 CodeMirror.e_preventDefault = e_preventDefault;
2916 CodeMirror.e_preventDefault = e_preventDefault;
2942 CodeMirror.e_stopPropagation = e_stopPropagation;
2917 CodeMirror.e_stopPropagation = e_stopPropagation;
2943
2918
2944 function e_target(e) {return e.target || e.srcElement;}
2919 function e_target(e) {return e.target || e.srcElement;}
2945 function e_button(e) {
2920 function e_button(e) {
2946 if (e.which) return e.which;
2921 var b = e.which;
2947 else if (e.button & 1) return 1;
2922 if (b == null) {
2948 else if (e.button & 2) return 3;
2923 if (e.button & 1) b = 1;
2949 else if (e.button & 4) return 2;
2924 else if (e.button & 2) b = 3;
2925 else if (e.button & 4) b = 2;
2926 }
2927 if (mac && e.ctrlKey && b == 1) b = 3;
2928 return b;
2950 }
2929 }
2951
2930
2952 // Allow 3rd-party code to override event properties by adding an override
2931 // Allow 3rd-party code to override event properties by adding an override
2953 // object to an event object.
2932 // object to an event object.
2954 function e_prop(e, prop) {
2933 function e_prop(e, prop) {
2955 var overridden = e.override && e.override.hasOwnProperty(prop);
2934 var overridden = e.override && e.override.hasOwnProperty(prop);
2956 return overridden ? e.override[prop] : e[prop];
2935 return overridden ? e.override[prop] : e[prop];
2957 }
2936 }
2958
2937
2959 // Event handler registration. If disconnect is true, it'll return a
2938 // Event handler registration. If disconnect is true, it'll return a
2960 // function that unregisters the handler.
2939 // function that unregisters the handler.
2961 function connect(node, type, handler, disconnect) {
2940 function connect(node, type, handler, disconnect) {
2962 if (typeof node.addEventListener == "function") {
2941 if (typeof node.addEventListener == "function") {
2963 node.addEventListener(type, handler, false);
2942 node.addEventListener(type, handler, false);
2964 if (disconnect) return function() {node.removeEventListener(type, handler, false);};
2943 if (disconnect) return function() {node.removeEventListener(type, handler, false);};
2965 } else {
2944 } else {
2966 var wrapHandler = function(event) {handler(event || window.event);};
2945 var wrapHandler = function(event) {handler(event || window.event);};
2967 node.attachEvent("on" + type, wrapHandler);
2946 node.attachEvent("on" + type, wrapHandler);
2968 if (disconnect) return function() {node.detachEvent("on" + type, wrapHandler);};
2947 if (disconnect) return function() {node.detachEvent("on" + type, wrapHandler);};
2969 }
2948 }
2970 }
2949 }
2971 CodeMirror.connect = connect;
2950 CodeMirror.connect = connect;
2972
2951
2973 function Delayed() {this.id = null;}
2952 function Delayed() {this.id = null;}
2974 Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
2953 Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
2975
2954
2976 var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
2955 var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
2977
2956
2978 var gecko = /gecko\/\d{7}/i.test(navigator.userAgent);
2979 var ie = /MSIE \d/.test(navigator.userAgent);
2980 var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent);
2981 var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent);
2982 var quirksMode = ie && document.documentMode == 5;
2983 var webkit = /WebKit\//.test(navigator.userAgent);
2984 var chrome = /Chrome\//.test(navigator.userAgent);
2985 var opera = /Opera\//.test(navigator.userAgent);
2986 var safari = /Apple Computer/.test(navigator.vendor);
2987 var khtml = /KHTML\//.test(navigator.userAgent);
2988 var mac_geLion = /Mac OS X 10\D([7-9]|\d\d)\D/.test(navigator.userAgent);
2989
2990 // Detect drag-and-drop
2957 // Detect drag-and-drop
2991 var dragAndDrop = function() {
2958 var dragAndDrop = function() {
2992 // There is *some* kind of drag-and-drop support in IE6-8, but I
2959 // There is *some* kind of drag-and-drop support in IE6-8, but I
2993 // couldn't get it to work yet.
2960 // couldn't get it to work yet.
2994 if (ie_lt9) return false;
2961 if (ie_lt9) return false;
2995 var div = document.createElement('div');
2962 var div = elt('div');
2996 return "draggable" in div || "dragDrop" in div;
2963 return "draggable" in div || "dragDrop" in div;
2997 }();
2964 }();
2998
2965
2999 // Feature-detect whether newlines in textareas are converted to \r\n
2966 // Feature-detect whether newlines in textareas are converted to \r\n
3000 var lineSep = function () {
2967 var lineSep = function () {
3001 var te = document.createElement("textarea");
2968 var te = elt("textarea");
3002 te.value = "foo\nbar";
2969 te.value = "foo\nbar";
3003 if (te.value.indexOf("\r") > -1) return "\r\n";
2970 if (te.value.indexOf("\r") > -1) return "\r\n";
3004 return "\n";
2971 return "\n";
3005 }();
2972 }();
3006
2973
3007 // For a reason I have yet to figure out, some browsers disallow
2974 // For a reason I have yet to figure out, some browsers disallow
3008 // word wrapping between certain characters *only* if a new inline
2975 // word wrapping between certain characters *only* if a new inline
3009 // element is started between them. This makes it hard to reliably
2976 // element is started between them. This makes it hard to reliably
3010 // measure the position of things, since that requires inserting an
2977 // measure the position of things, since that requires inserting an
3011 // extra span. This terribly fragile set of regexps matches the
2978 // extra span. This terribly fragile set of regexps matches the
3012 // character combinations that suffer from this phenomenon on the
2979 // character combinations that suffer from this phenomenon on the
3013 // various browsers.
2980 // various browsers.
3014 var spanAffectsWrapping = /^$/; // Won't match any two-character string
2981 var spanAffectsWrapping = /^$/; // Won't match any two-character string
3015 if (gecko) spanAffectsWrapping = /$'/;
2982 if (gecko) spanAffectsWrapping = /$'/;
3016 else if (safari) spanAffectsWrapping = /\-[^ \-?]|\?[^ !'\"\),.\-\/:;\?\]\}]/;
2983 else if (safari) spanAffectsWrapping = /\-[^ \-?]|\?[^ !'\"\),.\-\/:;\?\]\}]/;
3017 else if (chrome) spanAffectsWrapping = /\-[^ \-\.?]|\?[^ \-\.?\]\}:;!'\"\),\/]|[\.!\"#&%\)*+,:;=>\]|\}~][\(\{\[<]|\$'/;
2984 else if (chrome) spanAffectsWrapping = /\-[^ \-\.?]|\?[^ \-\.?\]\}:;!'\"\),\/]|[\.!\"#&%\)*+,:;=>\]|\}~][\(\{\[<]|\$'/;
3018
2985
3019 // Counts the column offset in a string, taking tabs into account.
2986 // Counts the column offset in a string, taking tabs into account.
3020 // Used mostly to find indentation.
2987 // Used mostly to find indentation.
3021 function countColumn(string, end, tabSize) {
2988 function countColumn(string, end, tabSize) {
3022 if (end == null) {
2989 if (end == null) {
3023 end = string.search(/[^\s\u00a0]/);
2990 end = string.search(/[^\s\u00a0]/);
3024 if (end == -1) end = string.length;
2991 if (end == -1) end = string.length;
3025 }
2992 }
3026 for (var i = 0, n = 0; i < end; ++i) {
2993 for (var i = 0, n = 0; i < end; ++i) {
3027 if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
2994 if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
3028 else ++n;
2995 else ++n;
3029 }
2996 }
3030 return n;
2997 return n;
3031 }
2998 }
3032
2999
3033 function computedStyle(elt) {
3034 if (elt.currentStyle) return elt.currentStyle;
3035 return window.getComputedStyle(elt, null);
3036 }
3037
3038 // Find the position of an element by following the offsetParent chain.
3039 // If screen==true, it returns screen (rather than page) coordinates.
3040 function eltOffset(node, screen) {
3000 function eltOffset(node, screen) {
3041 var bod = node.ownerDocument.body;
3042 var x = 0, y = 0, skipBody = false;
3043 for (var n = node; n; n = n.offsetParent) {
3044 var ol = n.offsetLeft, ot = n.offsetTop;
3045 // Firefox reports weird inverted offsets when the body has a border.
3046 if (n == bod) { x += Math.abs(ol); y += Math.abs(ot); }
3047 else { x += ol, y += ot; }
3048 if (screen && computedStyle(n).position == "fixed")
3049 skipBody = true;
3050 }
3051 var e = screen && !skipBody ? null : bod;
3052 for (var n = node.parentNode; n != e; n = n.parentNode)
3053 if (n.scrollLeft != null) { x -= n.scrollLeft; y -= n.scrollTop;}
3054 return {left: x, top: y};
3055 }
3056 // Use the faster and saner getBoundingClientRect method when possible.
3057 if (document.documentElement.getBoundingClientRect != null) eltOffset = function(node, screen) {
3058 // Take the parts of bounding client rect that we are interested in so we are able to edit if need be,
3001 // Take the parts of bounding client rect that we are interested in so we are able to edit if need be,
3059 // since the returned value cannot be changed externally (they are kept in sync as the element moves within the page)
3002 // since the returned value cannot be changed externally (they are kept in sync as the element moves within the page)
3060 try { var box = node.getBoundingClientRect(); box = { top: box.top, left: box.left }; }
3003 try { var box = node.getBoundingClientRect(); box = { top: box.top, left: box.left }; }
3061 catch(e) { box = {top: 0, left: 0}; }
3004 catch(e) { box = {top: 0, left: 0}; }
3062 if (!screen) {
3005 if (!screen) {
3063 // Get the toplevel scroll, working around browser differences.
3006 // Get the toplevel scroll, working around browser differences.
3064 if (window.pageYOffset == null) {
3007 if (window.pageYOffset == null) {
3065 var t = document.documentElement || document.body.parentNode;
3008 var t = document.documentElement || document.body.parentNode;
3066 if (t.scrollTop == null) t = document.body;
3009 if (t.scrollTop == null) t = document.body;
3067 box.top += t.scrollTop; box.left += t.scrollLeft;
3010 box.top += t.scrollTop; box.left += t.scrollLeft;
3068 } else {
3011 } else {
3069 box.top += window.pageYOffset; box.left += window.pageXOffset;
3012 box.top += window.pageYOffset; box.left += window.pageXOffset;
3070 }
3013 }
3071 }
3014 }
3072 return box;
3015 return box;
3073 };
3016 }
3074
3017
3075 // Get a node's text content.
3076 function eltText(node) {
3018 function eltText(node) {
3077 return node.textContent || node.innerText || node.nodeValue || "";
3019 return node.textContent || node.innerText || node.nodeValue || "";
3078 }
3020 }
3021
3022 var spaceStrs = [""];
3023 function spaceStr(n) {
3024 while (spaceStrs.length <= n)
3025 spaceStrs.push(lst(spaceStrs) + " ");
3026 return spaceStrs[n];
3027 }
3028
3029 function lst(arr) { return arr[arr.length-1]; }
3030
3079 function selectInput(node) {
3031 function selectInput(node) {
3080 if (ios) { // Mobile Safari apparently has a bug where select() is broken.
3032 if (ios) { // Mobile Safari apparently has a bug where select() is broken.
3081 node.selectionStart = 0;
3033 node.selectionStart = 0;
3082 node.selectionEnd = node.value.length;
3034 node.selectionEnd = node.value.length;
3083 } else node.select();
3035 } else node.select();
3084 }
3036 }
3085
3037
3086 // Operations on {line, ch} objects.
3038 // Operations on {line, ch} objects.
3087 function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
3039 function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
3088 function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
3040 function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
3089 function copyPos(x) {return {line: x.line, ch: x.ch};}
3041 function copyPos(x) {return {line: x.line, ch: x.ch};}
3090
3042
3091 var escapeElement = document.createElement("pre");
3043 function elt(tag, content, className, style) {
3092 function htmlEscape(str) {
3044 var e = document.createElement(tag);
3093 escapeElement.textContent = str;
3045 if (className) e.className = className;
3094 return escapeElement.innerHTML;
3046 if (style) e.style.cssText = style;
3047 if (typeof content == "string") setTextContent(e, content);
3048 else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
3049 return e;
3095 }
3050 }
3096 // Recent (late 2011) Opera betas insert bogus newlines at the start
3051 function removeChildren(e) {
3097 // of the textContent, so we strip those.
3052 e.innerHTML = "";
3098 if (htmlEscape("a") == "\na") {
3053 return e;
3099 htmlEscape = function(str) {
3054 }
3100 escapeElement.textContent = str;
3055 function removeChildrenAndAdd(parent, e) {
3101 return escapeElement.innerHTML.slice(1);
3056 removeChildren(parent).appendChild(e);
3102 };
3103 // Some IEs don't preserve tabs through innerHTML
3104 } else if (htmlEscape("\t") != "\t") {
3105 htmlEscape = function(str) {
3106 escapeElement.innerHTML = "";
3107 escapeElement.appendChild(document.createTextNode(str));
3108 return escapeElement.innerHTML;
3109 };
3110 }
3057 }
3111 CodeMirror.htmlEscape = htmlEscape;
3058 function setTextContent(e, str) {
3059 if (ie_lt9) {
3060 e.innerHTML = "";
3061 e.appendChild(document.createTextNode(str));
3062 } else e.textContent = str;
3063 }
3112
3064
3113 // Used to position the cursor after an undo/redo by finding the
3065 // Used to position the cursor after an undo/redo by finding the
3114 // last edited character.
3066 // last edited character.
3115 function editEnd(from, to) {
3067 function editEnd(from, to) {
3116 if (!to) return 0;
3068 if (!to) return 0;
3117 if (!from) return to.length;
3069 if (!from) return to.length;
3118 for (var i = from.length, j = to.length; i >= 0 && j >= 0; --i, --j)
3070 for (var i = from.length, j = to.length; i >= 0 && j >= 0; --i, --j)
3119 if (from.charAt(i) != to.charAt(j)) break;
3071 if (from.charAt(i) != to.charAt(j)) break;
3120 return j + 1;
3072 return j + 1;
3121 }
3073 }
3122
3074
3123 function indexOf(collection, elt) {
3075 function indexOf(collection, elt) {
3124 if (collection.indexOf) return collection.indexOf(elt);
3076 if (collection.indexOf) return collection.indexOf(elt);
3125 for (var i = 0, e = collection.length; i < e; ++i)
3077 for (var i = 0, e = collection.length; i < e; ++i)
3126 if (collection[i] == elt) return i;
3078 if (collection[i] == elt) return i;
3127 return -1;
3079 return -1;
3128 }
3080 }
3129 function isWordChar(ch) {
3081 function isWordChar(ch) {
3130 return /\w/.test(ch) || ch.toUpperCase() != ch.toLowerCase();
3082 return /\w/.test(ch) || ch.toUpperCase() != ch.toLowerCase();
3131 }
3083 }
3132
3084
3133 // See if "".split is the broken IE version, if so, provide an
3085 // See if "".split is the broken IE version, if so, provide an
3134 // alternative way to split lines.
3086 // alternative way to split lines.
3135 var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
3087 var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
3136 var pos = 0, nl, result = [];
3088 var pos = 0, result = [], l = string.length;
3137 while ((nl = string.indexOf("\n", pos)) > -1) {
3089 while (pos <= l) {
3138 result.push(string.slice(pos, string.charAt(nl-1) == "\r" ? nl - 1 : nl));
3090 var nl = string.indexOf("\n", pos);
3139 pos = nl + 1;
3091 if (nl == -1) nl = string.length;
3092 var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
3093 var rt = line.indexOf("\r");
3094 if (rt != -1) {
3095 result.push(line.slice(0, rt));
3096 pos += rt + 1;
3097 } else {
3098 result.push(line);
3099 pos = nl + 1;
3100 }
3140 }
3101 }
3141 result.push(string.slice(pos));
3142 return result;
3102 return result;
3143 } : function(string){return string.split(/\r?\n/);};
3103 } : function(string){return string.split(/\r\n?|\n/);};
3144 CodeMirror.splitLines = splitLines;
3104 CodeMirror.splitLines = splitLines;
3145
3105
3146 var hasSelection = window.getSelection ? function(te) {
3106 var hasSelection = window.getSelection ? function(te) {
3147 try { return te.selectionStart != te.selectionEnd; }
3107 try { return te.selectionStart != te.selectionEnd; }
3148 catch(e) { return false; }
3108 catch(e) { return false; }
3149 } : function(te) {
3109 } : function(te) {
3150 try {var range = te.ownerDocument.selection.createRange();}
3110 try {var range = te.ownerDocument.selection.createRange();}
3151 catch(e) {}
3111 catch(e) {}
3152 if (!range || range.parentElement() != te) return false;
3112 if (!range || range.parentElement() != te) return false;
3153 return range.compareEndPoints("StartToEnd", range) != 0;
3113 return range.compareEndPoints("StartToEnd", range) != 0;
3154 };
3114 };
3155
3115
3156 CodeMirror.defineMode("null", function() {
3116 CodeMirror.defineMode("null", function() {
3157 return {token: function(stream) {stream.skipToEnd();}};
3117 return {token: function(stream) {stream.skipToEnd();}};
3158 });
3118 });
3159 CodeMirror.defineMIME("text/plain", "null");
3119 CodeMirror.defineMIME("text/plain", "null");
3160
3120
3161 var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
3121 var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
3162 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
3122 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
3163 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
3123 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
3164 46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete",
3124 46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete",
3165 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
3125 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
3166 221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home",
3126 221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home",
3167 63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"};
3127 63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"};
3168 CodeMirror.keyNames = keyNames;
3128 CodeMirror.keyNames = keyNames;
3169 (function() {
3129 (function() {
3170 // Number keys
3130 // Number keys
3171 for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i);
3131 for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i);
3172 // Alphabetic keys
3132 // Alphabetic keys
3173 for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
3133 for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
3174 // Function keys
3134 // Function keys
3175 for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
3135 for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
3176 })();
3136 })();
3177
3137
3138 CodeMirror.version = "2.34";
3139
3178 return CodeMirror;
3140 return CodeMirror;
3179 })();
3141 })();
General Comments 0
You need to be logged in to leave comments. Login now