rack-push-notification 0.2.0 → 0.4.0

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