raddocs 0.1.0 → 0.1.1

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