honey-cms 0.1.2 → 0.2.0

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