codemirror-rails 0.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,16 @@
1
+ CodeMirror for Rails 3
2
+ ======================
3
+
4
+ Generator to install current version of CodeMirror 2 into a
5
+ Rails 3 project.
6
+
7
+ ```
8
+ rails generate codemirror:install
9
+ ```
10
+
11
+ TODO:
12
+
13
+ * Suppport for the Rails 3.1+ asset pipline
14
+ * Optionally install additional modes (currently only plain text)
15
+ * View helpers?
16
+ * JS initialization example for a basic CodeMirror textarea
@@ -0,0 +1,12 @@
1
+ Gem::Specification.new do |s|
2
+ s.name = 'codemirror-rails'
3
+ s.version = '0.1'
4
+ s.date = '2011-06-17'
5
+ s.authors = ['Nathan Fixler']
6
+ s.email = 'nathan@fixler.org'
7
+ s.summary = 'Use CodeMirror with Rails 3'
8
+ s.description = 'This gem provides CodeMirror assets for your Rails 3 application.'
9
+ s.homepage = 'https://github.com/fixlr/codemirror-rails'
10
+
11
+ s.files = Dir["#{File.dirname(__FILE__)}/**/*"]
12
+ end
@@ -0,0 +1,19 @@
1
+ Copyright (C) 2011 by Marijn Haverbeke <marijnh@gmail.com>
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ THE SOFTWARE.
@@ -0,0 +1 @@
1
+ require 'codemirror/rails'
@@ -0,0 +1,8 @@
1
+ module Codemirror
2
+ module Rails
3
+ if ::Rails.version < "3.1"
4
+ require 'codemirror/rails/railtie'
5
+ end
6
+ require 'codemirror/rails/version'
7
+ end
8
+ end
@@ -0,0 +1,10 @@
1
+ # Configure Rails 3.0 to use public/javascripts/codemirror et al
2
+ module Codemirror
3
+ module Rails
4
+ class Railtie < ::Rails::Railtie
5
+ config.before_configuration do
6
+ config.action_view.javascript_expansions[:defaults] << 'codemirror'
7
+ end
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,6 @@
1
+ module Codemirror
2
+ module Rails
3
+ VERSION = '0.0.0'
4
+ CODEMIRROR_VERSION = '2.1'
5
+ end
6
+ end
@@ -0,0 +1,17 @@
1
+ require 'rails'
2
+
3
+ module Codemirror
4
+ module Generators
5
+ class InstallGenerator < ::Rails::Generators::Base
6
+ desc "This generator installs CodeMirror #{Codemirror::Rails::CODEMIRROR_VERSION}"
7
+ source_root File.expand_path('../../../../../vendor/assets/', __FILE__)
8
+
9
+ def copy_codemirror
10
+ say_status("copying", "CodeMirror #{Codemirror::Rails::CODEMIRROR_VERSION}", :green)
11
+ copy_file "javascripts/codemirror.js", "public/javascripts/codemirror.js"
12
+ copy_file "stylesheets/codemirror.css", "public/stylesheets/codemirror.css"
13
+ copy_file "stylesheets/codemirror/themes/default.css", "public/stylesheets/codemirror/themes/default.css"
14
+ end
15
+ end
16
+ end
17
+ end if ::Rails.version < "3.1"
@@ -0,0 +1,2071 @@
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. It's
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
+ var targetDocument = options["document"];
17
+ // The element in which the editor lives.
18
+ var wrapper = targetDocument.createElement("div");
19
+ wrapper.className = "CodeMirror";
20
+ // This mess creates the base DOM structure for the editor.
21
+ wrapper.innerHTML =
22
+ '<div style="overflow: hidden; position: relative; width: 1px; height: 0px;">' + // Wraps and hides input textarea
23
+ '<textarea style="position: absolute; width: 2px;" wrap="off"></textarea></div>' +
24
+ '<div class="CodeMirror-scroll cm-s-' + options.theme + '">' +
25
+ '<div style="position: relative">' + // Set to the height of the text, causes scrolling
26
+ '<div style="position: absolute; height: 0; width: 0; overflow: hidden;"></div>' +
27
+ '<div style="position: relative">' + // Moved around its parent to cover visible view
28
+ '<div class="CodeMirror-gutter"><div class="CodeMirror-gutter-text"></div></div>' +
29
+ // Provides positioning relative to (visible) text origin
30
+ '<div class="CodeMirror-lines"><div style="position: relative">' +
31
+ '<pre class="CodeMirror-cursor">&#160;</pre>' + // Absolutely positioned blinky cursor
32
+ '<div></div>' + // This DIV contains 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
+ measure = code.firstChild, mover = measure.nextSibling,
39
+ gutter = mover.firstChild, gutterText = gutter.firstChild,
40
+ lineSpace = gutter.nextSibling.firstChild,
41
+ cursor = lineSpace.firstChild, lineDiv = cursor.nextSibling;
42
+ if (options.tabindex != null) input.tabindex = options.tabindex;
43
+ if (!options.gutter && !options.lineNumbers) gutter.style.display = "none";
44
+
45
+ // Delayed object wrap timeouts, making sure only one is active. blinker holds an interval.
46
+ var poll = new Delayed(), highlight = new Delayed(), blinker;
47
+
48
+ // mode holds a mode API object. lines an array of Line objects
49
+ // (see Line constructor), work an array of lines that should be
50
+ // parsed, and history the undo history (instance of History
51
+ // constructor).
52
+ var mode, lines = [new Line("")], work, history = new History(), focused;
53
+ loadMode();
54
+ // The selection. These are always maintained to point at valid
55
+ // positions. Inverted is used to remember that the user is
56
+ // selecting bottom-to-top.
57
+ var sel = {from: {line: 0, ch: 0}, to: {line: 0, ch: 0}, inverted: false};
58
+ // Selection-related flags. shiftSelecting obviously tracks
59
+ // whether the user is holding shift. reducedSelection is a hack
60
+ // to get around the fact that we can't create inverted
61
+ // selections. See below.
62
+ var shiftSelecting, reducedSelection, lastDoubleClick;
63
+ // Variables used by startOperation/endOperation to track what
64
+ // happened during the operation.
65
+ var updateInput, changes, textChanged, selectionChanged, leaveInputAlone;
66
+ // Current visible range (may be bigger than the view window).
67
+ var showingFrom = 0, showingTo = 0, lastHeight = 0, curKeyId = null;
68
+ // editing will hold an object describing the things we put in the
69
+ // textarea, to help figure out whether something changed.
70
+ // bracketHighlighted is used to remember that a backet has been
71
+ // marked.
72
+ var editing, bracketHighlighted;
73
+ // Tracks the maximum line length so that the horizontal scrollbar
74
+ // can be kept static when scrolling.
75
+ var maxLine = "";
76
+
77
+ // Initialize the content. Somewhat hacky (delayed prepareInput)
78
+ // to work around browser issues.
79
+ operation(function(){setValue(options.value || ""); updateInput = false;})();
80
+ setTimeout(prepareInput, 20);
81
+
82
+ // Register our event handlers.
83
+ connect(scroller, "mousedown", operation(onMouseDown));
84
+ // Gecko browsers fire contextmenu *after* opening the menu, at
85
+ // which point we can't mess with it anymore. Context menu is
86
+ // handled in onMouseDown for Gecko.
87
+ if (!gecko) connect(scroller, "contextmenu", operation(onContextMenu));
88
+ connect(code, "dblclick", operation(onDblClick));
89
+ connect(scroller, "scroll", function() {updateDisplay([]); if (options.onScroll) options.onScroll(instance);});
90
+ connect(window, "resize", function() {updateDisplay(true);});
91
+ connect(input, "keyup", operation(onKeyUp));
92
+ connect(input, "keydown", operation(onKeyDown));
93
+ connect(input, "keypress", operation(onKeyPress));
94
+ connect(input, "focus", onFocus);
95
+ connect(input, "blur", onBlur);
96
+
97
+ connect(scroller, "dragenter", function(e){e.stop();});
98
+ connect(scroller, "dragover", function(e){e.stop();});
99
+ connect(scroller, "drop", operation(onDrop));
100
+ connect(scroller, "paste", function(){focusInput(); fastPoll();});
101
+ connect(input, "paste", function(){fastPoll();});
102
+ connect(input, "cut", function(){fastPoll();});
103
+
104
+ // IE throws unspecified error in certain cases, when
105
+ // trying to access activeElement before onload
106
+ var hasFocus; try { hasFocus = (targetDocument.activeElement == input); } catch(e) { }
107
+ if (hasFocus) onFocus();
108
+ else onBlur();
109
+
110
+ function isLine(l) {return l >= 0 && l < lines.length;}
111
+ // The instance object that we'll return. Mostly calls out to
112
+ // local functions in the CodeMirror function. Some do some extra
113
+ // range checking and/or clipping. operation is used to wrap the
114
+ // call so that changes it makes are tracked, and the display is
115
+ // updated afterwards.
116
+ var instance = {
117
+ getValue: getValue,
118
+ setValue: operation(setValue),
119
+ getSelection: getSelection,
120
+ replaceSelection: operation(replaceSelection),
121
+ focus: function(){focusInput(); onFocus(); prepareInput(); fastPoll();},
122
+ setOption: function(option, value) {
123
+ options[option] = value;
124
+ if (option == "lineNumbers" || option == "gutter") gutterChanged();
125
+ else if (option == "mode" || option == "indentUnit") loadMode();
126
+ else if (option == "readOnly" && value == "nocursor") input.blur();
127
+ else if (option == "theme") scroller.className = scroller.className.replace(/cm-s-\w+/, "cm-s-" + value);
128
+ },
129
+ getOption: function(option) {return options[option];},
130
+ undo: operation(undo),
131
+ redo: operation(redo),
132
+ indentLine: operation(function(n) {if (isLine(n)) indentLine(n, "smart");}),
133
+ historySize: function() {return {undo: history.done.length, redo: history.undone.length};},
134
+ matchBrackets: operation(function(){matchBrackets(true);}),
135
+ getTokenAt: function(pos) {
136
+ pos = clipPos(pos);
137
+ return lines[pos.line].getTokenAt(mode, getStateBefore(pos.line), pos.ch);
138
+ },
139
+ cursorCoords: function(start){
140
+ if (start == null) start = sel.inverted;
141
+ return pageCoords(start ? sel.from : sel.to);
142
+ },
143
+ charCoords: function(pos){return pageCoords(clipPos(pos));},
144
+ coordsChar: function(coords) {
145
+ var off = eltOffset(lineSpace);
146
+ var line = clipLine(Math.min(lines.length - 1, showingFrom + Math.floor((coords.y - off.top) / lineHeight())));
147
+ return clipPos({line: line, ch: charFromX(clipLine(line), coords.x - off.left)});
148
+ },
149
+ getSearchCursor: function(query, pos, caseFold) {return new SearchCursor(query, pos, caseFold);},
150
+ markText: operation(function(a, b, c){return operation(markText(a, b, c));}),
151
+ setMarker: addGutterMarker,
152
+ clearMarker: removeGutterMarker,
153
+ setLineClass: operation(setLineClass),
154
+ lineInfo: lineInfo,
155
+ addWidget: function(pos, node, scroll) {
156
+ var pos = localCoords(clipPos(pos), true);
157
+ node.style.top = (showingFrom * lineHeight() + pos.yBot + paddingTop()) + "px";
158
+ node.style.left = (pos.x + paddingLeft()) + "px";
159
+ code.appendChild(node);
160
+ if (scroll)
161
+ scrollIntoView(pos.x, pos.yBot, pos.x + node.offsetWidth, pos.yBot + node.offsetHeight);
162
+ },
163
+
164
+ lineCount: function() {return lines.length;},
165
+ getCursor: function(start) {
166
+ if (start == null) start = sel.inverted;
167
+ return copyPos(start ? sel.from : sel.to);
168
+ },
169
+ somethingSelected: function() {return !posEq(sel.from, sel.to);},
170
+ setCursor: operation(function(line, ch) {
171
+ if (ch == null && typeof line.line == "number") setCursor(line.line, line.ch);
172
+ else setCursor(line, ch);
173
+ }),
174
+ setSelection: operation(function(from, to) {setSelection(clipPos(from), clipPos(to || from));}),
175
+ getLine: function(line) {if (isLine(line)) return lines[line].text;},
176
+ setLine: operation(function(line, text) {
177
+ if (isLine(line)) replaceRange(text, {line: line, ch: 0}, {line: line, ch: lines[line].text.length});
178
+ }),
179
+ removeLine: operation(function(line) {
180
+ if (isLine(line)) replaceRange("", {line: line, ch: 0}, clipPos({line: line+1, ch: 0}));
181
+ }),
182
+ replaceRange: operation(replaceRange),
183
+ getRange: function(from, to) {return getRange(clipPos(from), clipPos(to));},
184
+
185
+ operation: function(f){return operation(f)();},
186
+ refresh: function(){updateDisplay(true);},
187
+ getInputField: function(){return input;},
188
+ getWrapperElement: function(){return wrapper;}
189
+ };
190
+
191
+ function setValue(code) {
192
+ history = null;
193
+ var top = {line: 0, ch: 0};
194
+ updateLines(top, {line: lines.length - 1, ch: lines[lines.length-1].text.length},
195
+ splitLines(code), top, top);
196
+ history = new History();
197
+ }
198
+ function getValue(code) {
199
+ var text = [];
200
+ for (var i = 0, l = lines.length; i < l; ++i)
201
+ text.push(lines[i].text);
202
+ return text.join("\n");
203
+ }
204
+
205
+ function onMouseDown(e) {
206
+ var ld = lastDoubleClick; lastDoubleClick = null;
207
+ // First, see if this is a click in the gutter
208
+ for (var n = e.target(); n != wrapper; n = n.parentNode)
209
+ if (n.parentNode == gutterText) {
210
+ if (options.onGutterClick)
211
+ options.onGutterClick(instance, indexOf(gutterText.childNodes, n) + showingFrom);
212
+ return e.stop();
213
+ }
214
+
215
+ if (gecko && e.button() == 3) onContextMenu(e);
216
+ if (e.button() != 1) return;
217
+ // For button 1, if it was clicked inside the editor
218
+ // (posFromMouse returning non-null), we have to adjust the
219
+ // selection.
220
+ var start = posFromMouse(e), last = start, going;
221
+ if (!start) {if (e.target() == scroller) e.stop(); return;}
222
+
223
+ if (!focused) onFocus();
224
+ e.stop();
225
+ if (ld && +new Date - ld < 400) return selectLine(start.line);
226
+
227
+ setCursor(start.line, start.ch, true);
228
+ // And then we have to see if it's a drag event, in which case
229
+ // the dragged-over text must be selected.
230
+ function end() {
231
+ focusInput();
232
+ updateInput = true;
233
+ move(); up();
234
+ }
235
+ function extend(e) {
236
+ var cur = posFromMouse(e, true);
237
+ if (cur && !posEq(cur, last)) {
238
+ if (!focused) onFocus();
239
+ last = cur;
240
+ setSelectionUser(start, cur);
241
+ updateInput = false;
242
+ var visible = visibleLines();
243
+ if (cur.line >= visible.to || cur.line < visible.from)
244
+ going = setTimeout(operation(function(){extend(e);}), 150);
245
+ }
246
+ }
247
+
248
+ var move = connect(targetDocument, "mousemove", operation(function(e) {
249
+ clearTimeout(going);
250
+ e.stop();
251
+ extend(e);
252
+ }), true);
253
+ var up = connect(targetDocument, "mouseup", operation(function(e) {
254
+ clearTimeout(going);
255
+ var cur = posFromMouse(e);
256
+ if (cur) setSelectionUser(start, cur);
257
+ e.stop();
258
+ end();
259
+ }), true);
260
+ }
261
+ function onDblClick(e) {
262
+ var pos = posFromMouse(e);
263
+ if (!pos) return;
264
+ selectWordAt(pos);
265
+ e.stop();
266
+ lastDoubleClick = +new Date;
267
+ }
268
+ function onDrop(e) {
269
+ var pos = posFromMouse(e, true), files = e.e.dataTransfer.files;
270
+ if (!pos || options.readOnly) return;
271
+ if (files && files.length && window.FileReader && window.File) {
272
+ var n = files.length, text = Array(n), read = 0;
273
+ for (var i = 0; i < n; ++i) loadFile(files[i], i);
274
+ function loadFile(file, i) {
275
+ var reader = new FileReader;
276
+ reader.onload = function() {
277
+ text[i] = reader.result;
278
+ if (++read == n) replaceRange(text.join(""), clipPos(pos), clipPos(pos));
279
+ };
280
+ reader.readAsText(file);
281
+ }
282
+ }
283
+ else {
284
+ try {
285
+ var text = e.e.dataTransfer.getData("Text");
286
+ if (text) replaceRange(text, pos, pos);
287
+ }
288
+ catch(e){}
289
+ }
290
+ }
291
+ function onKeyDown(e) {
292
+ if (!focused) onFocus();
293
+
294
+ var code = e.e.keyCode;
295
+ // IE does strange things with escape.
296
+ if (ie && code == 27) { e.e.returnValue = false; }
297
+ // Tries to detect ctrl on non-mac, cmd on mac.
298
+ var mod = (mac ? e.e.metaKey : e.e.ctrlKey) && !e.e.altKey, anyMod = e.e.ctrlKey || e.e.altKey || e.e.metaKey;
299
+ if (code == 16 || e.e.shiftKey) shiftSelecting = shiftSelecting || (sel.inverted ? sel.to : sel.from);
300
+ else shiftSelecting = null;
301
+ // First give onKeyEvent option a chance to handle this.
302
+ if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e.e))) return;
303
+
304
+ if (code == 33 || code == 34) {scrollPage(code == 34); return e.stop();} // page up/down
305
+ if (mod && ((code == 36 || code == 35) || // ctrl-home/end
306
+ mac && (code == 38 || code == 40))) { // cmd-up/down
307
+ scrollEnd(code == 36 || code == 38); return e.stop();
308
+ }
309
+ if (mod && code == 65) {selectAll(); return e.stop();} // ctrl-a
310
+ if (!options.readOnly) {
311
+ if (!anyMod && code == 13) {return;} // enter
312
+ if (!anyMod && code == 9 && handleTab(e.e.shiftKey)) return e.stop(); // tab
313
+ if (mod && code == 90) {undo(); return e.stop();} // ctrl-z
314
+ if (mod && ((e.e.shiftKey && code == 90) || code == 89)) {redo(); return e.stop();} // ctrl-shift-z, ctrl-y
315
+ }
316
+
317
+ // Key id to use in the movementKeys map. We also pass it to
318
+ // fastPoll in order to 'self learn'. We need this because
319
+ // reducedSelection, the hack where we collapse the selection to
320
+ // its start when it is inverted and a movement key is pressed
321
+ // (and later restore it again), shouldn't be used for
322
+ // non-movement keys.
323
+ curKeyId = (mod ? "c" : "") + code;
324
+ if (sel.inverted && movementKeys.hasOwnProperty(curKeyId)) {
325
+ var range = selRange(input);
326
+ if (range) {
327
+ reducedSelection = {anchor: range.start};
328
+ setSelRange(input, range.start, range.start);
329
+ }
330
+ }
331
+ fastPoll(curKeyId);
332
+ }
333
+ function onKeyUp(e) {
334
+ if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e.e))) return;
335
+ if (reducedSelection) {
336
+ reducedSelection = null;
337
+ updateInput = true;
338
+ }
339
+ if (e.e.keyCode == 16) shiftSelecting = null;
340
+ }
341
+ function onKeyPress(e) {
342
+ if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e.e))) return;
343
+ if (options.electricChars && mode.electricChars) {
344
+ var ch = String.fromCharCode(e.e.charCode == null ? e.e.keyCode : e.e.charCode);
345
+ if (mode.electricChars.indexOf(ch) > -1)
346
+ setTimeout(operation(function() {indentLine(sel.to.line, "smart");}), 50);
347
+ }
348
+ var code = e.e.keyCode;
349
+ // Re-stop tab and enter. Necessary on some browsers.
350
+ if (code == 13) {if (!options.readOnly) handleEnter(); e.stop();}
351
+ else if (!e.e.ctrlKey && !e.e.altKey && !e.e.metaKey && code == 9 && options.tabMode != "default") e.stop();
352
+ else fastPoll(curKeyId);
353
+ }
354
+
355
+ function onFocus() {
356
+ if (options.readOnly == "nocursor") return;
357
+ if (!focused && options.onFocus) options.onFocus(instance);
358
+ focused = true;
359
+ slowPoll();
360
+ if (wrapper.className.search(/\bCodeMirror-focused\b/) == -1)
361
+ wrapper.className += " CodeMirror-focused";
362
+ restartBlink();
363
+ }
364
+ function onBlur() {
365
+ if (focused && options.onBlur) options.onBlur(instance);
366
+ clearInterval(blinker);
367
+ shiftSelecting = null;
368
+ focused = false;
369
+ wrapper.className = wrapper.className.replace(" CodeMirror-focused", "");
370
+ }
371
+
372
+ // Replace the range from from to to by the strings in newText.
373
+ // Afterwards, set the selection to selFrom, selTo.
374
+ function updateLines(from, to, newText, selFrom, selTo) {
375
+ if (history) {
376
+ var old = [];
377
+ for (var i = from.line, e = to.line + 1; i < e; ++i) old.push(lines[i].text);
378
+ history.addChange(from.line, newText.length, old);
379
+ while (history.done.length > options.undoDepth) history.done.shift();
380
+ }
381
+ updateLinesNoUndo(from, to, newText, selFrom, selTo);
382
+ if (newText.length < 5)
383
+ highlightLines(from.line, from.line + newText.length)
384
+ }
385
+ function unredoHelper(from, to) {
386
+ var change = from.pop();
387
+ if (change) {
388
+ var replaced = [], end = change.start + change.added;
389
+ for (var i = change.start; i < end; ++i) replaced.push(lines[i].text);
390
+ to.push({start: change.start, added: change.old.length, old: replaced});
391
+ var pos = clipPos({line: change.start + change.old.length - 1,
392
+ ch: editEnd(replaced[replaced.length-1], change.old[change.old.length-1])});
393
+ updateLinesNoUndo({line: change.start, ch: 0}, {line: end - 1, ch: lines[end-1].text.length}, change.old, pos, pos);
394
+ }
395
+ }
396
+ function undo() {unredoHelper(history.done, history.undone);}
397
+ function redo() {unredoHelper(history.undone, history.done);}
398
+
399
+ function updateLinesNoUndo(from, to, newText, selFrom, selTo) {
400
+ var recomputeMaxLength = false, maxLineLength = maxLine.length;
401
+ for (var i = from.line; i <= to.line; ++i) {
402
+ if (lines[i].text.length == maxLineLength) {recomputeMaxLength = true; break;}
403
+ }
404
+
405
+ var nlines = to.line - from.line, firstLine = lines[from.line], lastLine = lines[to.line];
406
+ // First adjust the line structure, taking some care to leave highlighting intact.
407
+ if (firstLine == lastLine) {
408
+ if (newText.length == 1)
409
+ firstLine.replace(from.ch, to.ch, newText[0]);
410
+ else {
411
+ lastLine = firstLine.split(to.ch, newText[newText.length-1]);
412
+ var spliceargs = [from.line + 1, nlines];
413
+ firstLine.replace(from.ch, firstLine.text.length, newText[0]);
414
+ for (var i = 1, e = newText.length - 1; i < e; ++i) spliceargs.push(new Line(newText[i]));
415
+ spliceargs.push(lastLine);
416
+ lines.splice.apply(lines, spliceargs);
417
+ }
418
+ }
419
+ else if (newText.length == 1) {
420
+ firstLine.replace(from.ch, firstLine.text.length, newText[0] + lastLine.text.slice(to.ch));
421
+ lines.splice(from.line + 1, nlines);
422
+ }
423
+ else {
424
+ var spliceargs = [from.line + 1, nlines - 1];
425
+ firstLine.replace(from.ch, firstLine.text.length, newText[0]);
426
+ lastLine.replace(0, to.ch, newText[newText.length-1]);
427
+ for (var i = 1, e = newText.length - 1; i < e; ++i) spliceargs.push(new Line(newText[i]));
428
+ lines.splice.apply(lines, spliceargs);
429
+ }
430
+
431
+
432
+ for (var i = from.line, e = i + newText.length; i < e; ++i) {
433
+ var l = lines[i].text;
434
+ if (l.length > maxLineLength) {
435
+ maxLine = l; maxLineLength = l.length;
436
+ recomputeMaxLength = false;
437
+ }
438
+ }
439
+ if (recomputeMaxLength) {
440
+ maxLineLength = 0; maxLine = "";
441
+ for (var i = 0, e = lines.length; i < e; ++i) {
442
+ var l = lines[i].text;
443
+ if (l.length > maxLineLength) {
444
+ maxLineLength = l.length; maxLine = l;
445
+ }
446
+ }
447
+ }
448
+
449
+ // Add these lines to the work array, so that they will be
450
+ // highlighted. Adjust work lines if lines were added/removed.
451
+ var newWork = [], lendiff = newText.length - nlines - 1;
452
+ for (var i = 0, l = work.length; i < l; ++i) {
453
+ var task = work[i];
454
+ if (task < from.line) newWork.push(task);
455
+ else if (task > to.line) newWork.push(task + lendiff);
456
+ }
457
+ if (newText.length) newWork.push(from.line);
458
+ work = newWork;
459
+ startWorker(100);
460
+ // Remember that these lines changed, for updating the display
461
+ changes.push({from: from.line, to: to.line + 1, diff: lendiff});
462
+ textChanged = {from: from, to: to, text: newText};
463
+
464
+ // Update the selection
465
+ function updateLine(n) {return n <= Math.min(to.line, to.line + lendiff) ? n : n + lendiff;}
466
+ setSelection(selFrom, selTo, updateLine(sel.from.line), updateLine(sel.to.line));
467
+
468
+ // Make sure the scroll-size div has the correct height.
469
+ code.style.height = (lines.length * lineHeight() + 2 * paddingTop()) + "px";
470
+ }
471
+
472
+ function replaceRange(code, from, to) {
473
+ from = clipPos(from);
474
+ if (!to) to = from; else to = clipPos(to);
475
+ code = splitLines(code);
476
+ function adjustPos(pos) {
477
+ if (posLess(pos, from)) return pos;
478
+ if (!posLess(to, pos)) return end;
479
+ var line = pos.line + code.length - (to.line - from.line) - 1;
480
+ var ch = pos.ch;
481
+ if (pos.line == to.line)
482
+ ch += code[code.length-1].length - (to.ch - (to.line == from.line ? from.ch : 0));
483
+ return {line: line, ch: ch};
484
+ }
485
+ var end;
486
+ replaceRange1(code, from, to, function(end1) {
487
+ end = end1;
488
+ return {from: adjustPos(sel.from), to: adjustPos(sel.to)};
489
+ });
490
+ return end;
491
+ }
492
+ function replaceSelection(code, collapse) {
493
+ replaceRange1(splitLines(code), sel.from, sel.to, function(end) {
494
+ if (collapse == "end") return {from: end, to: end};
495
+ else if (collapse == "start") return {from: sel.from, to: sel.from};
496
+ else return {from: sel.from, to: end};
497
+ });
498
+ }
499
+ function replaceRange1(code, from, to, computeSel) {
500
+ var endch = code.length == 1 ? code[0].length + from.ch : code[code.length-1].length;
501
+ var newSel = computeSel({line: from.line + code.length - 1, ch: endch});
502
+ updateLines(from, to, code, newSel.from, newSel.to);
503
+ }
504
+
505
+ function getRange(from, to) {
506
+ var l1 = from.line, l2 = to.line;
507
+ if (l1 == l2) return lines[l1].text.slice(from.ch, to.ch);
508
+ var code = [lines[l1].text.slice(from.ch)];
509
+ for (var i = l1 + 1; i < l2; ++i) code.push(lines[i].text);
510
+ code.push(lines[l2].text.slice(0, to.ch));
511
+ return code.join("\n");
512
+ }
513
+ function getSelection() {
514
+ return getRange(sel.from, sel.to);
515
+ }
516
+
517
+ var pollingFast = false; // Ensures slowPoll doesn't cancel fastPoll
518
+ function slowPoll() {
519
+ if (pollingFast) return;
520
+ poll.set(2000, function() {
521
+ startOperation();
522
+ readInput();
523
+ if (focused) slowPoll();
524
+ endOperation();
525
+ });
526
+ }
527
+ function fastPoll(keyId) {
528
+ var missed = false;
529
+ pollingFast = true;
530
+ function p() {
531
+ startOperation();
532
+ var changed = readInput();
533
+ if (changed == "moved" && keyId) movementKeys[keyId] = true;
534
+ if (!changed && !missed) {missed = true; poll.set(80, p);}
535
+ else {pollingFast = false; slowPoll();}
536
+ endOperation();
537
+ }
538
+ poll.set(20, p);
539
+ }
540
+
541
+ // Inspects the textarea, compares its state (content, selection)
542
+ // to the data in the editing variable, and updates the editor
543
+ // content or cursor if something changed.
544
+ function readInput() {
545
+ if (leaveInputAlone) return;
546
+ var changed = false, text = input.value, sr = selRange(input);
547
+ if (!sr) return false;
548
+ var changed = editing.text != text, rs = reducedSelection;
549
+ var moved = changed || sr.start != editing.start || sr.end != (rs ? editing.start : editing.end);
550
+ if (!moved && !rs) return false;
551
+ if (changed) {
552
+ shiftSelecting = reducedSelection = null;
553
+ if (options.readOnly) {updateInput = true; return "changed";}
554
+ }
555
+
556
+ // Compute selection start and end based on start/end offsets in textarea
557
+ function computeOffset(n, startLine) {
558
+ var pos = 0;
559
+ for (;;) {
560
+ var found = text.indexOf("\n", pos);
561
+ if (found == -1 || (text.charAt(found-1) == "\r" ? found - 1 : found) >= n)
562
+ return {line: startLine, ch: n - pos};
563
+ ++startLine;
564
+ pos = found + 1;
565
+ }
566
+ }
567
+ var from = computeOffset(sr.start, editing.from),
568
+ to = computeOffset(sr.end, editing.from);
569
+ // Here we have to take the reducedSelection hack into account,
570
+ // so that you can, for example, press shift-up at the start of
571
+ // your selection and have the right thing happen.
572
+ if (rs) {
573
+ var head = sr.start == rs.anchor ? to : from;
574
+ var tail = shiftSelecting ? sel.to : sr.start == rs.anchor ? from : to;
575
+ if (sel.inverted = posLess(head, tail)) { from = head; to = tail; }
576
+ else { reducedSelection = null; from = tail; to = head; }
577
+ }
578
+
579
+ // In some cases (cursor on same line as before), we don't have
580
+ // to update the textarea content at all.
581
+ if (from.line == to.line && from.line == sel.from.line && from.line == sel.to.line && !shiftSelecting)
582
+ updateInput = false;
583
+
584
+ // Magic mess to extract precise edited range from the changed
585
+ // string.
586
+ if (changed) {
587
+ var start = 0, end = text.length, len = Math.min(end, editing.text.length);
588
+ var c, line = editing.from, nl = -1;
589
+ while (start < len && (c = text.charAt(start)) == editing.text.charAt(start)) {
590
+ ++start;
591
+ if (c == "\n") {line++; nl = start;}
592
+ }
593
+ var ch = nl > -1 ? start - nl : start, endline = editing.to - 1, edend = editing.text.length;
594
+ for (;;) {
595
+ c = editing.text.charAt(edend);
596
+ if (text.charAt(end) != c) {++end; ++edend; break;}
597
+ if (c == "\n") endline--;
598
+ if (edend <= start || end <= start) break;
599
+ --end; --edend;
600
+ }
601
+ var nl = editing.text.lastIndexOf("\n", edend - 1), endch = nl == -1 ? edend : edend - nl - 1;
602
+ updateLines({line: line, ch: ch}, {line: endline, ch: endch}, splitLines(text.slice(start, end)), from, to);
603
+ if (line != endline || from.line != line) updateInput = true;
604
+ }
605
+ else setSelection(from, to);
606
+
607
+ editing.text = text; editing.start = sr.start; editing.end = sr.end;
608
+ return changed ? "changed" : moved ? "moved" : false;
609
+ }
610
+
611
+ // Set the textarea content and selection range to match the
612
+ // editor state.
613
+ function prepareInput() {
614
+ var text = [];
615
+ var from = Math.max(0, sel.from.line - 1), to = Math.min(lines.length, sel.to.line + 2);
616
+ for (var i = from; i < to; ++i) text.push(lines[i].text);
617
+ text = input.value = text.join(lineSep);
618
+ var startch = sel.from.ch, endch = sel.to.ch;
619
+ for (var i = from; i < sel.from.line; ++i)
620
+ startch += lineSep.length + lines[i].text.length;
621
+ for (var i = from; i < sel.to.line; ++i)
622
+ endch += lineSep.length + lines[i].text.length;
623
+ editing = {text: text, from: from, to: to, start: startch, end: endch};
624
+ setSelRange(input, startch, reducedSelection ? startch : endch);
625
+ }
626
+ function focusInput() {
627
+ if (options.readOnly != "nocursor") input.focus();
628
+ }
629
+
630
+ function scrollCursorIntoView() {
631
+ var cursor = localCoords(sel.inverted ? sel.from : sel.to);
632
+ return scrollIntoView(cursor.x, cursor.y, cursor.x, cursor.yBot);
633
+ }
634
+ function scrollIntoView(x1, y1, x2, y2) {
635
+ var pl = paddingLeft(), pt = paddingTop(), lh = lineHeight();
636
+ y1 += pt; y2 += pt; x1 += pl; x2 += pl;
637
+ var screen = scroller.clientHeight, screentop = scroller.scrollTop, scrolled = false, result = true;
638
+ if (y1 < screentop) {scroller.scrollTop = Math.max(0, y1 - 2*lh); scrolled = true;}
639
+ else if (y2 > screentop + screen) {scroller.scrollTop = y2 + lh - screen; scrolled = true;}
640
+
641
+ var screenw = scroller.clientWidth, screenleft = scroller.scrollLeft;
642
+ if (x1 < screenleft) {
643
+ if (x1 < 50) x1 = 0;
644
+ scroller.scrollLeft = Math.max(0, x1 - 10);
645
+ scrolled = true;
646
+ }
647
+ else if (x2 > screenw + screenleft) {
648
+ scroller.scrollLeft = x2 + 10 - screenw;
649
+ scrolled = true;
650
+ if (x2 > code.clientWidth) result = false;
651
+ }
652
+ if (scrolled && options.onScroll) options.onScroll(instance);
653
+ return result;
654
+ }
655
+
656
+ function visibleLines() {
657
+ var lh = lineHeight(), top = scroller.scrollTop - paddingTop();
658
+ return {from: Math.min(lines.length, Math.max(0, Math.floor(top / lh))),
659
+ to: Math.min(lines.length, Math.ceil((top + scroller.clientHeight) / lh))};
660
+ }
661
+ // Uses a set of changes plus the current scroll position to
662
+ // determine which DOM updates have to be made, and makes the
663
+ // updates.
664
+ function updateDisplay(changes) {
665
+ if (!scroller.clientWidth) {
666
+ showingFrom = showingTo = 0;
667
+ return;
668
+ }
669
+ // First create a range of theoretically intact lines, and punch
670
+ // holes in that using the change info.
671
+ var intact = changes === true ? [] : [{from: showingFrom, to: showingTo, domStart: 0}];
672
+ for (var i = 0, l = changes.length || 0; i < l; ++i) {
673
+ var change = changes[i], intact2 = [], diff = change.diff || 0;
674
+ for (var j = 0, l2 = intact.length; j < l2; ++j) {
675
+ var range = intact[j];
676
+ if (change.to <= range.from)
677
+ intact2.push({from: range.from + diff, to: range.to + diff, domStart: range.domStart});
678
+ else if (range.to <= change.from)
679
+ intact2.push(range);
680
+ else {
681
+ if (change.from > range.from)
682
+ intact2.push({from: range.from, to: change.from, domStart: range.domStart})
683
+ if (change.to < range.to)
684
+ intact2.push({from: change.to + diff, to: range.to + diff,
685
+ domStart: range.domStart + (change.to - range.from)});
686
+ }
687
+ }
688
+ intact = intact2;
689
+ }
690
+
691
+ // Then, determine which lines we'd want to see, and which
692
+ // updates have to be made to get there.
693
+ var visible = visibleLines();
694
+ var from = Math.min(showingFrom, Math.max(visible.from - 3, 0)),
695
+ to = Math.min(lines.length, Math.max(showingTo, visible.to + 3)),
696
+ updates = [], domPos = 0, domEnd = showingTo - showingFrom, pos = from, changedLines = 0;
697
+
698
+ for (var i = 0, l = intact.length; i < l; ++i) {
699
+ var range = intact[i];
700
+ if (range.to <= from) continue;
701
+ if (range.from >= to) break;
702
+ if (range.domStart > domPos || range.from > pos) {
703
+ updates.push({from: pos, to: range.from, domSize: range.domStart - domPos, domStart: domPos});
704
+ changedLines += range.from - pos;
705
+ }
706
+ pos = range.to;
707
+ domPos = range.domStart + (range.to - range.from);
708
+ }
709
+ if (domPos != domEnd || pos != to) {
710
+ changedLines += Math.abs(to - pos);
711
+ updates.push({from: pos, to: to, domSize: domEnd - domPos, domStart: domPos});
712
+ }
713
+
714
+ if (!updates.length) return;
715
+ lineDiv.style.display = "none";
716
+ // If more than 30% of the screen needs update, just do a full
717
+ // redraw (which is quicker than patching)
718
+ if (changedLines > (visible.to - visible.from) * .3)
719
+ refreshDisplay(from = Math.max(visible.from - 10, 0), to = Math.min(visible.to + 7, lines.length));
720
+ // Otherwise, only update the stuff that needs updating.
721
+ else
722
+ patchDisplay(updates);
723
+ lineDiv.style.display = "";
724
+
725
+ // Position the mover div to align with the lines it's supposed
726
+ // to be showing (which will cover the visible display)
727
+ var different = from != showingFrom || to != showingTo || lastHeight != scroller.clientHeight;
728
+ showingFrom = from; showingTo = to;
729
+ mover.style.top = (from * lineHeight()) + "px";
730
+ if (different) {
731
+ lastHeight = scroller.clientHeight;
732
+ code.style.height = (lines.length * lineHeight() + 2 * paddingTop()) + "px";
733
+ updateGutter();
734
+ }
735
+
736
+ var textWidth = stringWidth(maxLine);
737
+ lineSpace.style.width = textWidth > scroller.clientWidth ? textWidth + "px" : "";
738
+
739
+ // Since this is all rather error prone, it is honoured with the
740
+ // only assertion in the whole file.
741
+ if (lineDiv.childNodes.length != showingTo - showingFrom)
742
+ throw new Error("BAD PATCH! " + JSON.stringify(updates) + " size=" + (showingTo - showingFrom) +
743
+ " nodes=" + lineDiv.childNodes.length);
744
+ updateCursor();
745
+ }
746
+
747
+ function refreshDisplay(from, to) {
748
+ var html = [], start = {line: from, ch: 0}, inSel = posLess(sel.from, start) && !posLess(sel.to, start);
749
+ for (var i = from; i < to; ++i) {
750
+ var ch1 = null, ch2 = null;
751
+ if (inSel) {
752
+ ch1 = 0;
753
+ if (sel.to.line == i) {inSel = false; ch2 = sel.to.ch;}
754
+ }
755
+ else if (sel.from.line == i) {
756
+ if (sel.to.line == i) {ch1 = sel.from.ch; ch2 = sel.to.ch;}
757
+ else {inSel = true; ch1 = sel.from.ch;}
758
+ }
759
+ html.push(lines[i].getHTML(ch1, ch2, true));
760
+ }
761
+ lineDiv.innerHTML = html.join("");
762
+ }
763
+ function patchDisplay(updates) {
764
+ // Slightly different algorithm for IE (badInnerHTML), since
765
+ // there .innerHTML on PRE nodes is dumb, and discards
766
+ // whitespace.
767
+ var sfrom = sel.from.line, sto = sel.to.line, off = 0,
768
+ scratch = badInnerHTML && targetDocument.createElement("div");
769
+ for (var i = 0, e = updates.length; i < e; ++i) {
770
+ var rec = updates[i];
771
+ var extra = (rec.to - rec.from) - rec.domSize;
772
+ var nodeAfter = lineDiv.childNodes[rec.domStart + rec.domSize + off] || null;
773
+ if (badInnerHTML)
774
+ for (var j = Math.max(-extra, rec.domSize); j > 0; --j)
775
+ lineDiv.removeChild(nodeAfter ? nodeAfter.previousSibling : lineDiv.lastChild);
776
+ else if (extra) {
777
+ for (var j = Math.max(0, extra); j > 0; --j)
778
+ lineDiv.insertBefore(targetDocument.createElement("pre"), nodeAfter);
779
+ for (var j = Math.max(0, -extra); j > 0; --j)
780
+ lineDiv.removeChild(nodeAfter ? nodeAfter.previousSibling : lineDiv.lastChild);
781
+ }
782
+ var node = lineDiv.childNodes[rec.domStart + off], inSel = sfrom < rec.from && sto >= rec.from;
783
+ for (var j = rec.from; j < rec.to; ++j) {
784
+ var ch1 = null, ch2 = null;
785
+ if (inSel) {
786
+ ch1 = 0;
787
+ if (sto == j) {inSel = false; ch2 = sel.to.ch;}
788
+ }
789
+ else if (sfrom == j) {
790
+ if (sto == j) {ch1 = sel.from.ch; ch2 = sel.to.ch;}
791
+ else {inSel = true; ch1 = sel.from.ch;}
792
+ }
793
+ if (badInnerHTML) {
794
+ scratch.innerHTML = lines[j].getHTML(ch1, ch2, true);
795
+ lineDiv.insertBefore(scratch.firstChild, nodeAfter);
796
+ }
797
+ else {
798
+ node.innerHTML = lines[j].getHTML(ch1, ch2, false);
799
+ node.className = lines[j].className || "";
800
+ node = node.nextSibling;
801
+ }
802
+ }
803
+ off += extra;
804
+ }
805
+ }
806
+
807
+ function updateGutter() {
808
+ if (!options.gutter && !options.lineNumbers) return;
809
+ var hText = mover.offsetHeight, hEditor = scroller.clientHeight;
810
+ gutter.style.height = (hText - hEditor < 2 ? hEditor : hText) + "px";
811
+ var html = [];
812
+ for (var i = showingFrom; i < Math.max(showingTo, showingFrom + 1); ++i) {
813
+ var marker = lines[i].gutterMarker;
814
+ var text = options.lineNumbers ? i + options.firstLineNumber : null;
815
+ if (marker && marker.text)
816
+ text = marker.text.replace("%N%", text != null ? text : "");
817
+ else if (text == null)
818
+ text = "\u00a0";
819
+ html.push((marker && marker.style ? '<pre class="' + marker.style + '">' : "<pre>"), text, "</pre>");
820
+ }
821
+ gutter.style.display = "none";
822
+ gutterText.innerHTML = html.join("");
823
+ var minwidth = String(lines.length).length, firstNode = gutterText.firstChild, val = eltText(firstNode), pad = "";
824
+ while (val.length + pad.length < minwidth) pad += "\u00a0";
825
+ if (pad) firstNode.insertBefore(targetDocument.createTextNode(pad), firstNode.firstChild);
826
+ gutter.style.display = "";
827
+ lineSpace.style.marginLeft = gutter.offsetWidth + "px";
828
+ }
829
+ function updateCursor() {
830
+ var head = sel.inverted ? sel.from : sel.to, lh = lineHeight();
831
+ var x = charX(head.line, head.ch) + "px", y = (head.line - showingFrom) * lh + "px";
832
+ inputDiv.style.top = (head.line * lh - scroller.scrollTop) + "px";
833
+ if (posEq(sel.from, sel.to)) {
834
+ cursor.style.top = y; cursor.style.left = x;
835
+ cursor.style.display = "";
836
+ }
837
+ else cursor.style.display = "none";
838
+ }
839
+
840
+ function setSelectionUser(from, to) {
841
+ var sh = shiftSelecting && clipPos(shiftSelecting);
842
+ if (sh) {
843
+ if (posLess(sh, from)) from = sh;
844
+ else if (posLess(to, sh)) to = sh;
845
+ }
846
+ setSelection(from, to);
847
+ }
848
+ // Update the selection. Last two args are only used by
849
+ // updateLines, since they have to be expressed in the line
850
+ // numbers before the update.
851
+ function setSelection(from, to, oldFrom, oldTo) {
852
+ if (posEq(sel.from, from) && posEq(sel.to, to)) return;
853
+ if (posLess(to, from)) {var tmp = to; to = from; from = tmp;}
854
+
855
+ if (posEq(from, to)) sel.inverted = false;
856
+ else if (posEq(from, sel.to)) sel.inverted = false;
857
+ else if (posEq(to, sel.from)) sel.inverted = true;
858
+
859
+ // Some ugly logic used to only mark the lines that actually did
860
+ // see a change in selection as changed, rather than the whole
861
+ // selected range.
862
+ if (oldFrom == null) {oldFrom = sel.from.line; oldTo = sel.to.line;}
863
+ if (posEq(from, to)) {
864
+ if (!posEq(sel.from, sel.to))
865
+ changes.push({from: oldFrom, to: oldTo + 1});
866
+ }
867
+ else if (posEq(sel.from, sel.to)) {
868
+ changes.push({from: from.line, to: to.line + 1});
869
+ }
870
+ else {
871
+ if (!posEq(from, sel.from)) {
872
+ if (from.line < oldFrom)
873
+ changes.push({from: from.line, to: Math.min(to.line, oldFrom) + 1});
874
+ else
875
+ changes.push({from: oldFrom, to: Math.min(oldTo, from.line) + 1});
876
+ }
877
+ if (!posEq(to, sel.to)) {
878
+ if (to.line < oldTo)
879
+ changes.push({from: Math.max(oldFrom, from.line), to: oldTo + 1});
880
+ else
881
+ changes.push({from: Math.max(from.line, oldTo), to: to.line + 1});
882
+ }
883
+ }
884
+ sel.from = from; sel.to = to;
885
+ selectionChanged = true;
886
+ }
887
+ function setCursor(line, ch, user) {
888
+ var pos = clipPos({line: line, ch: ch || 0});
889
+ (user ? setSelectionUser : setSelection)(pos, pos);
890
+ }
891
+
892
+ function clipLine(n) {return Math.max(0, Math.min(n, lines.length-1));}
893
+ function clipPos(pos) {
894
+ if (pos.line < 0) return {line: 0, ch: 0};
895
+ if (pos.line >= lines.length) return {line: lines.length-1, ch: lines[lines.length-1].text.length};
896
+ var ch = pos.ch, linelen = lines[pos.line].text.length;
897
+ if (ch == null || ch > linelen) return {line: pos.line, ch: linelen};
898
+ else if (ch < 0) return {line: pos.line, ch: 0};
899
+ else return pos;
900
+ }
901
+
902
+ function scrollPage(down) {
903
+ var linesPerPage = Math.floor(scroller.clientHeight / lineHeight()), head = sel.inverted ? sel.from : sel.to;
904
+ setCursor(head.line + (Math.max(linesPerPage - 1, 1) * (down ? 1 : -1)), head.ch, true);
905
+ }
906
+ function scrollEnd(top) {
907
+ var pos = top ? {line: 0, ch: 0} : {line: lines.length - 1, ch: lines[lines.length-1].text.length};
908
+ setSelectionUser(pos, pos);
909
+ }
910
+ function selectAll() {
911
+ var endLine = lines.length - 1;
912
+ setSelection({line: 0, ch: 0}, {line: endLine, ch: lines[endLine].text.length});
913
+ }
914
+ function selectWordAt(pos) {
915
+ var line = lines[pos.line].text;
916
+ var start = pos.ch, end = pos.ch;
917
+ while (start > 0 && /\w/.test(line.charAt(start - 1))) --start;
918
+ while (end < line.length && /\w/.test(line.charAt(end))) ++end;
919
+ setSelectionUser({line: pos.line, ch: start}, {line: pos.line, ch: end});
920
+ }
921
+ function selectLine(line) {
922
+ setSelectionUser({line: line, ch: 0}, {line: line, ch: lines[line].text.length});
923
+ }
924
+ function handleEnter() {
925
+ replaceSelection("\n", "end");
926
+ if (options.enterMode != "flat")
927
+ indentLine(sel.from.line, options.enterMode == "keep" ? "prev" : "smart");
928
+ }
929
+ function handleTab(shift) {
930
+ shiftSelecting = null;
931
+ switch (options.tabMode) {
932
+ case "default":
933
+ return false;
934
+ case "indent":
935
+ for (var i = sel.from.line, e = sel.to.line; i <= e; ++i) indentLine(i, "smart");
936
+ break;
937
+ case "classic":
938
+ if (posEq(sel.from, sel.to)) {
939
+ if (shift) indentLine(sel.from.line, "smart");
940
+ else replaceSelection("\t", "end");
941
+ break;
942
+ }
943
+ case "shift":
944
+ for (var i = sel.from.line, e = sel.to.line; i <= e; ++i) indentLine(i, shift ? "subtract" : "add");
945
+ break;
946
+ }
947
+ return true;
948
+ }
949
+
950
+ function indentLine(n, how) {
951
+ if (how == "smart") {
952
+ if (!mode.indent) how = "prev";
953
+ else var state = getStateBefore(n);
954
+ }
955
+
956
+ var line = lines[n], curSpace = line.indentation(), curSpaceString = line.text.match(/^\s*/)[0], indentation;
957
+ if (how == "prev") {
958
+ if (n) indentation = lines[n-1].indentation();
959
+ else indentation = 0;
960
+ }
961
+ else if (how == "smart") indentation = mode.indent(state, line.text.slice(curSpaceString.length));
962
+ else if (how == "add") indentation = curSpace + options.indentUnit;
963
+ else if (how == "subtract") indentation = curSpace - options.indentUnit;
964
+ indentation = Math.max(0, indentation);
965
+ var diff = indentation - curSpace;
966
+
967
+ if (!diff) {
968
+ if (sel.from.line != n && sel.to.line != n) return;
969
+ var indentString = curSpaceString;
970
+ }
971
+ else {
972
+ var indentString = "", pos = 0;
973
+ if (options.indentWithTabs)
974
+ for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
975
+ while (pos < indentation) {++pos; indentString += " ";}
976
+ }
977
+
978
+ replaceRange(indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length});
979
+ }
980
+
981
+ function loadMode() {
982
+ mode = CodeMirror.getMode(options, options.mode);
983
+ for (var i = 0, l = lines.length; i < l; ++i)
984
+ lines[i].stateAfter = null;
985
+ work = [0];
986
+ startWorker();
987
+ }
988
+ function gutterChanged() {
989
+ var visible = options.gutter || options.lineNumbers;
990
+ gutter.style.display = visible ? "" : "none";
991
+ if (visible) updateGutter();
992
+ else lineDiv.parentNode.style.marginLeft = 0;
993
+ }
994
+
995
+ function markText(from, to, className) {
996
+ from = clipPos(from); to = clipPos(to);
997
+ var accum = [];
998
+ function add(line, from, to, className) {
999
+ var line = lines[line], mark = line.addMark(from, to, className);
1000
+ mark.line = line;
1001
+ accum.push(mark);
1002
+ }
1003
+ if (from.line == to.line) add(from.line, from.ch, to.ch, className);
1004
+ else {
1005
+ add(from.line, from.ch, null, className);
1006
+ for (var i = from.line + 1, e = to.line; i < e; ++i)
1007
+ add(i, 0, null, className);
1008
+ add(to.line, 0, to.ch, className);
1009
+ }
1010
+ changes.push({from: from.line, to: to.line + 1});
1011
+ return function() {
1012
+ var start, end;
1013
+ for (var i = 0; i < accum.length; ++i) {
1014
+ var mark = accum[i], found = indexOf(lines, mark.line);
1015
+ mark.line.removeMark(mark);
1016
+ if (found > -1) {
1017
+ if (start == null) start = found;
1018
+ end = found;
1019
+ }
1020
+ }
1021
+ if (start != null) changes.push({from: start, to: end + 1});
1022
+ };
1023
+ }
1024
+
1025
+ function addGutterMarker(line, text, className) {
1026
+ if (typeof line == "number") line = lines[clipLine(line)];
1027
+ line.gutterMarker = {text: text, style: className};
1028
+ updateGutter();
1029
+ return line;
1030
+ }
1031
+ function removeGutterMarker(line) {
1032
+ if (typeof line == "number") line = lines[clipLine(line)];
1033
+ line.gutterMarker = null;
1034
+ updateGutter();
1035
+ }
1036
+ function setLineClass(line, className) {
1037
+ if (typeof line == "number") {
1038
+ var no = line;
1039
+ line = lines[clipLine(line)];
1040
+ }
1041
+ else {
1042
+ var no = indexOf(lines, line);
1043
+ if (no == -1) return null;
1044
+ }
1045
+ if (line.className != className) {
1046
+ line.className = className;
1047
+ changes.push({from: no, to: no + 1});
1048
+ }
1049
+ return line;
1050
+ }
1051
+
1052
+ function lineInfo(line) {
1053
+ if (typeof line == "number") {
1054
+ var n = line;
1055
+ line = lines[line];
1056
+ if (!line) return null;
1057
+ }
1058
+ else {
1059
+ var n = indexOf(lines, line);
1060
+ if (n == -1) return null;
1061
+ }
1062
+ var marker = line.gutterMarker;
1063
+ return {line: n, text: line.text, markerText: marker && marker.text, markerClass: marker && marker.style};
1064
+ }
1065
+
1066
+ function stringWidth(str) {
1067
+ measure.innerHTML = "<pre><span>x</span></pre>";
1068
+ measure.firstChild.firstChild.firstChild.nodeValue = str;
1069
+ return measure.firstChild.firstChild.offsetWidth || 10;
1070
+ }
1071
+ // These are used to go from pixel positions to character
1072
+ // positions, taking varying character widths into account.
1073
+ function charX(line, pos) {
1074
+ if (pos == 0) return 0;
1075
+ measure.innerHTML = "<pre><span>" + lines[line].getHTML(null, null, false, pos) + "</span></pre>";
1076
+ return measure.firstChild.firstChild.offsetWidth;
1077
+ }
1078
+ function charFromX(line, x) {
1079
+ if (x <= 0) return 0;
1080
+ var lineObj = lines[line], text = lineObj.text;
1081
+ function getX(len) {
1082
+ measure.innerHTML = "<pre><span>" + lineObj.getHTML(null, null, false, len) + "</span></pre>";
1083
+ return measure.firstChild.firstChild.offsetWidth;
1084
+ }
1085
+ var from = 0, fromX = 0, to = text.length, toX;
1086
+ // Guess a suitable upper bound for our search.
1087
+ var estimated = Math.min(to, Math.ceil(x / stringWidth("x")));
1088
+ for (;;) {
1089
+ var estX = getX(estimated);
1090
+ if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));
1091
+ else {toX = estX; to = estimated; break;}
1092
+ }
1093
+ if (x > toX) return to;
1094
+ // Try to guess a suitable lower bound as well.
1095
+ estimated = Math.floor(to * 0.8); estX = getX(estimated);
1096
+ if (estX < x) {from = estimated; fromX = estX;}
1097
+ // Do a binary search between these bounds.
1098
+ for (;;) {
1099
+ if (to - from <= 1) return (toX - x > x - fromX) ? from : to;
1100
+ var middle = Math.ceil((from + to) / 2), middleX = getX(middle);
1101
+ if (middleX > x) {to = middle; toX = middleX;}
1102
+ else {from = middle; fromX = middleX;}
1103
+ }
1104
+ }
1105
+
1106
+ function localCoords(pos, inLineWrap) {
1107
+ var lh = lineHeight(), line = pos.line - (inLineWrap ? showingFrom : 0);
1108
+ return {x: charX(pos.line, pos.ch), y: line * lh, yBot: (line + 1) * lh};
1109
+ }
1110
+ function pageCoords(pos) {
1111
+ var local = localCoords(pos, true), off = eltOffset(lineSpace);
1112
+ return {x: off.left + local.x, y: off.top + local.y, yBot: off.top + local.yBot};
1113
+ }
1114
+
1115
+ function lineHeight() {
1116
+ var nlines = lineDiv.childNodes.length;
1117
+ if (nlines) return (lineDiv.offsetHeight / nlines) || 1;
1118
+ measure.innerHTML = "<pre>x</pre>";
1119
+ return measure.firstChild.offsetHeight || 1;
1120
+ }
1121
+ function paddingTop() {return lineSpace.offsetTop;}
1122
+ function paddingLeft() {return lineSpace.offsetLeft;}
1123
+
1124
+ function posFromMouse(e, liberal) {
1125
+ var offW = eltOffset(scroller, true), x = e.e.clientX, y = e.e.clientY;
1126
+ // This is a mess of a heuristic to try and determine whether a
1127
+ // scroll-bar was clicked or not, and to return null if one was
1128
+ // (and !liberal).
1129
+ if (!liberal && (x - offW.left > scroller.clientWidth || y - offW.top > scroller.clientHeight))
1130
+ return null;
1131
+ var offL = eltOffset(lineSpace, true);
1132
+ var line = showingFrom + Math.floor((y - offL.top) / lineHeight());
1133
+ return clipPos({line: line, ch: charFromX(clipLine(line), x - offL.left)});
1134
+ }
1135
+ function onContextMenu(e) {
1136
+ var pos = posFromMouse(e);
1137
+ if (!pos || window.opera) return; // Opera is difficult.
1138
+ if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
1139
+ setCursor(pos.line, pos.ch);
1140
+
1141
+ var oldCSS = input.style.cssText;
1142
+ input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.pageY() - 1) +
1143
+ "px; left: " + (e.pageX() - 1) + "px; z-index: 1000; background: white; " +
1144
+ "border-width: 0; outline: none; overflow: hidden; opacity: .05;";
1145
+ var val = input.value = getSelection();
1146
+ focusInput();
1147
+ setSelRange(input, 0, input.value.length);
1148
+ leaveInputAlone = true;
1149
+ function rehide() {
1150
+ if (input.value != val) operation(replaceSelection)(input.value, "end");
1151
+ input.style.cssText = oldCSS;
1152
+ leaveInputAlone = false;
1153
+ prepareInput();
1154
+ slowPoll();
1155
+ }
1156
+
1157
+ if (gecko) {
1158
+ e.stop()
1159
+ var mouseup = connect(window, "mouseup", function() {
1160
+ mouseup();
1161
+ setTimeout(rehide, 20);
1162
+ }, true);
1163
+ }
1164
+ else {
1165
+ setTimeout(rehide, 50);
1166
+ }
1167
+ }
1168
+
1169
+ // Cursor-blinking
1170
+ function restartBlink() {
1171
+ clearInterval(blinker);
1172
+ var on = true;
1173
+ cursor.style.visibility = "";
1174
+ blinker = setInterval(function() {
1175
+ cursor.style.visibility = (on = !on) ? "" : "hidden";
1176
+ }, 650);
1177
+ }
1178
+
1179
+ var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
1180
+ function matchBrackets(autoclear) {
1181
+ var head = sel.inverted ? sel.from : sel.to, line = lines[head.line], pos = head.ch - 1;
1182
+ var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
1183
+ if (!match) return;
1184
+ var ch = match.charAt(0), forward = match.charAt(1) == ">", d = forward ? 1 : -1, st = line.styles;
1185
+ for (var off = pos + 1, i = 0, e = st.length; i < e; i+=2)
1186
+ if ((off -= st[i].length) <= 0) {var style = st[i+1]; break;}
1187
+
1188
+ var stack = [line.text.charAt(pos)], re = /[(){}[\]]/;
1189
+ function scan(line, from, to) {
1190
+ if (!line.text) return;
1191
+ var st = line.styles, pos = forward ? 0 : line.text.length - 1, cur;
1192
+ for (var i = forward ? 0 : st.length - 2, e = forward ? st.length : -2; i != e; i += 2*d) {
1193
+ var text = st[i];
1194
+ if (st[i+1] != null && st[i+1] != style) {pos += d * text.length; continue;}
1195
+ for (var j = forward ? 0 : text.length - 1, te = forward ? text.length : -1; j != te; j += d, pos+=d) {
1196
+ if (pos >= from && pos < to && re.test(cur = text.charAt(j))) {
1197
+ var match = matching[cur];
1198
+ if (match.charAt(1) == ">" == forward) stack.push(cur);
1199
+ else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false};
1200
+ else if (!stack.length) return {pos: pos, match: true};
1201
+ }
1202
+ }
1203
+ }
1204
+ }
1205
+ for (var i = head.line, e = forward ? Math.min(i + 50, lines.length) : Math.max(-1, i - 50); i != e; i+=d) {
1206
+ var line = lines[i], first = i == head.line;
1207
+ var found = scan(line, first && forward ? pos + 1 : 0, first && !forward ? pos : line.text.length);
1208
+ if (found) {
1209
+ var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
1210
+ var one = markText({line: head.line, ch: pos}, {line: head.line, ch: pos+1}, style),
1211
+ two = markText({line: i, ch: found.pos}, {line: i, ch: found.pos + 1}, style);
1212
+ var clear = operation(function(){one(); two();});
1213
+ if (autoclear) setTimeout(clear, 800);
1214
+ else bracketHighlighted = clear;
1215
+ break;
1216
+ }
1217
+ }
1218
+ }
1219
+
1220
+ // Finds the line to start with when starting a parse. Tries to
1221
+ // find a line with a stateAfter, so that it can start with a
1222
+ // valid state. If that fails, it returns the line with the
1223
+ // smallest indentation, which tends to need the least context to
1224
+ // parse correctly.
1225
+ function findStartLine(n) {
1226
+ var minindent, minline;
1227
+ for (var search = n, lim = n - 40; search > lim; --search) {
1228
+ if (search == 0) return 0;
1229
+ var line = lines[search-1];
1230
+ if (line.stateAfter) return search;
1231
+ var indented = line.indentation();
1232
+ if (minline == null || minindent > indented) {
1233
+ minline = search;
1234
+ minindent = indented;
1235
+ }
1236
+ }
1237
+ return minline;
1238
+ }
1239
+ function getStateBefore(n) {
1240
+ var start = findStartLine(n), state = start && lines[start-1].stateAfter;
1241
+ if (!state) state = startState(mode);
1242
+ else state = copyState(mode, state);
1243
+ for (var i = start; i < n; ++i) {
1244
+ var line = lines[i];
1245
+ line.highlight(mode, state);
1246
+ line.stateAfter = copyState(mode, state);
1247
+ }
1248
+ if (!lines[n].stateAfter) work.push(n);
1249
+ return state;
1250
+ }
1251
+ function highlightLines(start, end) {
1252
+ var state = getStateBefore(start);
1253
+ for (var i = start; i < end; ++i) {
1254
+ var line = lines[i];
1255
+ line.highlight(mode, state);
1256
+ line.stateAfter = copyState(mode, state);
1257
+ }
1258
+ }
1259
+ function highlightWorker() {
1260
+ var end = +new Date + options.workTime;
1261
+ var foundWork = work.length;
1262
+ while (work.length) {
1263
+ if (!lines[showingFrom].stateAfter) var task = showingFrom;
1264
+ else var task = work.pop();
1265
+ if (task >= lines.length) continue;
1266
+ var start = findStartLine(task), state = start && lines[start-1].stateAfter;
1267
+ if (state) state = copyState(mode, state);
1268
+ else state = startState(mode);
1269
+
1270
+ var unchanged = 0;
1271
+ for (var i = start, l = lines.length; i < l; ++i) {
1272
+ var line = lines[i], hadState = line.stateAfter;
1273
+ if (+new Date > end) {
1274
+ work.push(i);
1275
+ startWorker(options.workDelay);
1276
+ changes.push({from: task, to: i});
1277
+ return;
1278
+ }
1279
+ var changed = line.highlight(mode, state);
1280
+ line.stateAfter = copyState(mode, state);
1281
+ if (changed || !hadState) unchanged = 0;
1282
+ else if (++unchanged > 3) break;
1283
+ }
1284
+ changes.push({from: task, to: i});
1285
+ }
1286
+ if (foundWork && options.onHighlightComplete)
1287
+ options.onHighlightComplete(instance);
1288
+ }
1289
+ function startWorker(time) {
1290
+ if (!work.length) return;
1291
+ highlight.set(time, operation(highlightWorker));
1292
+ }
1293
+
1294
+ // Operations are used to wrap changes in such a way that each
1295
+ // change won't have to update the cursor and display (which would
1296
+ // be awkward, slow, and error-prone), but instead updates are
1297
+ // batched and then all combined and executed at once.
1298
+ function startOperation() {
1299
+ updateInput = null; changes = []; textChanged = selectionChanged = false;
1300
+ }
1301
+ function endOperation() {
1302
+ var reScroll = false;
1303
+ if (selectionChanged) reScroll = !scrollCursorIntoView();
1304
+ if (changes.length) updateDisplay(changes);
1305
+ else if (selectionChanged) updateCursor();
1306
+ if (reScroll) scrollCursorIntoView();
1307
+ if (selectionChanged) restartBlink();
1308
+
1309
+ // updateInput can be set to a boolean value to force/prevent an
1310
+ // update.
1311
+ if (!leaveInputAlone && (updateInput === true || (updateInput !== false && selectionChanged)))
1312
+ prepareInput();
1313
+
1314
+ if (selectionChanged && options.matchBrackets)
1315
+ setTimeout(operation(function() {
1316
+ if (bracketHighlighted) {bracketHighlighted(); bracketHighlighted = null;}
1317
+ matchBrackets(false);
1318
+ }), 20);
1319
+ var tc = textChanged; // textChanged can be reset by cursoractivity callback
1320
+ if (selectionChanged && options.onCursorActivity)
1321
+ options.onCursorActivity(instance);
1322
+ if (tc && options.onChange && instance)
1323
+ options.onChange(instance, tc);
1324
+ }
1325
+ var nestedOperation = 0;
1326
+ function operation(f) {
1327
+ return function() {
1328
+ if (!nestedOperation++) startOperation();
1329
+ try {var result = f.apply(this, arguments);}
1330
+ finally {if (!--nestedOperation) endOperation();}
1331
+ return result;
1332
+ };
1333
+ }
1334
+
1335
+ function SearchCursor(query, pos, caseFold) {
1336
+ this.atOccurrence = false;
1337
+ if (caseFold == null) caseFold = typeof query == "string" && query == query.toLowerCase();
1338
+
1339
+ if (pos && typeof pos == "object") pos = clipPos(pos);
1340
+ else pos = {line: 0, ch: 0};
1341
+ this.pos = {from: pos, to: pos};
1342
+
1343
+ // The matches method is filled in based on the type of query.
1344
+ // It takes a position and a direction, and returns an object
1345
+ // describing the next occurrence of the query, or null if no
1346
+ // more matches were found.
1347
+ if (typeof query != "string") // Regexp match
1348
+ this.matches = function(reverse, pos) {
1349
+ if (reverse) {
1350
+ var line = lines[pos.line].text.slice(0, pos.ch), match = line.match(query), start = 0;
1351
+ while (match) {
1352
+ var ind = line.indexOf(match[0]);
1353
+ start += ind;
1354
+ line = line.slice(ind + 1);
1355
+ var newmatch = line.match(query);
1356
+ if (newmatch) match = newmatch;
1357
+ else break;
1358
+ start++;
1359
+ }
1360
+ }
1361
+ else {
1362
+ var line = lines[pos.line].text.slice(pos.ch), match = line.match(query),
1363
+ start = match && pos.ch + line.indexOf(match[0]);
1364
+ }
1365
+ if (match)
1366
+ return {from: {line: pos.line, ch: start},
1367
+ to: {line: pos.line, ch: start + match[0].length},
1368
+ match: match};
1369
+ };
1370
+ else { // String query
1371
+ if (caseFold) query = query.toLowerCase();
1372
+ var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
1373
+ var target = query.split("\n");
1374
+ // Different methods for single-line and multi-line queries
1375
+ if (target.length == 1)
1376
+ this.matches = function(reverse, pos) {
1377
+ var line = fold(lines[pos.line].text), len = query.length, match;
1378
+ if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1)
1379
+ : (match = line.indexOf(query, pos.ch)) != -1)
1380
+ return {from: {line: pos.line, ch: match},
1381
+ to: {line: pos.line, ch: match + len}};
1382
+ };
1383
+ else
1384
+ this.matches = function(reverse, pos) {
1385
+ var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(lines[ln].text);
1386
+ var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match));
1387
+ if (reverse ? offsetA >= pos.ch || offsetA != match.length
1388
+ : offsetA <= pos.ch || offsetA != line.length - match.length)
1389
+ return;
1390
+ for (;;) {
1391
+ if (reverse ? !ln : ln == lines.length - 1) return;
1392
+ line = fold(lines[ln += reverse ? -1 : 1].text);
1393
+ match = target[reverse ? --idx : ++idx];
1394
+ if (idx > 0 && idx < target.length - 1) {
1395
+ if (line != match) return;
1396
+ else continue;
1397
+ }
1398
+ var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length);
1399
+ if (reverse ? offsetB != line.length - match.length : offsetB != match.length)
1400
+ return;
1401
+ var start = {line: pos.line, ch: offsetA}, end = {line: ln, ch: offsetB};
1402
+ return {from: reverse ? end : start, to: reverse ? start : end};
1403
+ }
1404
+ };
1405
+ }
1406
+ }
1407
+
1408
+ SearchCursor.prototype = {
1409
+ findNext: function() {return this.find(false);},
1410
+ findPrevious: function() {return this.find(true);},
1411
+
1412
+ find: function(reverse) {
1413
+ var self = this, pos = clipPos(reverse ? this.pos.from : this.pos.to);
1414
+ function savePosAndFail(line) {
1415
+ var pos = {line: line, ch: 0};
1416
+ self.pos = {from: pos, to: pos};
1417
+ self.atOccurrence = false;
1418
+ return false;
1419
+ }
1420
+
1421
+ for (;;) {
1422
+ if (this.pos = this.matches(reverse, pos)) {
1423
+ this.atOccurrence = true;
1424
+ return this.pos.match || true;
1425
+ }
1426
+ if (reverse) {
1427
+ if (!pos.line) return savePosAndFail(0);
1428
+ pos = {line: pos.line-1, ch: lines[pos.line-1].text.length};
1429
+ }
1430
+ else {
1431
+ if (pos.line == lines.length - 1) return savePosAndFail(lines.length);
1432
+ pos = {line: pos.line+1, ch: 0};
1433
+ }
1434
+ }
1435
+ },
1436
+
1437
+ from: function() {if (this.atOccurrence) return copyPos(this.pos.from);},
1438
+ to: function() {if (this.atOccurrence) return copyPos(this.pos.to);}
1439
+ };
1440
+
1441
+ for (var ext in extensions)
1442
+ if (extensions.propertyIsEnumerable(ext) &&
1443
+ !instance.propertyIsEnumerable(ext))
1444
+ instance[ext] = extensions[ext];
1445
+ return instance;
1446
+ } // (end of function CodeMirror)
1447
+
1448
+ // The default configuration options.
1449
+ CodeMirror.defaults = {
1450
+ value: "",
1451
+ mode: null,
1452
+ theme: "default",
1453
+ indentUnit: 2,
1454
+ indentWithTabs: false,
1455
+ tabMode: "classic",
1456
+ enterMode: "indent",
1457
+ electricChars: true,
1458
+ onKeyEvent: null,
1459
+ lineNumbers: false,
1460
+ gutter: false,
1461
+ firstLineNumber: 1,
1462
+ readOnly: false,
1463
+ onChange: null,
1464
+ onCursorActivity: null,
1465
+ onGutterClick: null,
1466
+ onHighlightComplete: null,
1467
+ onFocus: null, onBlur: null, onScroll: null,
1468
+ matchBrackets: false,
1469
+ workTime: 100,
1470
+ workDelay: 200,
1471
+ undoDepth: 40,
1472
+ tabindex: null,
1473
+ document: window.document
1474
+ };
1475
+
1476
+ // Known modes, by name and by MIME
1477
+ var modes = {}, mimeModes = {};
1478
+ CodeMirror.defineMode = function(name, mode) {
1479
+ if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
1480
+ modes[name] = mode;
1481
+ };
1482
+ CodeMirror.defineMIME = function(mime, spec) {
1483
+ mimeModes[mime] = spec;
1484
+ };
1485
+ CodeMirror.getMode = function(options, spec) {
1486
+ if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
1487
+ spec = mimeModes[spec];
1488
+ if (typeof spec == "string")
1489
+ var mname = spec, config = {};
1490
+ else if (spec != null)
1491
+ var mname = spec.name, config = spec;
1492
+ var mfactory = modes[mname];
1493
+ if (!mfactory) {
1494
+ if (window.console) console.warn("No mode " + mname + " found, falling back to plain text.");
1495
+ return CodeMirror.getMode(options, "text/plain");
1496
+ }
1497
+ return mfactory(options, config || {});
1498
+ }
1499
+ CodeMirror.listModes = function() {
1500
+ var list = [];
1501
+ for (var m in modes)
1502
+ if (modes.propertyIsEnumerable(m)) list.push(m);
1503
+ return list;
1504
+ };
1505
+ CodeMirror.listMIMEs = function() {
1506
+ var list = [];
1507
+ for (var m in mimeModes)
1508
+ if (mimeModes.propertyIsEnumerable(m)) list.push(m);
1509
+ return list;
1510
+ };
1511
+
1512
+ var extensions = {};
1513
+ CodeMirror.defineExtension = function(name, func) {
1514
+ extensions[name] = func;
1515
+ };
1516
+
1517
+ CodeMirror.fromTextArea = function(textarea, options) {
1518
+ if (!options) options = {};
1519
+ options.value = textarea.value;
1520
+ if (!options.tabindex && textarea.tabindex)
1521
+ options.tabindex = textarea.tabindex;
1522
+
1523
+ function save() {textarea.value = instance.getValue();}
1524
+ if (textarea.form) {
1525
+ // Deplorable hack to make the submit method do the right thing.
1526
+ var rmSubmit = connect(textarea.form, "submit", save, true);
1527
+ if (typeof textarea.form.submit == "function") {
1528
+ var realSubmit = textarea.form.submit;
1529
+ function wrappedSubmit() {
1530
+ save();
1531
+ textarea.form.submit = realSubmit;
1532
+ textarea.form.submit();
1533
+ textarea.form.submit = wrappedSubmit;
1534
+ }
1535
+ textarea.form.submit = wrappedSubmit;
1536
+ }
1537
+ }
1538
+
1539
+ textarea.style.display = "none";
1540
+ var instance = CodeMirror(function(node) {
1541
+ textarea.parentNode.insertBefore(node, textarea.nextSibling);
1542
+ }, options);
1543
+ instance.save = save;
1544
+ instance.toTextArea = function() {
1545
+ save();
1546
+ textarea.parentNode.removeChild(instance.getWrapperElement());
1547
+ textarea.style.display = "";
1548
+ if (textarea.form) {
1549
+ rmSubmit();
1550
+ if (typeof textarea.form.submit == "function")
1551
+ textarea.form.submit = realSubmit;
1552
+ }
1553
+ };
1554
+ return instance;
1555
+ };
1556
+
1557
+ // Utility functions for working with state. Exported because modes
1558
+ // sometimes need to do this.
1559
+ function copyState(mode, state) {
1560
+ if (state === true) return state;
1561
+ if (mode.copyState) return mode.copyState(state);
1562
+ var nstate = {};
1563
+ for (var n in state) {
1564
+ var val = state[n];
1565
+ if (val instanceof Array) val = val.concat([]);
1566
+ nstate[n] = val;
1567
+ }
1568
+ return nstate;
1569
+ }
1570
+ CodeMirror.startState = startState;
1571
+ function startState(mode, a1, a2) {
1572
+ return mode.startState ? mode.startState(a1, a2) : true;
1573
+ }
1574
+ CodeMirror.copyState = copyState;
1575
+
1576
+ // The character stream used by a mode's parser.
1577
+ function StringStream(string) {
1578
+ this.pos = this.start = 0;
1579
+ this.string = string;
1580
+ }
1581
+ StringStream.prototype = {
1582
+ eol: function() {return this.pos >= this.string.length;},
1583
+ sol: function() {return this.pos == 0;},
1584
+ peek: function() {return this.string.charAt(this.pos);},
1585
+ next: function() {
1586
+ if (this.pos < this.string.length)
1587
+ return this.string.charAt(this.pos++);
1588
+ },
1589
+ eat: function(match) {
1590
+ var ch = this.string.charAt(this.pos);
1591
+ if (typeof match == "string") var ok = ch == match;
1592
+ else var ok = ch && (match.test ? match.test(ch) : match(ch));
1593
+ if (ok) {++this.pos; return ch;}
1594
+ },
1595
+ eatWhile: function(match) {
1596
+ var start = this.start;
1597
+ while (this.eat(match)){}
1598
+ return this.pos > start;
1599
+ },
1600
+ eatSpace: function() {
1601
+ var start = this.pos;
1602
+ while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
1603
+ return this.pos > start;
1604
+ },
1605
+ skipToEnd: function() {this.pos = this.string.length;},
1606
+ skipTo: function(ch) {
1607
+ var found = this.string.indexOf(ch, this.pos);
1608
+ if (found > -1) {this.pos = found; return true;}
1609
+ },
1610
+ backUp: function(n) {this.pos -= n;},
1611
+ column: function() {return countColumn(this.string, this.start);},
1612
+ indentation: function() {return countColumn(this.string);},
1613
+ match: function(pattern, consume, caseInsensitive) {
1614
+ if (typeof pattern == "string") {
1615
+ function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}
1616
+ if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
1617
+ if (consume !== false) this.pos += pattern.length;
1618
+ return true;
1619
+ }
1620
+ }
1621
+ else {
1622
+ var match = this.string.slice(this.pos).match(pattern);
1623
+ if (match && consume !== false) this.pos += match[0].length;
1624
+ return match;
1625
+ }
1626
+ },
1627
+ current: function(){return this.string.slice(this.start, this.pos);}
1628
+ };
1629
+ CodeMirror.StringStream = StringStream;
1630
+
1631
+ // Line objects. These hold state related to a line, including
1632
+ // highlighting info (the styles array).
1633
+ function Line(text, styles) {
1634
+ this.styles = styles || [text, null];
1635
+ this.stateAfter = null;
1636
+ this.text = text;
1637
+ this.marked = this.gutterMarker = this.className = null;
1638
+ }
1639
+ Line.prototype = {
1640
+ // Replace a piece of a line, keeping the styles around it intact.
1641
+ replace: function(from, to, text) {
1642
+ var st = [], mk = this.marked;
1643
+ copyStyles(0, from, this.styles, st);
1644
+ if (text) st.push(text, null);
1645
+ copyStyles(to, this.text.length, this.styles, st);
1646
+ this.styles = st;
1647
+ this.text = this.text.slice(0, from) + text + this.text.slice(to);
1648
+ this.stateAfter = null;
1649
+ if (mk) {
1650
+ var diff = text.length - (to - from), end = this.text.length;
1651
+ function fix(n) {return n <= Math.min(to, to + diff) ? n : n + diff;}
1652
+ for (var i = 0; i < mk.length; ++i) {
1653
+ var mark = mk[i], del = false;
1654
+ if (mark.from >= end) del = true;
1655
+ else {mark.from = fix(mark.from); if (mark.to != null) mark.to = fix(mark.to);}
1656
+ if (del || mark.from >= mark.to) {mk.splice(i, 1); i--;}
1657
+ }
1658
+ }
1659
+ },
1660
+ // Split a line in two, again keeping styles intact.
1661
+ split: function(pos, textBefore) {
1662
+ var st = [textBefore, null];
1663
+ copyStyles(pos, this.text.length, this.styles, st);
1664
+ return new Line(textBefore + this.text.slice(pos), st);
1665
+ },
1666
+ addMark: function(from, to, style) {
1667
+ var mk = this.marked, mark = {from: from, to: to, style: style};
1668
+ if (this.marked == null) this.marked = [];
1669
+ this.marked.push(mark);
1670
+ this.marked.sort(function(a, b){return a.from - b.from;});
1671
+ return mark;
1672
+ },
1673
+ removeMark: function(mark) {
1674
+ var mk = this.marked;
1675
+ if (!mk) return;
1676
+ for (var i = 0; i < mk.length; ++i)
1677
+ if (mk[i] == mark) {mk.splice(i, 1); break;}
1678
+ },
1679
+ // Run the given mode's parser over a line, update the styles
1680
+ // array, which contains alternating fragments of text and CSS
1681
+ // classes.
1682
+ highlight: function(mode, state) {
1683
+ var stream = new StringStream(this.text), st = this.styles, pos = 0;
1684
+ var changed = false, curWord = st[0], prevWord;
1685
+ if (this.text == "" && mode.blankLine) mode.blankLine(state);
1686
+ while (!stream.eol()) {
1687
+ var style = mode.token(stream, state);
1688
+ var substr = this.text.slice(stream.start, stream.pos);
1689
+ stream.start = stream.pos;
1690
+ if (pos && st[pos-1] == style)
1691
+ st[pos-2] += substr;
1692
+ else if (substr) {
1693
+ if (!changed && (st[pos+1] != style || (pos && st[pos-2] != prevWord))) changed = true;
1694
+ st[pos++] = substr; st[pos++] = style;
1695
+ prevWord = curWord; curWord = st[pos];
1696
+ }
1697
+ // Give up when line is ridiculously long
1698
+ if (stream.pos > 5000) {
1699
+ st[pos++] = this.text.slice(stream.pos); st[pos++] = null;
1700
+ break;
1701
+ }
1702
+ }
1703
+ if (st.length != pos) {st.length = pos; changed = true;}
1704
+ if (pos && st[pos-2] != prevWord) changed = true;
1705
+ // Short lines with simple highlights always count as changed,
1706
+ // because they are likely to highlight the same way in various
1707
+ // contexts.
1708
+ return changed || (st.length < 5 && this.text.length < 10);
1709
+ },
1710
+ // Fetch the parser token for a given character. Useful for hacks
1711
+ // that want to inspect the mode state (say, for completion).
1712
+ getTokenAt: function(mode, state, ch) {
1713
+ var txt = this.text, stream = new StringStream(txt);
1714
+ while (stream.pos < ch && !stream.eol()) {
1715
+ stream.start = stream.pos;
1716
+ var style = mode.token(stream, state);
1717
+ }
1718
+ return {start: stream.start,
1719
+ end: stream.pos,
1720
+ string: stream.current(),
1721
+ className: style || null,
1722
+ state: state};
1723
+ },
1724
+ indentation: function() {return countColumn(this.text);},
1725
+ // Produces an HTML fragment for the line, taking selection,
1726
+ // marking, and highlighting into account.
1727
+ getHTML: function(sfrom, sto, includePre, endAt) {
1728
+ var html = [];
1729
+ if (includePre)
1730
+ html.push(this.className ? '<pre class="' + this.className + '">': "<pre>");
1731
+ function span(text, style) {
1732
+ if (!text) return;
1733
+ if (style) html.push('<span class="cm-', style, '">', htmlEscape(text), "</span>");
1734
+ else html.push(htmlEscape(text));
1735
+ }
1736
+ var st = this.styles, allText = this.text, marked = this.marked;
1737
+ if (sfrom == sto) sfrom = null;
1738
+ var len = allText.length;
1739
+ if (endAt != null) len = Math.min(endAt, len);
1740
+
1741
+ if (!allText && endAt == null)
1742
+ span(" ", sfrom != null && sto == null ? "CodeMirror-selected" : null);
1743
+ else if (!marked && sfrom == null)
1744
+ for (var i = 0, ch = 0; ch < len; i+=2) {
1745
+ var str = st[i], l = str.length;
1746
+ if (ch + l > len) str = str.slice(0, len - ch);
1747
+ ch += l;
1748
+ span(str, st[i+1]);
1749
+ }
1750
+ else {
1751
+ var pos = 0, i = 0, text = "", style, sg = 0;
1752
+ var markpos = -1, mark = null;
1753
+ function nextMark() {
1754
+ if (marked) {
1755
+ markpos += 1;
1756
+ mark = (markpos < marked.length) ? marked[markpos] : null;
1757
+ }
1758
+ }
1759
+ nextMark();
1760
+ while (pos < len) {
1761
+ var upto = len;
1762
+ var extraStyle = "";
1763
+ if (sfrom != null) {
1764
+ if (sfrom > pos) upto = sfrom;
1765
+ else if (sto == null || sto > pos) {
1766
+ extraStyle = " CodeMirror-selected";
1767
+ if (sto != null) upto = Math.min(upto, sto);
1768
+ }
1769
+ }
1770
+ while (mark && mark.to != null && mark.to <= pos) nextMark();
1771
+ if (mark) {
1772
+ if (mark.from > pos) upto = Math.min(upto, mark.from);
1773
+ else {
1774
+ extraStyle += " " + mark.style;
1775
+ if (mark.to != null) upto = Math.min(upto, mark.to);
1776
+ }
1777
+ }
1778
+ for (;;) {
1779
+ var end = pos + text.length;
1780
+ var apliedStyle = style;
1781
+ if (extraStyle) apliedStyle = style ? style + extraStyle : extraStyle;
1782
+ span(end > upto ? text.slice(0, upto - pos) : text, apliedStyle);
1783
+ if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
1784
+ pos = end;
1785
+ text = st[i++]; style = st[i++];
1786
+ }
1787
+ }
1788
+ if (sfrom != null && sto == null) span(" ", "CodeMirror-selected");
1789
+ }
1790
+ if (includePre) html.push("</pre>");
1791
+ return html.join("");
1792
+ }
1793
+ };
1794
+ // Utility used by replace and split above
1795
+ function copyStyles(from, to, source, dest) {
1796
+ for (var i = 0, pos = 0, state = 0; pos < to; i+=2) {
1797
+ var part = source[i], end = pos + part.length;
1798
+ if (state == 0) {
1799
+ if (end > from) dest.push(part.slice(from - pos, Math.min(part.length, to - pos)), source[i+1]);
1800
+ if (end >= from) state = 1;
1801
+ }
1802
+ else if (state == 1) {
1803
+ if (end > to) dest.push(part.slice(0, to - pos), source[i+1]);
1804
+ else dest.push(part, source[i+1]);
1805
+ }
1806
+ pos = end;
1807
+ }
1808
+ }
1809
+
1810
+ // The history object 'chunks' changes that are made close together
1811
+ // and at almost the same time into bigger undoable units.
1812
+ function History() {
1813
+ this.time = 0;
1814
+ this.done = []; this.undone = [];
1815
+ }
1816
+ History.prototype = {
1817
+ addChange: function(start, added, old) {
1818
+ this.undone.length = 0;
1819
+ var time = +new Date, last = this.done[this.done.length - 1];
1820
+ if (time - this.time > 400 || !last ||
1821
+ last.start > start + added || last.start + last.added < start - last.added + last.old.length)
1822
+ this.done.push({start: start, added: added, old: old});
1823
+ else {
1824
+ var oldoff = 0;
1825
+ if (start < last.start) {
1826
+ for (var i = last.start - start - 1; i >= 0; --i)
1827
+ last.old.unshift(old[i]);
1828
+ last.added += last.start - start;
1829
+ last.start = start;
1830
+ }
1831
+ else if (last.start < start) {
1832
+ oldoff = start - last.start;
1833
+ added += oldoff;
1834
+ }
1835
+ for (var i = last.added - oldoff, e = old.length; i < e; ++i)
1836
+ last.old.push(old[i]);
1837
+ if (last.added < added) last.added = added;
1838
+ }
1839
+ this.time = time;
1840
+ }
1841
+ };
1842
+
1843
+ // Event stopping compatibility wrapper.
1844
+ function stopEvent() {
1845
+ if (this.preventDefault) {this.preventDefault(); this.stopPropagation();}
1846
+ else {this.returnValue = false; this.cancelBubble = true;}
1847
+ }
1848
+ // Ensure an event has a stop method.
1849
+ function addStop(event) {
1850
+ if (!event.stop) event.stop = stopEvent;
1851
+ return event;
1852
+ }
1853
+
1854
+ // Event wrapper, exposing the few operations we need.
1855
+ function Event(orig) {this.e = orig;}
1856
+ Event.prototype = {
1857
+ stop: function() {stopEvent.call(this.e);},
1858
+ target: function() {return this.e.target || this.e.srcElement;},
1859
+ button: function() {
1860
+ if (this.e.which) return this.e.which;
1861
+ else if (this.e.button & 1) return 1;
1862
+ else if (this.e.button & 2) return 3;
1863
+ else if (this.e.button & 4) return 2;
1864
+ },
1865
+ pageX: function() {
1866
+ if (this.e.pageX != null) return this.e.pageX;
1867
+ var doc = this.target().ownerDocument;
1868
+ return this.e.clientX + doc.body.scrollLeft + doc.documentElement.scrollLeft;
1869
+ },
1870
+ pageY: function() {
1871
+ if (this.e.pageY != null) return this.e.pageY;
1872
+ var doc = this.target().ownerDocument;
1873
+ return this.e.clientY + doc.body.scrollTop + doc.documentElement.scrollTop;
1874
+ }
1875
+ };
1876
+
1877
+ // Event handler registration. If disconnect is true, it'll return a
1878
+ // function that unregisters the handler.
1879
+ function connect(node, type, handler, disconnect) {
1880
+ function wrapHandler(event) {handler(new Event(event || window.event));}
1881
+ if (typeof node.addEventListener == "function") {
1882
+ node.addEventListener(type, wrapHandler, false);
1883
+ if (disconnect) return function() {node.removeEventListener(type, wrapHandler, false);};
1884
+ }
1885
+ else {
1886
+ node.attachEvent("on" + type, wrapHandler);
1887
+ if (disconnect) return function() {node.detachEvent("on" + type, wrapHandler);};
1888
+ }
1889
+ }
1890
+
1891
+ function Delayed() {this.id = null;}
1892
+ Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
1893
+
1894
+ // Some IE versions don't preserve whitespace when setting the
1895
+ // innerHTML of a PRE tag.
1896
+ var badInnerHTML = (function() {
1897
+ var pre = document.createElement("pre");
1898
+ pre.innerHTML = " "; return !pre.innerHTML;
1899
+ })();
1900
+
1901
+ var gecko = /gecko\/\d{7}/i.test(navigator.userAgent);
1902
+ var ie = /MSIE \d/.test(navigator.userAgent);
1903
+ var safari = /Apple Computer/.test(navigator.vendor);
1904
+
1905
+ var lineSep = "\n";
1906
+ // Feature-detect whether newlines in textareas are converted to \r\n
1907
+ (function () {
1908
+ var te = document.createElement("textarea");
1909
+ te.value = "foo\nbar";
1910
+ if (te.value.indexOf("\r") > -1) lineSep = "\r\n";
1911
+ }());
1912
+
1913
+ var tabSize = 8;
1914
+ var mac = /Mac/.test(navigator.platform);
1915
+ var movementKeys = {};
1916
+ for (var i = 35; i <= 40; ++i)
1917
+ movementKeys[i] = movementKeys["c" + i] = true;
1918
+
1919
+ // Counts the column offset in a string, taking tabs into account.
1920
+ // Used mostly to find indentation.
1921
+ function countColumn(string, end) {
1922
+ if (end == null) {
1923
+ end = string.search(/[^\s\u00a0]/);
1924
+ if (end == -1) end = string.length;
1925
+ }
1926
+ for (var i = 0, n = 0; i < end; ++i) {
1927
+ if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
1928
+ else ++n;
1929
+ }
1930
+ return n;
1931
+ }
1932
+
1933
+ // Find the position of an element by following the offsetParent chain.
1934
+ // If screen==true, it returns screen (rather than page) coordinates.
1935
+ function eltOffset(node, screen) {
1936
+ var doc = node.ownerDocument.body;
1937
+ var x = 0, y = 0, hitDoc = false;
1938
+ for (var n = node; n; n = n.offsetParent) {
1939
+ x += n.offsetLeft; y += n.offsetTop;
1940
+ // Fixed-position elements don't have the document in their offset chain
1941
+ if (n == doc) hitDoc = true;
1942
+ }
1943
+ var e = screen && hitDoc ? null : doc;
1944
+ for (var n = node.parentNode; n != e; n = n.parentNode)
1945
+ if (n.scrollLeft != null) { x -= n.scrollLeft; y -= n.scrollTop;}
1946
+ return {left: x, top: y};
1947
+ }
1948
+ // Get a node's text content.
1949
+ function eltText(node) {
1950
+ return node.textContent || node.innerText || node.nodeValue || "";
1951
+ }
1952
+
1953
+ // Operations on {line, ch} objects.
1954
+ function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
1955
+ function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
1956
+ function copyPos(x) {return {line: x.line, ch: x.ch};}
1957
+
1958
+ function htmlEscape(str) {
1959
+ return str.replace(/[<>&]/g, function(str) {
1960
+ return str == "&" ? "&amp;" : str == "<" ? "&lt;" : "&gt;";
1961
+ });
1962
+ }
1963
+ CodeMirror.htmlEscape = htmlEscape;
1964
+
1965
+ // Used to position the cursor after an undo/redo by finding the
1966
+ // last edited character.
1967
+ function editEnd(from, to) {
1968
+ if (!to) return from ? from.length : 0;
1969
+ if (!from) return to.length;
1970
+ for (var i = from.length, j = to.length; i >= 0 && j >= 0; --i, --j)
1971
+ if (from.charAt(i) != to.charAt(j)) break;
1972
+ return j + 1;
1973
+ }
1974
+
1975
+ function indexOf(collection, elt) {
1976
+ if (collection.indexOf) return collection.indexOf(elt);
1977
+ for (var i = 0, e = collection.length; i < e; ++i)
1978
+ if (collection[i] == elt) return i;
1979
+ return -1;
1980
+ }
1981
+
1982
+ // See if "".split is the broken IE version, if so, provide an
1983
+ // alternative way to split lines.
1984
+ if ("\n\nb".split(/\n/).length != 3)
1985
+ var splitLines = function(string) {
1986
+ var pos = 0, nl, result = [];
1987
+ while ((nl = string.indexOf("\n", pos)) > -1) {
1988
+ result.push(string.slice(pos, string.charAt(nl-1) == "\r" ? nl - 1 : nl));
1989
+ pos = nl + 1;
1990
+ }
1991
+ result.push(string.slice(pos));
1992
+ return result;
1993
+ };
1994
+ else
1995
+ var splitLines = function(string){return string.split(/\r?\n/);};
1996
+ CodeMirror.splitLines = splitLines;
1997
+
1998
+ // Sane model of finding and setting the selection in a textarea
1999
+ if (window.getSelection) {
2000
+ var selRange = function(te) {
2001
+ try {return {start: te.selectionStart, end: te.selectionEnd};}
2002
+ catch(e) {return null;}
2003
+ };
2004
+ if (safari)
2005
+ // On Safari, selection set with setSelectionRange are in a sort
2006
+ // of limbo wrt their anchor. If you press shift-left in them,
2007
+ // the anchor is put at the end, and the selection expanded to
2008
+ // the left. If you press shift-right, the anchor ends up at the
2009
+ // front. This is not what CodeMirror wants, so it does a
2010
+ // spurious modify() call to get out of limbo.
2011
+ var setSelRange = function(te, start, end) {
2012
+ if (start == end)
2013
+ te.setSelectionRange(start, end);
2014
+ else {
2015
+ te.setSelectionRange(start, end - 1);
2016
+ window.getSelection().modify("extend", "forward", "character");
2017
+ }
2018
+ };
2019
+ else
2020
+ var setSelRange = function(te, start, end) {
2021
+ try {te.setSelectionRange(start, end);}
2022
+ catch(e) {} // Fails on Firefox when textarea isn't part of the document
2023
+ };
2024
+ }
2025
+ // IE model. Don't ask.
2026
+ else {
2027
+ var selRange = function(te) {
2028
+ try {var range = te.ownerDocument.selection.createRange();}
2029
+ catch(e) {return null;}
2030
+ if (!range || range.parentElement() != te) return null;
2031
+ var val = te.value, len = val.length, localRange = te.createTextRange();
2032
+ localRange.moveToBookmark(range.getBookmark());
2033
+ var endRange = te.createTextRange();
2034
+ endRange.collapse(false);
2035
+
2036
+ if (localRange.compareEndPoints("StartToEnd", endRange) > -1)
2037
+ return {start: len, end: len};
2038
+
2039
+ var start = -localRange.moveStart("character", -len);
2040
+ for (var i = val.indexOf("\r"); i > -1 && i < start; i = val.indexOf("\r", i+1), start++) {}
2041
+
2042
+ if (localRange.compareEndPoints("EndToEnd", endRange) > -1)
2043
+ return {start: start, end: len};
2044
+
2045
+ var end = -localRange.moveEnd("character", -len);
2046
+ for (var i = val.indexOf("\r"); i > -1 && i < end; i = val.indexOf("\r", i+1), end++) {}
2047
+ return {start: start, end: end};
2048
+ };
2049
+ var setSelRange = function(te, start, end) {
2050
+ var range = te.createTextRange();
2051
+ range.collapse(true);
2052
+ var endrange = range.duplicate();
2053
+ var newlines = 0, txt = te.value;
2054
+ for (var pos = txt.indexOf("\n"); pos > -1 && pos < start; pos = txt.indexOf("\n", pos + 1))
2055
+ ++newlines;
2056
+ range.move("character", start - newlines);
2057
+ for (; pos > -1 && pos < end; pos = txt.indexOf("\n", pos + 1))
2058
+ ++newlines;
2059
+ endrange.move("character", end - newlines);
2060
+ range.setEndPoint("EndToEnd", endrange);
2061
+ range.select();
2062
+ };
2063
+ }
2064
+
2065
+ CodeMirror.defineMode("null", function() {
2066
+ return {token: function(stream) {stream.skipToEnd();}};
2067
+ });
2068
+ CodeMirror.defineMIME("text/plain", "null");
2069
+
2070
+ return CodeMirror;
2071
+ })();