puffer_pages 0.0.18 → 0.0.19

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