View | Details | Raw Unified | Return to bug 11559
Collapse All | Expand All

(-)a/koha-tmpl/intranet-tmpl/lib/codemirror/codemirror.css (+248 lines)
Line 0 Link Here
1
/* BASICS */
2
3
.CodeMirror {
4
  /* Set height, width, borders, and global font properties here */
5
  font-family: monospace;
6
  height: 300px;
7
}
8
.CodeMirror-scroll {
9
  /* Set scrolling behaviour here */
10
  overflow: auto;
11
}
12
13
/* PADDING */
14
15
.CodeMirror-lines {
16
  padding: 4px 0; /* Vertical padding around content */
17
}
18
.CodeMirror pre {
19
  padding: 0 4px; /* Horizontal padding of content */
20
}
21
22
.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
23
  background-color: white; /* The little square between H and V scrollbars */
24
}
25
26
/* GUTTER */
27
28
.CodeMirror-gutters {
29
  border-right: 1px solid #ddd;
30
  background-color: #f7f7f7;
31
  white-space: nowrap;
32
}
33
.CodeMirror-linenumbers {}
34
.CodeMirror-linenumber {
35
  padding: 0 3px 0 5px;
36
  min-width: 20px;
37
  text-align: right;
38
  color: #999;
39
}
40
41
/* CURSOR */
42
43
.CodeMirror div.CodeMirror-cursor {
44
  border-left: 1px solid black;
45
  z-index: 3;
46
}
47
/* Shown when moving in bi-directional text */
48
.CodeMirror div.CodeMirror-secondarycursor {
49
  border-left: 1px solid silver;
50
}
51
.CodeMirror.cm-keymap-fat-cursor div.CodeMirror-cursor {
52
  width: auto;
53
  border: 0;
54
  background: #7e7;
55
  z-index: 1;
56
}
57
/* Can style cursor different in overwrite (non-insert) mode */
58
.CodeMirror div.CodeMirror-cursor.CodeMirror-overwrite {}
59
60
.cm-tab { display: inline-block; }
61
62
/* DEFAULT THEME */
63
64
.cm-s-default .cm-keyword {color: #708;}
65
.cm-s-default .cm-atom {color: #219;}
66
.cm-s-default .cm-number {color: #164;}
67
.cm-s-default .cm-def {color: #00f;}
68
.cm-s-default .cm-variable {color: black;}
69
.cm-s-default .cm-variable-2 {color: #05a;}
70
.cm-s-default .cm-variable-3 {color: #085;}
71
.cm-s-default .cm-property {color: black;}
72
.cm-s-default .cm-operator {color: black;}
73
.cm-s-default .cm-comment {color: #a50;}
74
.cm-s-default .cm-string {color: #a11;}
75
.cm-s-default .cm-string-2 {color: #f50;}
76
.cm-s-default .cm-meta {color: #555;}
77
.cm-s-default .cm-error {color: #f00;}
78
.cm-s-default .cm-qualifier {color: #555;}
79
.cm-s-default .cm-builtin {color: #30a;}
80
.cm-s-default .cm-bracket {color: #997;}
81
.cm-s-default .cm-tag {color: #170;}
82
.cm-s-default .cm-attribute {color: #00c;}
83
.cm-s-default .cm-header {color: blue;}
84
.cm-s-default .cm-quote {color: #090;}
85
.cm-s-default .cm-hr {color: #999;}
86
.cm-s-default .cm-link {color: #00c;}
87
88
.cm-negative {color: #d44;}
89
.cm-positive {color: #292;}
90
.cm-header, .cm-strong {font-weight: bold;}
91
.cm-em {font-style: italic;}
92
.cm-link {text-decoration: underline;}
93
94
.cm-invalidchar {color: #f00;}
95
96
div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
97
div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
98
99
/* STOP */
100
101
/* The rest of this file contains styles related to the mechanics of
102
   the editor. You probably shouldn't touch them. */
103
104
.CodeMirror {
105
  line-height: 1;
106
  position: relative;
107
  overflow: hidden;
108
  background: white;
109
  color: black;
110
}
111
112
.CodeMirror-scroll {
113
  /* 30px is the magic margin used to hide the element's real scrollbars */
114
  /* See overflow: hidden in .CodeMirror */
115
  margin-bottom: -30px; margin-right: -30px;
116
  padding-bottom: 30px; padding-right: 30px;
117
  height: 100%;
118
  outline: none; /* Prevent dragging from highlighting the element */
119
  position: relative;
120
}
121
.CodeMirror-sizer {
122
  position: relative;
123
}
124
125
/* The fake, visible scrollbars. Used to force redraw during scrolling
126
   before actuall scrolling happens, thus preventing shaking and
127
   flickering artifacts. */
128
.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
129
  position: absolute;
130
  z-index: 6;
131
  display: none;
132
}
133
.CodeMirror-vscrollbar {
134
  right: 0; top: 0;
135
  overflow-x: hidden;
136
  overflow-y: scroll;
137
}
138
.CodeMirror-hscrollbar {
139
  bottom: 0; left: 0;
140
  overflow-y: hidden;
141
  overflow-x: scroll;
142
}
143
.CodeMirror-scrollbar-filler {
144
  right: 0; bottom: 0;
145
}
146
.CodeMirror-gutter-filler {
147
  left: 0; bottom: 0;
148
}
149
150
.CodeMirror-gutters {
151
  position: absolute; left: 0; top: 0;
152
  padding-bottom: 30px;
153
  z-index: 3;
154
}
155
.CodeMirror-gutter {
156
  white-space: normal;
157
  height: 100%;
158
  padding-bottom: 30px;
159
  margin-bottom: -32px;
160
  display: inline-block;
161
  /* Hack to make IE7 behave */
162
  *zoom:1;
163
  *display:inline;
164
}
165
.CodeMirror-gutter-elt {
166
  position: absolute;
167
  cursor: default;
168
  z-index: 4;
169
}
170
171
.CodeMirror-lines {
172
  cursor: text;
173
}
174
.CodeMirror pre {
175
  /* Reset some styles that the rest of the page might have set */
176
  -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
177
  border-width: 0;
178
  background: transparent;
179
  font-family: inherit;
180
  font-size: inherit;
181
  margin: 0;
182
  white-space: pre;
183
  word-wrap: normal;
184
  line-height: inherit;
185
  color: inherit;
186
  z-index: 2;
187
  position: relative;
188
  overflow: visible;
189
}
190
.CodeMirror-wrap pre {
191
  word-wrap: break-word;
192
  white-space: pre-wrap;
193
  word-break: normal;
194
}
195
.CodeMirror-linebackground {
196
  position: absolute;
197
  left: 0; right: 0; top: 0; bottom: 0;
198
  z-index: 0;
199
}
200
201
.CodeMirror-linewidget {
202
  position: relative;
203
  z-index: 2;
204
  overflow: auto;
205
}
206
207
.CodeMirror-widget {
208
}
209
210
.CodeMirror-wrap .CodeMirror-scroll {
211
  overflow-x: hidden;
212
}
213
214
.CodeMirror-measure {
215
  position: absolute;
216
  width: 100%; height: 0px;
217
  overflow: hidden;
218
  visibility: hidden;
219
}
220
.CodeMirror-measure pre { position: static; }
221
222
.CodeMirror div.CodeMirror-cursor {
223
  position: absolute;
224
  visibility: hidden;
225
  border-right: none;
226
  width: 0;
227
}
228
.CodeMirror-focused div.CodeMirror-cursor {
229
  visibility: visible;
230
}
231
232
.CodeMirror-selected { background: #d9d9d9; }
233
.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
234
235
.cm-searching {
236
  background: #ffa;
237
  background: rgba(255, 255, 0, .4);
238
}
239
240
/* IE7 hack to prevent it from returning funny offsetTops on the spans */
241
.CodeMirror span { *vertical-align: text-bottom; }
242
243
@media print {
244
  /* Hide the cursor when printing */
245
  .CodeMirror div.CodeMirror-cursor {
246
    visibility: hidden;
247
  }
248
}
(-)a/koha-tmpl/intranet-tmpl/lib/codemirror/codemirror.js (+5715 lines)
Line 0 Link Here
1
// CodeMirror version 3.14
2
//
3
// CodeMirror is the only global var we claim
4
window.CodeMirror = (function() {
5
  "use strict";
6
7
  // BROWSER SNIFFING
8
9
  // Crude, but necessary to handle a number of hard-to-feature-detect
10
  // bugs and behavior differences.
11
  var gecko = /gecko\/\d/i.test(navigator.userAgent);
12
  var ie = /MSIE \d/.test(navigator.userAgent);
13
  var ie_lt8 = ie && (document.documentMode == null || document.documentMode < 8);
14
  var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9);
15
  var webkit = /WebKit\//.test(navigator.userAgent);
16
  var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
17
  var chrome = /Chrome\//.test(navigator.userAgent);
18
  var opera = /Opera\//.test(navigator.userAgent);
19
  var safari = /Apple Computer/.test(navigator.vendor);
20
  var khtml = /KHTML\//.test(navigator.userAgent);
21
  var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent);
22
  var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
23
  var phantom = /PhantomJS/.test(navigator.userAgent);
24
25
  var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
26
  // This is woefully incomplete. Suggestions for alternative methods welcome.
27
  var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
28
  var mac = ios || /Mac/.test(navigator.platform);
29
  var windows = /windows/i.test(navigator.platform);
30
31
  var opera_version = opera && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
32
  if (opera_version) opera_version = Number(opera_version[1]);
33
  // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
34
  var flipCtrlCmd = mac && (qtwebkit || opera && (opera_version == null || opera_version < 12.11));
35
  var captureMiddleClick = gecko || (ie && !ie_lt9);
36
37
  // Optimize some code when these features are not used
38
  var sawReadOnlySpans = false, sawCollapsedSpans = false;
39
40
  // CONSTRUCTOR
41
42
  function CodeMirror(place, options) {
43
    if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
44
45
    this.options = options = options || {};
46
    // Determine effective options based on given values and defaults.
47
    for (var opt in defaults) if (!options.hasOwnProperty(opt) && defaults.hasOwnProperty(opt))
48
      options[opt] = defaults[opt];
49
    setGuttersForLineNumbers(options);
50
51
    var docStart = typeof options.value == "string" ? 0 : options.value.first;
52
    var display = this.display = makeDisplay(place, docStart);
53
    display.wrapper.CodeMirror = this;
54
    updateGutters(this);
55
    if (options.autofocus && !mobile) focusInput(this);
56
57
    this.state = {keyMaps: [],
58
                  overlays: [],
59
                  modeGen: 0,
60
                  overwrite: false, focused: false,
61
                  suppressEdits: false, pasteIncoming: false,
62
                  draggingText: false,
63
                  highlight: new Delayed()};
64
65
    themeChanged(this);
66
    if (options.lineWrapping)
67
      this.display.wrapper.className += " CodeMirror-wrap";
68
69
    var doc = options.value;
70
    if (typeof doc == "string") doc = new Doc(options.value, options.mode);
71
    operation(this, attachDoc)(this, doc);
72
73
    // Override magic textarea content restore that IE sometimes does
74
    // on our hidden textarea on reload
75
    if (ie) setTimeout(bind(resetInput, this, true), 20);
76
77
    registerEventHandlers(this);
78
    // IE throws unspecified error in certain cases, when
79
    // trying to access activeElement before onload
80
    var hasFocus; try { hasFocus = (document.activeElement == display.input); } catch(e) { }
81
    if (hasFocus || (options.autofocus && !mobile)) setTimeout(bind(onFocus, this), 20);
82
    else onBlur(this);
83
84
    operation(this, function() {
85
      for (var opt in optionHandlers)
86
        if (optionHandlers.propertyIsEnumerable(opt))
87
          optionHandlers[opt](this, options[opt], Init);
88
      for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
89
    })();
90
  }
91
92
  // DISPLAY CONSTRUCTOR
93
94
  function makeDisplay(place, docStart) {
95
    var d = {};
96
97
    var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none; font-size: 4px;");
98
    if (webkit) input.style.width = "1000px";
99
    else input.setAttribute("wrap", "off");
100
    // if border: 0; -- iOS fails to open keyboard (issue #1287)
101
    if (ios) input.style.border = "1px solid black";
102
    input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); input.setAttribute("spellcheck", "false");
103
104
    // Wraps and hides input textarea
105
    d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
106
    // The actual fake scrollbars.
107
    d.scrollbarH = elt("div", [elt("div", null, null, "height: 1px")], "CodeMirror-hscrollbar");
108
    d.scrollbarV = elt("div", [elt("div", null, null, "width: 1px")], "CodeMirror-vscrollbar");
109
    d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
110
    d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
111
    // DIVs containing the selection and the actual code
112
    d.lineDiv = elt("div", null, "CodeMirror-code");
113
    d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
114
    // Blinky cursor, and element used to ensure cursor fits at the end of a line
115
    d.cursor = elt("div", "\u00a0", "CodeMirror-cursor");
116
    // Secondary cursor, shown when on a 'jump' in bi-directional text
117
    d.otherCursor = elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor");
118
    // Used to measure text size
119
    d.measure = elt("div", null, "CodeMirror-measure");
120
    // Wraps everything that needs to exist inside the vertically-padded coordinate system
121
    d.lineSpace = elt("div", [d.measure, d.selectionDiv, d.lineDiv, d.cursor, d.otherCursor],
122
                         null, "position: relative; outline: none");
123
    // Moved around its parent to cover visible view
124
    d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
125
    // Set to the height of the text, causes scrolling
126
    d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
127
    // D is needed because behavior of elts with overflow: auto and padding is inconsistent across browsers
128
    d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerCutOff + "px; width: 1px;");
129
    // Will contain the gutters, if any
130
    d.gutters = elt("div", null, "CodeMirror-gutters");
131
    d.lineGutter = null;
132
    // Provides scrolling
133
    d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
134
    d.scroller.setAttribute("tabIndex", "-1");
135
    // The element in which the editor lives.
136
    d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV,
137
                            d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
138
    // Work around IE7 z-index bug
139
    if (ie_lt8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
140
    if (place.appendChild) place.appendChild(d.wrapper); else place(d.wrapper);
141
142
    // Needed to hide big blue blinking cursor on Mobile Safari
143
    if (ios) input.style.width = "0px";
144
    if (!webkit) d.scroller.draggable = true;
145
    // Needed to handle Tab key in KHTML
146
    if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; }
147
    // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
148
    else if (ie_lt8) d.scrollbarH.style.minWidth = d.scrollbarV.style.minWidth = "18px";
149
150
    // Current visible range (may be bigger than the view window).
151
    d.viewOffset = d.lastSizeC = 0;
152
    d.showingFrom = d.showingTo = docStart;
153
154
    // Used to only resize the line number gutter when necessary (when
155
    // the amount of lines crosses a boundary that makes its width change)
156
    d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
157
    // See readInput and resetInput
158
    d.prevInput = "";
159
    // Set to true when a non-horizontal-scrolling widget is added. As
160
    // an optimization, widget aligning is skipped when d is false.
161
    d.alignWidgets = false;
162
    // Flag that indicates whether we currently expect input to appear
163
    // (after some event like 'keypress' or 'input') and are polling
164
    // intensively.
165
    d.pollingFast = false;
166
    // Self-resetting timeout for the poller
167
    d.poll = new Delayed();
168
169
    d.cachedCharWidth = d.cachedTextHeight = null;
170
    d.measureLineCache = [];
171
    d.measureLineCachePos = 0;
172
173
    // Tracks when resetInput has punted to just putting a short
174
    // string instead of the (large) selection.
175
    d.inaccurateSelection = false;
176
177
    // Tracks the maximum line length so that the horizontal scrollbar
178
    // can be kept static when scrolling.
179
    d.maxLine = null;
180
    d.maxLineLength = 0;
181
    d.maxLineChanged = false;
182
183
    // Used for measuring wheel scrolling granularity
184
    d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
185
186
    return d;
187
  }
188
189
  // STATE UPDATES
190
191
  // Used to get the editor into a consistent state again when options change.
192
193
  function loadMode(cm) {
194
    cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
195
    cm.doc.iter(function(line) {
196
      if (line.stateAfter) line.stateAfter = null;
197
      if (line.styles) line.styles = null;
198
    });
199
    cm.doc.frontier = cm.doc.first;
200
    startWorker(cm, 100);
201
    cm.state.modeGen++;
202
    if (cm.curOp) regChange(cm);
203
  }
204
205
  function wrappingChanged(cm) {
206
    if (cm.options.lineWrapping) {
207
      cm.display.wrapper.className += " CodeMirror-wrap";
208
      cm.display.sizer.style.minWidth = "";
209
    } else {
210
      cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", "");
211
      computeMaxLength(cm);
212
    }
213
    estimateLineHeights(cm);
214
    regChange(cm);
215
    clearCaches(cm);
216
    setTimeout(function(){updateScrollbars(cm);}, 100);
217
  }
218
219
  function estimateHeight(cm) {
220
    var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
221
    var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
222
    return function(line) {
223
      if (lineIsHidden(cm.doc, line))
224
        return 0;
225
      else if (wrapping)
226
        return (Math.ceil(line.text.length / perLine) || 1) * th;
227
      else
228
        return th;
229
    };
230
  }
231
232
  function estimateLineHeights(cm) {
233
    var doc = cm.doc, est = estimateHeight(cm);
234
    doc.iter(function(line) {
235
      var estHeight = est(line);
236
      if (estHeight != line.height) updateLineHeight(line, estHeight);
237
    });
238
  }
239
240
  function keyMapChanged(cm) {
241
    var map = keyMap[cm.options.keyMap], style = map.style;
242
    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") +
243
      (style ? " cm-keymap-" + style : "");
244
    cm.state.disableInput = map.disableInput;
245
  }
246
247
  function themeChanged(cm) {
248
    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
249
      cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
250
    clearCaches(cm);
251
  }
252
253
  function guttersChanged(cm) {
254
    updateGutters(cm);
255
    regChange(cm);
256
    setTimeout(function(){alignHorizontally(cm);}, 20);
257
  }
258
259
  function updateGutters(cm) {
260
    var gutters = cm.display.gutters, specs = cm.options.gutters;
261
    removeChildren(gutters);
262
    for (var i = 0; i < specs.length; ++i) {
263
      var gutterClass = specs[i];
264
      var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
265
      if (gutterClass == "CodeMirror-linenumbers") {
266
        cm.display.lineGutter = gElt;
267
        gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
268
      }
269
    }
270
    gutters.style.display = i ? "" : "none";
271
  }
272
273
  function lineLength(doc, line) {
274
    if (line.height == 0) return 0;
275
    var len = line.text.length, merged, cur = line;
276
    while (merged = collapsedSpanAtStart(cur)) {
277
      var found = merged.find();
278
      cur = getLine(doc, found.from.line);
279
      len += found.from.ch - found.to.ch;
280
    }
281
    cur = line;
282
    while (merged = collapsedSpanAtEnd(cur)) {
283
      var found = merged.find();
284
      len -= cur.text.length - found.from.ch;
285
      cur = getLine(doc, found.to.line);
286
      len += cur.text.length - found.to.ch;
287
    }
288
    return len;
289
  }
290
291
  function computeMaxLength(cm) {
292
    var d = cm.display, doc = cm.doc;
293
    d.maxLine = getLine(doc, doc.first);
294
    d.maxLineLength = lineLength(doc, d.maxLine);
295
    d.maxLineChanged = true;
296
    doc.iter(function(line) {
297
      var len = lineLength(doc, line);
298
      if (len > d.maxLineLength) {
299
        d.maxLineLength = len;
300
        d.maxLine = line;
301
      }
302
    });
303
  }
304
305
  // Make sure the gutters options contains the element
306
  // "CodeMirror-linenumbers" when the lineNumbers option is true.
307
  function setGuttersForLineNumbers(options) {
308
    var found = false;
309
    for (var i = 0; i < options.gutters.length; ++i) {
310
      if (options.gutters[i] == "CodeMirror-linenumbers") {
311
        if (options.lineNumbers) found = true;
312
        else options.gutters.splice(i--, 1);
313
      }
314
    }
315
    if (!found && options.lineNumbers)
316
      options.gutters.push("CodeMirror-linenumbers");
317
  }
318
319
  // SCROLLBARS
320
321
  // Re-synchronize the fake scrollbars with the actual size of the
322
  // content. Optionally force a scrollTop.
323
  function updateScrollbars(cm) {
324
    var d = cm.display, docHeight = cm.doc.height;
325
    var totalHeight = docHeight + paddingVert(d);
326
    d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px";
327
    d.gutters.style.height = Math.max(totalHeight, d.scroller.clientHeight - scrollerCutOff) + "px";
328
    var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight);
329
    var needsH = d.scroller.scrollWidth > (d.scroller.clientWidth + 1);
330
    var needsV = scrollHeight > (d.scroller.clientHeight + 1);
331
    if (needsV) {
332
      d.scrollbarV.style.display = "block";
333
      d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0";
334
      d.scrollbarV.firstChild.style.height =
335
        (scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px";
336
    } else d.scrollbarV.style.display = "";
337
    if (needsH) {
338
      d.scrollbarH.style.display = "block";
339
      d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0";
340
      d.scrollbarH.firstChild.style.width =
341
        (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px";
342
    } else d.scrollbarH.style.display = "";
343
    if (needsH && needsV) {
344
      d.scrollbarFiller.style.display = "block";
345
      d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px";
346
    } else d.scrollbarFiller.style.display = "";
347
    if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
348
      d.gutterFiller.style.display = "block";
349
      d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px";
350
      d.gutterFiller.style.width = d.gutters.offsetWidth + "px";
351
    } else d.gutterFiller.style.display = "";
352
353
    if (mac_geLion && scrollbarWidth(d.measure) === 0)
354
      d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px";
355
  }
356
357
  function visibleLines(display, doc, viewPort) {
358
    var top = display.scroller.scrollTop, height = display.wrapper.clientHeight;
359
    if (typeof viewPort == "number") top = viewPort;
360
    else if (viewPort) {top = viewPort.top; height = viewPort.bottom - viewPort.top;}
361
    top = Math.floor(top - paddingTop(display));
362
    var bottom = Math.ceil(top + height);
363
    return {from: lineAtHeight(doc, top), to: lineAtHeight(doc, bottom)};
364
  }
365
366
  // LINE NUMBERS
367
368
  function alignHorizontally(cm) {
369
    var display = cm.display;
370
    if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
371
    var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
372
    var gutterW = display.gutters.offsetWidth, l = comp + "px";
373
    for (var n = display.lineDiv.firstChild; n; n = n.nextSibling) if (n.alignable) {
374
      for (var i = 0, a = n.alignable; i < a.length; ++i) a[i].style.left = l;
375
    }
376
    if (cm.options.fixedGutter)
377
      display.gutters.style.left = (comp + gutterW) + "px";
378
  }
379
380
  function maybeUpdateLineNumberWidth(cm) {
381
    if (!cm.options.lineNumbers) return false;
382
    var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
383
    if (last.length != display.lineNumChars) {
384
      var test = display.measure.appendChild(elt("div", [elt("div", last)],
385
                                                 "CodeMirror-linenumber CodeMirror-gutter-elt"));
386
      var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
387
      display.lineGutter.style.width = "";
388
      display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);
389
      display.lineNumWidth = display.lineNumInnerWidth + padding;
390
      display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
391
      display.lineGutter.style.width = display.lineNumWidth + "px";
392
      return true;
393
    }
394
    return false;
395
  }
396
397
  function lineNumberFor(options, i) {
398
    return String(options.lineNumberFormatter(i + options.firstLineNumber));
399
  }
400
  function compensateForHScroll(display) {
401
    return getRect(display.scroller).left - getRect(display.sizer).left;
402
  }
403
404
  // DISPLAY DRAWING
405
406
  function updateDisplay(cm, changes, viewPort) {
407
    var oldFrom = cm.display.showingFrom, oldTo = cm.display.showingTo, updated;
408
    var visible = visibleLines(cm.display, cm.doc, viewPort);
409
    for (;;) {
410
      if (!updateDisplayInner(cm, changes, visible)) break;
411
      updated = true;
412
      updateSelection(cm);
413
      updateScrollbars(cm);
414
415
      // Clip forced viewport to actual scrollable area
416
      if (viewPort)
417
        viewPort = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight,
418
                            typeof viewPort == "number" ? viewPort : viewPort.top);
419
      visible = visibleLines(cm.display, cm.doc, viewPort);
420
      if (visible.from >= cm.display.showingFrom && visible.to <= cm.display.showingTo)
421
        break;
422
      changes = [];
423
    }
424
425
    if (updated) {
426
      signalLater(cm, "update", cm);
427
      if (cm.display.showingFrom != oldFrom || cm.display.showingTo != oldTo)
428
        signalLater(cm, "viewportChange", cm, cm.display.showingFrom, cm.display.showingTo);
429
    }
430
    return updated;
431
  }
432
433
  // Uses a set of changes plus the current scroll position to
434
  // determine which DOM updates have to be made, and makes the
435
  // updates.
436
  function updateDisplayInner(cm, changes, visible) {
437
    var display = cm.display, doc = cm.doc;
438
    if (!display.wrapper.clientWidth) {
439
      display.showingFrom = display.showingTo = doc.first;
440
      display.viewOffset = 0;
441
      return;
442
    }
443
444
    // Bail out if the visible area is already rendered and nothing changed.
445
    if (changes.length == 0 &&
446
        visible.from > display.showingFrom && visible.to < display.showingTo)
447
      return;
448
449
    if (maybeUpdateLineNumberWidth(cm))
450
      changes = [{from: doc.first, to: doc.first + doc.size}];
451
    var gutterW = display.sizer.style.marginLeft = display.gutters.offsetWidth + "px";
452
    display.scrollbarH.style.left = cm.options.fixedGutter ? gutterW : "0";
453
454
    // Used to determine which lines need their line numbers updated
455
    var positionsChangedFrom = Infinity;
456
    if (cm.options.lineNumbers)
457
      for (var i = 0; i < changes.length; ++i)
458
        if (changes[i].diff) { positionsChangedFrom = changes[i].from; break; }
459
460
    var end = doc.first + doc.size;
461
    var from = Math.max(visible.from - cm.options.viewportMargin, doc.first);
462
    var to = Math.min(end, visible.to + cm.options.viewportMargin);
463
    if (display.showingFrom < from && from - display.showingFrom < 20) from = Math.max(doc.first, display.showingFrom);
464
    if (display.showingTo > to && display.showingTo - to < 20) to = Math.min(end, display.showingTo);
465
    if (sawCollapsedSpans) {
466
      from = lineNo(visualLine(doc, getLine(doc, from)));
467
      while (to < end && lineIsHidden(doc, getLine(doc, to))) ++to;
468
    }
469
470
    // Create a range of theoretically intact lines, and punch holes
471
    // in that using the change info.
472
    var intact = [{from: Math.max(display.showingFrom, doc.first),
473
                   to: Math.min(display.showingTo, end)}];
474
    if (intact[0].from >= intact[0].to) intact = [];
475
    else intact = computeIntact(intact, changes);
476
    // When merged lines are present, we might have to reduce the
477
    // intact ranges because changes in continued fragments of the
478
    // intact lines do require the lines to be redrawn.
479
    if (sawCollapsedSpans)
480
      for (var i = 0; i < intact.length; ++i) {
481
        var range = intact[i], merged;
482
        while (merged = collapsedSpanAtEnd(getLine(doc, range.to - 1))) {
483
          var newTo = merged.find().from.line;
484
          if (newTo > range.from) range.to = newTo;
485
          else { intact.splice(i--, 1); break; }
486
        }
487
      }
488
489
    // Clip off the parts that won't be visible
490
    var intactLines = 0;
491
    for (var i = 0; i < intact.length; ++i) {
492
      var range = intact[i];
493
      if (range.from < from) range.from = from;
494
      if (range.to > to) range.to = to;
495
      if (range.from >= range.to) intact.splice(i--, 1);
496
      else intactLines += range.to - range.from;
497
    }
498
    if (intactLines == to - from && from == display.showingFrom && to == display.showingTo) {
499
      updateViewOffset(cm);
500
      return;
501
    }
502
    intact.sort(function(a, b) {return a.from - b.from;});
503
504
    // Avoid crashing on IE's "unspecified error" when in iframes
505
    try {
506
      var focused = document.activeElement;
507
    } catch(e) {}
508
    if (intactLines < (to - from) * .7) display.lineDiv.style.display = "none";
509
    patchDisplay(cm, from, to, intact, positionsChangedFrom);
510
    display.lineDiv.style.display = "";
511
    if (focused && document.activeElement != focused && focused.offsetHeight) focused.focus();
512
513
    var different = from != display.showingFrom || to != display.showingTo ||
514
      display.lastSizeC != display.wrapper.clientHeight;
515
    // This is just a bogus formula that detects when the editor is
516
    // resized or the font size changes.
517
    if (different) {
518
      display.lastSizeC = display.wrapper.clientHeight;
519
      startWorker(cm, 400);
520
    }
521
    display.showingFrom = from; display.showingTo = to;
522
523
    var prevBottom = display.lineDiv.offsetTop;
524
    for (var node = display.lineDiv.firstChild, height; node; node = node.nextSibling) if (node.lineObj) {
525
      if (ie_lt8) {
526
        var bot = node.offsetTop + node.offsetHeight;
527
        height = bot - prevBottom;
528
        prevBottom = bot;
529
      } else {
530
        var box = getRect(node);
531
        height = box.bottom - box.top;
532
      }
533
      var diff = node.lineObj.height - height;
534
      if (height < 2) height = textHeight(display);
535
      if (diff > .001 || diff < -.001) {
536
        updateLineHeight(node.lineObj, height);
537
        var widgets = node.lineObj.widgets;
538
        if (widgets) for (var i = 0; i < widgets.length; ++i)
539
          widgets[i].height = widgets[i].node.offsetHeight;
540
      }
541
    }
542
    updateViewOffset(cm);
543
544
    return true;
545
  }
546
547
  function updateViewOffset(cm) {
548
    var off = cm.display.viewOffset = heightAtLine(cm, getLine(cm.doc, cm.display.showingFrom));
549
    // Position the mover div to align with the current virtual scroll position
550
    cm.display.mover.style.top = off + "px";
551
  }
552
553
  function computeIntact(intact, changes) {
554
    for (var i = 0, l = changes.length || 0; i < l; ++i) {
555
      var change = changes[i], intact2 = [], diff = change.diff || 0;
556
      for (var j = 0, l2 = intact.length; j < l2; ++j) {
557
        var range = intact[j];
558
        if (change.to <= range.from && change.diff) {
559
          intact2.push({from: range.from + diff, to: range.to + diff});
560
        } else if (change.to <= range.from || change.from >= range.to) {
561
          intact2.push(range);
562
        } else {
563
          if (change.from > range.from)
564
            intact2.push({from: range.from, to: change.from});
565
          if (change.to < range.to)
566
            intact2.push({from: change.to + diff, to: range.to + diff});
567
        }
568
      }
569
      intact = intact2;
570
    }
571
    return intact;
572
  }
573
574
  function getDimensions(cm) {
575
    var d = cm.display, left = {}, width = {};
576
    for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
577
      left[cm.options.gutters[i]] = n.offsetLeft;
578
      width[cm.options.gutters[i]] = n.offsetWidth;
579
    }
580
    return {fixedPos: compensateForHScroll(d),
581
            gutterTotalWidth: d.gutters.offsetWidth,
582
            gutterLeft: left,
583
            gutterWidth: width,
584
            wrapperWidth: d.wrapper.clientWidth};
585
  }
586
587
  function patchDisplay(cm, from, to, intact, updateNumbersFrom) {
588
    var dims = getDimensions(cm);
589
    var display = cm.display, lineNumbers = cm.options.lineNumbers;
590
    if (!intact.length && (!webkit || !cm.display.currentWheelTarget))
591
      removeChildren(display.lineDiv);
592
    var container = display.lineDiv, cur = container.firstChild;
593
594
    function rm(node) {
595
      var next = node.nextSibling;
596
      if (webkit && mac && cm.display.currentWheelTarget == node) {
597
        node.style.display = "none";
598
        node.lineObj = null;
599
      } else {
600
        node.parentNode.removeChild(node);
601
      }
602
      return next;
603
    }
604
605
    var nextIntact = intact.shift(), lineN = from;
606
    cm.doc.iter(from, to, function(line) {
607
      if (nextIntact && nextIntact.to == lineN) nextIntact = intact.shift();
608
      if (lineIsHidden(cm.doc, line)) {
609
        if (line.height != 0) updateLineHeight(line, 0);
610
        if (line.widgets && cur.previousSibling) for (var i = 0; i < line.widgets.length; ++i) {
611
          var w = line.widgets[i];
612
          if (w.showIfHidden) {
613
            var prev = cur.previousSibling;
614
            if (/pre/i.test(prev.nodeName)) {
615
              var wrap = elt("div", null, null, "position: relative");
616
              prev.parentNode.replaceChild(wrap, prev);
617
              wrap.appendChild(prev);
618
              prev = wrap;
619
            }
620
            var wnode = prev.appendChild(elt("div", [w.node], "CodeMirror-linewidget"));
621
            if (!w.handleMouseEvents) wnode.ignoreEvents = true;
622
            positionLineWidget(w, wnode, prev, dims);
623
          }
624
        }
625
      } else if (nextIntact && nextIntact.from <= lineN && nextIntact.to > lineN) {
626
        // This line is intact. Skip to the actual node. Update its
627
        // line number if needed.
628
        while (cur.lineObj != line) cur = rm(cur);
629
        if (lineNumbers && updateNumbersFrom <= lineN && cur.lineNumber)
630
          setTextContent(cur.lineNumber, lineNumberFor(cm.options, lineN));
631
        cur = cur.nextSibling;
632
      } else {
633
        // For lines with widgets, make an attempt to find and reuse
634
        // the existing element, so that widgets aren't needlessly
635
        // removed and re-inserted into the dom
636
        if (line.widgets) for (var j = 0, search = cur, reuse; search && j < 20; ++j, search = search.nextSibling)
637
          if (search.lineObj == line && /div/i.test(search.nodeName)) { reuse = search; break; }
638
        // This line needs to be generated.
639
        var lineNode = buildLineElement(cm, line, lineN, dims, reuse);
640
        if (lineNode != reuse) {
641
          container.insertBefore(lineNode, cur);
642
        } else {
643
          while (cur != reuse) cur = rm(cur);
644
          cur = cur.nextSibling;
645
        }
646
647
        lineNode.lineObj = line;
648
      }
649
      ++lineN;
650
    });
651
    while (cur) cur = rm(cur);
652
  }
653
654
  function buildLineElement(cm, line, lineNo, dims, reuse) {
655
    var lineElement = lineContent(cm, line);
656
    var markers = line.gutterMarkers, display = cm.display, wrap;
657
658
    if (!cm.options.lineNumbers && !markers && !line.bgClass && !line.wrapClass && !line.widgets)
659
      return lineElement;
660
661
    // Lines with gutter elements, widgets or a background class need
662
    // to be wrapped again, and have the extra elements added to the
663
    // wrapper div
664
665
    if (reuse) {
666
      reuse.alignable = null;
667
      var isOk = true, widgetsSeen = 0, insertBefore = null;
668
      for (var n = reuse.firstChild, next; n; n = next) {
669
        next = n.nextSibling;
670
        if (!/\bCodeMirror-linewidget\b/.test(n.className)) {
671
          reuse.removeChild(n);
672
        } else {
673
          for (var i = 0, first = true; i < line.widgets.length; ++i) {
674
            var widget = line.widgets[i];
675
            if (!widget.above) { insertBefore = n; first = false; }
676
            if (widget.node == n.firstChild) {
677
              positionLineWidget(widget, n, reuse, dims);
678
              ++widgetsSeen;
679
              break;
680
            }
681
          }
682
          if (i == line.widgets.length) { isOk = false; break; }
683
        }
684
      }
685
      reuse.insertBefore(lineElement, insertBefore);
686
      if (isOk && widgetsSeen == line.widgets.length) {
687
        wrap = reuse;
688
        reuse.className = line.wrapClass || "";
689
      }
690
    }
691
    if (!wrap) {
692
      wrap = elt("div", null, line.wrapClass, "position: relative");
693
      wrap.appendChild(lineElement);
694
    }
695
    // Kludge to make sure the styled element lies behind the selection (by z-index)
696
    if (line.bgClass)
697
      wrap.insertBefore(elt("div", null, line.bgClass + " CodeMirror-linebackground"), wrap.firstChild);
698
    if (cm.options.lineNumbers || markers) {
699
      var gutterWrap = wrap.insertBefore(elt("div", null, null, "position: absolute; left: " +
700
                                             (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"),
701
                                         wrap.firstChild);
702
      if (cm.options.fixedGutter) (wrap.alignable || (wrap.alignable = [])).push(gutterWrap);
703
      if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
704
        wrap.lineNumber = gutterWrap.appendChild(
705
          elt("div", lineNumberFor(cm.options, lineNo),
706
              "CodeMirror-linenumber CodeMirror-gutter-elt",
707
              "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
708
              + display.lineNumInnerWidth + "px"));
709
      if (markers)
710
        for (var k = 0; k < cm.options.gutters.length; ++k) {
711
          var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
712
          if (found)
713
            gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
714
                                       dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
715
        }
716
    }
717
    if (ie_lt8) wrap.style.zIndex = 2;
718
    if (line.widgets && wrap != reuse) for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
719
      var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
720
      if (!widget.handleMouseEvents) node.ignoreEvents = true;
721
      positionLineWidget(widget, node, wrap, dims);
722
      if (widget.above)
723
        wrap.insertBefore(node, cm.options.lineNumbers && line.height != 0 ? gutterWrap : lineElement);
724
      else
725
        wrap.appendChild(node);
726
      signalLater(widget, "redraw");
727
    }
728
    return wrap;
729
  }
730
731
  function positionLineWidget(widget, node, wrap, dims) {
732
    if (widget.noHScroll) {
733
      (wrap.alignable || (wrap.alignable = [])).push(node);
734
      var width = dims.wrapperWidth;
735
      node.style.left = dims.fixedPos + "px";
736
      if (!widget.coverGutter) {
737
        width -= dims.gutterTotalWidth;
738
        node.style.paddingLeft = dims.gutterTotalWidth + "px";
739
      }
740
      node.style.width = width + "px";
741
    }
742
    if (widget.coverGutter) {
743
      node.style.zIndex = 5;
744
      node.style.position = "relative";
745
      if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
746
    }
747
  }
748
749
  // SELECTION / CURSOR
750
751
  function updateSelection(cm) {
752
    var display = cm.display;
753
    var collapsed = posEq(cm.doc.sel.from, cm.doc.sel.to);
754
    if (collapsed || cm.options.showCursorWhenSelecting)
755
      updateSelectionCursor(cm);
756
    else
757
      display.cursor.style.display = display.otherCursor.style.display = "none";
758
    if (!collapsed)
759
      updateSelectionRange(cm);
760
    else
761
      display.selectionDiv.style.display = "none";
762
763
    // Move the hidden textarea near the cursor to prevent scrolling artifacts
764
    if (cm.options.moveInputWithCursor) {
765
      var headPos = cursorCoords(cm, cm.doc.sel.head, "div");
766
      var wrapOff = getRect(display.wrapper), lineOff = getRect(display.lineDiv);
767
      display.inputDiv.style.top = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
768
                                                        headPos.top + lineOff.top - wrapOff.top)) + "px";
769
      display.inputDiv.style.left = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
770
                                                         headPos.left + lineOff.left - wrapOff.left)) + "px";
771
    }
772
  }
773
774
  // No selection, plain cursor
775
  function updateSelectionCursor(cm) {
776
    var display = cm.display, pos = cursorCoords(cm, cm.doc.sel.head, "div");
777
    display.cursor.style.left = pos.left + "px";
778
    display.cursor.style.top = pos.top + "px";
779
    display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
780
    display.cursor.style.display = "";
781
782
    if (pos.other) {
783
      display.otherCursor.style.display = "";
784
      display.otherCursor.style.left = pos.other.left + "px";
785
      display.otherCursor.style.top = pos.other.top + "px";
786
      display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
787
    } else { display.otherCursor.style.display = "none"; }
788
  }
789
790
  // Highlight selection
791
  function updateSelectionRange(cm) {
792
    var display = cm.display, doc = cm.doc, sel = cm.doc.sel;
793
    var fragment = document.createDocumentFragment();
794
    var clientWidth = display.lineSpace.offsetWidth, pl = paddingLeft(cm.display);
795
796
    function add(left, top, width, bottom) {
797
      if (top < 0) top = 0;
798
      fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
799
                               "px; top: " + top + "px; width: " + (width == null ? clientWidth - left : width) +
800
                               "px; height: " + (bottom - top) + "px"));
801
    }
802
803
    function drawForLine(line, fromArg, toArg) {
804
      var lineObj = getLine(doc, line);
805
      var lineLen = lineObj.text.length;
806
      var start, end;
807
      function coords(ch, bias) {
808
        return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
809
      }
810
811
      iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
812
        var leftPos = coords(from, "left"), rightPos, left, right;
813
        if (from == to) {
814
          rightPos = leftPos;
815
          left = right = leftPos.left;
816
        } else {
817
          rightPos = coords(to - 1, "right");
818
          if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
819
          left = leftPos.left;
820
          right = rightPos.right;
821
        }
822
        if (fromArg == null && from == 0) left = pl;
823
        if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
824
          add(left, leftPos.top, null, leftPos.bottom);
825
          left = pl;
826
          if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
827
        }
828
        if (toArg == null && to == lineLen) right = clientWidth;
829
        if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
830
          start = leftPos;
831
        if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
832
          end = rightPos;
833
        if (left < pl + 1) left = pl;
834
        add(left, rightPos.top, right - left, rightPos.bottom);
835
      });
836
      return {start: start, end: end};
837
    }
838
839
    if (sel.from.line == sel.to.line) {
840
      drawForLine(sel.from.line, sel.from.ch, sel.to.ch);
841
    } else {
842
      var fromLine = getLine(doc, sel.from.line), toLine = getLine(doc, sel.to.line);
843
      var singleVLine = visualLine(doc, fromLine) == visualLine(doc, toLine);
844
      var leftEnd = drawForLine(sel.from.line, sel.from.ch, singleVLine ? fromLine.text.length : null).end;
845
      var rightStart = drawForLine(sel.to.line, singleVLine ? 0 : null, sel.to.ch).start;
846
      if (singleVLine) {
847
        if (leftEnd.top < rightStart.top - 2) {
848
          add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
849
          add(pl, rightStart.top, rightStart.left, rightStart.bottom);
850
        } else {
851
          add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
852
        }
853
      }
854
      if (leftEnd.bottom < rightStart.top)
855
        add(pl, leftEnd.bottom, null, rightStart.top);
856
    }
857
858
    removeChildrenAndAdd(display.selectionDiv, fragment);
859
    display.selectionDiv.style.display = "";
860
  }
861
862
  // Cursor-blinking
863
  function restartBlink(cm) {
864
    if (!cm.state.focused) return;
865
    var display = cm.display;
866
    clearInterval(display.blinker);
867
    var on = true;
868
    display.cursor.style.visibility = display.otherCursor.style.visibility = "";
869
    display.blinker = setInterval(function() {
870
      display.cursor.style.visibility = display.otherCursor.style.visibility = (on = !on) ? "" : "hidden";
871
    }, cm.options.cursorBlinkRate);
872
  }
873
874
  // HIGHLIGHT WORKER
875
876
  function startWorker(cm, time) {
877
    if (cm.doc.mode.startState && cm.doc.frontier < cm.display.showingTo)
878
      cm.state.highlight.set(time, bind(highlightWorker, cm));
879
  }
880
881
  function highlightWorker(cm) {
882
    var doc = cm.doc;
883
    if (doc.frontier < doc.first) doc.frontier = doc.first;
884
    if (doc.frontier >= cm.display.showingTo) return;
885
    var end = +new Date + cm.options.workTime;
886
    var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
887
    var changed = [], prevChange;
888
    doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.showingTo + 500), function(line) {
889
      if (doc.frontier >= cm.display.showingFrom) { // Visible
890
        var oldStyles = line.styles;
891
        line.styles = highlightLine(cm, line, state);
892
        var ischange = !oldStyles || oldStyles.length != line.styles.length;
893
        for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
894
        if (ischange) {
895
          if (prevChange && prevChange.end == doc.frontier) prevChange.end++;
896
          else changed.push(prevChange = {start: doc.frontier, end: doc.frontier + 1});
897
        }
898
        line.stateAfter = copyState(doc.mode, state);
899
      } else {
900
        processLine(cm, line, state);
901
        line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
902
      }
903
      ++doc.frontier;
904
      if (+new Date > end) {
905
        startWorker(cm, cm.options.workDelay);
906
        return true;
907
      }
908
    });
909
    if (changed.length)
910
      operation(cm, function() {
911
        for (var i = 0; i < changed.length; ++i)
912
          regChange(this, changed[i].start, changed[i].end);
913
      })();
914
  }
915
916
  // Finds the line to start with when starting a parse. Tries to
917
  // find a line with a stateAfter, so that it can start with a
918
  // valid state. If that fails, it returns the line with the
919
  // smallest indentation, which tends to need the least context to
920
  // parse correctly.
921
  function findStartLine(cm, n, precise) {
922
    var minindent, minline, doc = cm.doc;
923
    for (var search = n, lim = n - 100; search > lim; --search) {
924
      if (search <= doc.first) return doc.first;
925
      var line = getLine(doc, search - 1);
926
      if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
927
      var indented = countColumn(line.text, null, cm.options.tabSize);
928
      if (minline == null || minindent > indented) {
929
        minline = search - 1;
930
        minindent = indented;
931
      }
932
    }
933
    return minline;
934
  }
935
936
  function getStateBefore(cm, n, precise) {
937
    var doc = cm.doc, display = cm.display;
938
      if (!doc.mode.startState) return true;
939
    var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
940
    if (!state) state = startState(doc.mode);
941
    else state = copyState(doc.mode, state);
942
    doc.iter(pos, n, function(line) {
943
      processLine(cm, line, state);
944
      var save = pos == n - 1 || pos % 5 == 0 || pos >= display.showingFrom && pos < display.showingTo;
945
      line.stateAfter = save ? copyState(doc.mode, state) : null;
946
      ++pos;
947
    });
948
    return state;
949
  }
950
951
  // POSITION MEASUREMENT
952
953
  function paddingTop(display) {return display.lineSpace.offsetTop;}
954
  function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
955
  function paddingLeft(display) {
956
    var e = removeChildrenAndAdd(display.measure, elt("pre", null, null, "text-align: left")).appendChild(elt("span", "x"));
957
    return e.offsetLeft;
958
  }
959
960
  function measureChar(cm, line, ch, data, bias) {
961
    var dir = -1;
962
    data = data || measureLine(cm, line);
963
964
    for (var pos = ch;; pos += dir) {
965
      var r = data[pos];
966
      if (r) break;
967
      if (dir < 0 && pos == 0) dir = 1;
968
    }
969
    var rightV = (pos < ch || bias == "right") && r.topRight != null;
970
    return {left: pos < ch ? r.right : r.left,
971
            right: pos > ch ? r.left : r.right,
972
            top: rightV ? r.topRight : r.top,
973
            bottom: rightV ? r.bottomRight : r.bottom};
974
  }
975
976
  function findCachedMeasurement(cm, line) {
977
    var cache = cm.display.measureLineCache;
978
    for (var i = 0; i < cache.length; ++i) {
979
      var memo = cache[i];
980
      if (memo.text == line.text && memo.markedSpans == line.markedSpans &&
981
          cm.display.scroller.clientWidth == memo.width &&
982
          memo.classes == line.textClass + "|" + line.bgClass + "|" + line.wrapClass)
983
        return memo;
984
    }
985
  }
986
987
  function clearCachedMeasurement(cm, line) {
988
    var exists = findCachedMeasurement(cm, line);
989
    if (exists) exists.text = exists.measure = exists.markedSpans = null;
990
  }
991
992
  function measureLine(cm, line) {
993
    // First look in the cache
994
    var cached = findCachedMeasurement(cm, line);
995
    if (cached) return cached.measure;
996
997
    // Failing that, recompute and store result in cache
998
    var measure = measureLineInner(cm, line);
999
    var cache = cm.display.measureLineCache;
1000
    var memo = {text: line.text, width: cm.display.scroller.clientWidth,
1001
                markedSpans: line.markedSpans, measure: measure,
1002
                classes: line.textClass + "|" + line.bgClass + "|" + line.wrapClass};
1003
    if (cache.length == 16) cache[++cm.display.measureLineCachePos % 16] = memo;
1004
    else cache.push(memo);
1005
    return measure;
1006
  }
1007
1008
  function measureLineInner(cm, line) {
1009
    var display = cm.display, measure = emptyArray(line.text.length);
1010
    var pre = lineContent(cm, line, measure);
1011
1012
    // IE does not cache element positions of inline elements between
1013
    // calls to getBoundingClientRect. This makes the loop below,
1014
    // which gathers the positions of all the characters on the line,
1015
    // do an amount of layout work quadratic to the number of
1016
    // characters. When line wrapping is off, we try to improve things
1017
    // by first subdividing the line into a bunch of inline blocks, so
1018
    // that IE can reuse most of the layout information from caches
1019
    // for those blocks. This does interfere with line wrapping, so it
1020
    // doesn't work when wrapping is on, but in that case the
1021
    // situation is slightly better, since IE does cache line-wrapping
1022
    // information and only recomputes per-line.
1023
    if (ie && !ie_lt8 && !cm.options.lineWrapping && pre.childNodes.length > 100) {
1024
      var fragment = document.createDocumentFragment();
1025
      var chunk = 10, n = pre.childNodes.length;
1026
      for (var i = 0, chunks = Math.ceil(n / chunk); i < chunks; ++i) {
1027
        var wrap = elt("div", null, null, "display: inline-block");
1028
        for (var j = 0; j < chunk && n; ++j) {
1029
          wrap.appendChild(pre.firstChild);
1030
          --n;
1031
        }
1032
        fragment.appendChild(wrap);
1033
      }
1034
      pre.appendChild(fragment);
1035
    }
1036
1037
    removeChildrenAndAdd(display.measure, pre);
1038
1039
    var outer = getRect(display.lineDiv);
1040
    var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHeight;
1041
    // Work around an IE7/8 bug where it will sometimes have randomly
1042
    // replaced our pre with a clone at this point.
1043
    if (ie_lt9 && display.measure.first != pre)
1044
      removeChildrenAndAdd(display.measure, pre);
1045
1046
    function categorizeVSpan(top, bot) {
1047
      if (bot > maxBot) bot = maxBot;
1048
      if (top < 0) top = 0;
1049
      for (var j = 0; j < vranges.length; j += 2) {
1050
        var rtop = vranges[j], rbot = vranges[j+1];
1051
        if (rtop > bot || rbot < top) continue;
1052
        if (rtop <= top && rbot >= bot ||
1053
            top <= rtop && bot >= rbot ||
1054
            Math.min(bot, rbot) - Math.max(top, rtop) >= (bot - top) >> 1) {
1055
          vranges[j] = Math.min(top, rtop);
1056
          vranges[j+1] = Math.max(bot, rbot);
1057
          return j;
1058
        }
1059
      }
1060
      vranges.push(top, bot);
1061
      return j;
1062
    }
1063
1064
    for (var i = 0, cur; i < measure.length; ++i) if (cur = measure[i]) {
1065
      var size, node = cur;
1066
      // A widget might wrap, needs special care
1067
      if (/\bCodeMirror-widget\b/.test(cur.className) && cur.getClientRects) {
1068
        if (cur.firstChild.nodeType == 1) node = cur.firstChild;
1069
        var rects = node.getClientRects(), rLeft = rects[0], rRight = rects[rects.length - 1];
1070
        if (rects.length > 1) {
1071
          var vCatLeft = categorizeVSpan(rLeft.top - outer.top, rLeft.bottom - outer.top);
1072
          var vCatRight = categorizeVSpan(rRight.top - outer.top, rRight.bottom - outer.top);
1073
          data[i] = {left: rLeft.left - outer.left, right: rRight.right - outer.left,
1074
                     top: vCatLeft, topRight: vCatRight};
1075
          continue;
1076
        }
1077
      }
1078
      size = getRect(node);
1079
      var vCat = categorizeVSpan(size.top - outer.top, size.bottom - outer.top);
1080
      var right = size.right;
1081
      if (cur.measureRight) right = getRect(cur.measureRight).left;
1082
      data[i] = {left: size.left - outer.left, right: right - outer.left, top: vCat};
1083
    }
1084
    for (var i = 0, cur; i < data.length; ++i) if (cur = data[i]) {
1085
      var vr = cur.top, vrRight = cur.topRight;
1086
      cur.top = vranges[vr]; cur.bottom = vranges[vr+1];
1087
      if (vrRight != null) { cur.topRight = vranges[vrRight]; cur.bottomRight = vranges[vrRight+1]; }
1088
    }
1089
    return data;
1090
  }
1091
1092
  function measureLineWidth(cm, line) {
1093
    var hasBadSpan = false;
1094
    if (line.markedSpans) for (var i = 0; i < line.markedSpans; ++i) {
1095
      var sp = line.markedSpans[i];
1096
      if (sp.collapsed && (sp.to == null || sp.to == line.text.length)) hasBadSpan = true;
1097
    }
1098
    var cached = !hasBadSpan && findCachedMeasurement(cm, line);
1099
    if (cached) return measureChar(cm, line, line.text.length, cached.measure, "right").right;
1100
1101
    var pre = lineContent(cm, line);
1102
    var end = pre.appendChild(zeroWidthElement(cm.display.measure));
1103
    removeChildrenAndAdd(cm.display.measure, pre);
1104
    return getRect(end).right - getRect(cm.display.lineDiv).left;
1105
  }
1106
1107
  function clearCaches(cm) {
1108
    cm.display.measureLineCache.length = cm.display.measureLineCachePos = 0;
1109
    cm.display.cachedCharWidth = cm.display.cachedTextHeight = null;
1110
    if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
1111
    cm.display.lineNumChars = null;
1112
  }
1113
1114
  function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
1115
  function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
1116
1117
  // Context is one of "line", "div" (display.lineDiv), "local"/null (editor), or "page"
1118
  function intoCoordSystem(cm, lineObj, rect, context) {
1119
    if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
1120
      var size = widgetHeight(lineObj.widgets[i]);
1121
      rect.top += size; rect.bottom += size;
1122
    }
1123
    if (context == "line") return rect;
1124
    if (!context) context = "local";
1125
    var yOff = heightAtLine(cm, lineObj);
1126
    if (context == "local") yOff += paddingTop(cm.display);
1127
    else yOff -= cm.display.viewOffset;
1128
    if (context == "page" || context == "window") {
1129
      var lOff = getRect(cm.display.lineSpace);
1130
      yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
1131
      var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
1132
      rect.left += xOff; rect.right += xOff;
1133
    }
1134
    rect.top += yOff; rect.bottom += yOff;
1135
    return rect;
1136
  }
1137
1138
  // Context may be "window", "page", "div", or "local"/null
1139
  // Result is in "div" coords
1140
  function fromCoordSystem(cm, coords, context) {
1141
    if (context == "div") return coords;
1142
    var left = coords.left, top = coords.top;
1143
    // First move into "page" coordinate system
1144
    if (context == "page") {
1145
      left -= pageScrollX();
1146
      top -= pageScrollY();
1147
    } else if (context == "local" || !context) {
1148
      var localBox = getRect(cm.display.sizer);
1149
      left += localBox.left;
1150
      top += localBox.top;
1151
    }
1152
1153
    var lineSpaceBox = getRect(cm.display.lineSpace);
1154
    return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
1155
  }
1156
1157
  function charCoords(cm, pos, context, lineObj, bias) {
1158
    if (!lineObj) lineObj = getLine(cm.doc, pos.line);
1159
    return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, null, bias), context);
1160
  }
1161
1162
  function cursorCoords(cm, pos, context, lineObj, measurement) {
1163
    lineObj = lineObj || getLine(cm.doc, pos.line);
1164
    if (!measurement) measurement = measureLine(cm, lineObj);
1165
    function get(ch, right) {
1166
      var m = measureChar(cm, lineObj, ch, measurement, right ? "right" : "left");
1167
      if (right) m.left = m.right; else m.right = m.left;
1168
      return intoCoordSystem(cm, lineObj, m, context);
1169
    }
1170
    function getBidi(ch, partPos) {
1171
      var part = order[partPos], right = part.level % 2;
1172
      if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
1173
        part = order[--partPos];
1174
        ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
1175
        right = true;
1176
      } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
1177
        part = order[++partPos];
1178
        ch = bidiLeft(part) - part.level % 2;
1179
        right = false;
1180
      }
1181
      if (right && ch == part.to && ch > part.from) return get(ch - 1);
1182
      return get(ch, right);
1183
    }
1184
    var order = getOrder(lineObj), ch = pos.ch;
1185
    if (!order) return get(ch);
1186
    var partPos = getBidiPartAt(order, ch);
1187
    var val = getBidi(ch, partPos);
1188
    if (bidiOther != null) val.other = getBidi(ch, bidiOther);
1189
    return val;
1190
  }
1191
1192
  function PosWithInfo(line, ch, outside, xRel) {
1193
    var pos = new Pos(line, ch);
1194
    pos.xRel = xRel;
1195
    if (outside) pos.outside = true;
1196
    return pos;
1197
  }
1198
1199
  // Coords must be lineSpace-local
1200
  function coordsChar(cm, x, y) {
1201
    var doc = cm.doc;
1202
    y += cm.display.viewOffset;
1203
    if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
1204
    var lineNo = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
1205
    if (lineNo > last)
1206
      return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
1207
    if (x < 0) x = 0;
1208
1209
    for (;;) {
1210
      var lineObj = getLine(doc, lineNo);
1211
      var found = coordsCharInner(cm, lineObj, lineNo, x, y);
1212
      var merged = collapsedSpanAtEnd(lineObj);
1213
      var mergedPos = merged && merged.find();
1214
      if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
1215
        lineNo = mergedPos.to.line;
1216
      else
1217
        return found;
1218
    }
1219
  }
1220
1221
  function coordsCharInner(cm, lineObj, lineNo, x, y) {
1222
    var innerOff = y - heightAtLine(cm, lineObj);
1223
    var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
1224
    var measurement = measureLine(cm, lineObj);
1225
1226
    function getX(ch) {
1227
      var sp = cursorCoords(cm, Pos(lineNo, ch), "line",
1228
                            lineObj, measurement);
1229
      wrongLine = true;
1230
      if (innerOff > sp.bottom) return sp.left - adjust;
1231
      else if (innerOff < sp.top) return sp.left + adjust;
1232
      else wrongLine = false;
1233
      return sp.left;
1234
    }
1235
1236
    var bidi = getOrder(lineObj), dist = lineObj.text.length;
1237
    var from = lineLeft(lineObj), to = lineRight(lineObj);
1238
    var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
1239
1240
    if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
1241
    // Do a binary search between these bounds.
1242
    for (;;) {
1243
      if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
1244
        var ch = x < fromX || x - fromX <= toX - x ? from : to;
1245
        var xDiff = x - (ch == from ? fromX : toX);
1246
        while (isExtendingChar.test(lineObj.text.charAt(ch))) ++ch;
1247
        var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
1248
                              xDiff < 0 ? -1 : xDiff ? 1 : 0);
1249
        return pos;
1250
      }
1251
      var step = Math.ceil(dist / 2), middle = from + step;
1252
      if (bidi) {
1253
        middle = from;
1254
        for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
1255
      }
1256
      var middleX = getX(middle);
1257
      if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
1258
      else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
1259
    }
1260
  }
1261
1262
  var measureText;
1263
  function textHeight(display) {
1264
    if (display.cachedTextHeight != null) return display.cachedTextHeight;
1265
    if (measureText == null) {
1266
      measureText = elt("pre");
1267
      // Measure a bunch of lines, for browsers that compute
1268
      // fractional heights.
1269
      for (var i = 0; i < 49; ++i) {
1270
        measureText.appendChild(document.createTextNode("x"));
1271
        measureText.appendChild(elt("br"));
1272
      }
1273
      measureText.appendChild(document.createTextNode("x"));
1274
    }
1275
    removeChildrenAndAdd(display.measure, measureText);
1276
    var height = measureText.offsetHeight / 50;
1277
    if (height > 3) display.cachedTextHeight = height;
1278
    removeChildren(display.measure);
1279
    return height || 1;
1280
  }
1281
1282
  function charWidth(display) {
1283
    if (display.cachedCharWidth != null) return display.cachedCharWidth;
1284
    var anchor = elt("span", "x");
1285
    var pre = elt("pre", [anchor]);
1286
    removeChildrenAndAdd(display.measure, pre);
1287
    var width = anchor.offsetWidth;
1288
    if (width > 2) display.cachedCharWidth = width;
1289
    return width || 10;
1290
  }
1291
1292
  // OPERATIONS
1293
1294
  // Operations are used to wrap changes in such a way that each
1295
  // change won't have to update the cursor and display (which would
1296
  // be awkward, slow, and error-prone), but instead updates are
1297
  // batched and then all combined and executed at once.
1298
1299
  var nextOpId = 0;
1300
  function startOperation(cm) {
1301
    cm.curOp = {
1302
      // An array of ranges of lines that have to be updated. See
1303
      // updateDisplay.
1304
      changes: [],
1305
      updateInput: null,
1306
      userSelChange: null,
1307
      textChanged: null,
1308
      selectionChanged: false,
1309
      cursorActivity: false,
1310
      updateMaxLine: false,
1311
      updateScrollPos: false,
1312
      id: ++nextOpId
1313
    };
1314
    if (!delayedCallbackDepth++) delayedCallbacks = [];
1315
  }
1316
1317
  function endOperation(cm) {
1318
    var op = cm.curOp, doc = cm.doc, display = cm.display;
1319
    cm.curOp = null;
1320
1321
    if (op.updateMaxLine) computeMaxLength(cm);
1322
    if (display.maxLineChanged && !cm.options.lineWrapping && display.maxLine) {
1323
      var width = measureLineWidth(cm, display.maxLine);
1324
      display.sizer.style.minWidth = Math.max(0, width + 3 + scrollerCutOff) + "px";
1325
      display.maxLineChanged = false;
1326
      var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + display.sizer.offsetWidth - display.scroller.clientWidth);
1327
      if (maxScrollLeft < doc.scrollLeft && !op.updateScrollPos)
1328
        setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft), true);
1329
    }
1330
    var newScrollPos, updated;
1331
    if (op.updateScrollPos) {
1332
      newScrollPos = op.updateScrollPos;
1333
    } else if (op.selectionChanged && display.scroller.clientHeight) { // don't rescroll if not visible
1334
      var coords = cursorCoords(cm, doc.sel.head);
1335
      newScrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom);
1336
    }
1337
    if (op.changes.length || newScrollPos && newScrollPos.scrollTop != null) {
1338
      updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrollTop);
1339
      if (cm.display.scroller.offsetHeight) cm.doc.scrollTop = cm.display.scroller.scrollTop;
1340
    }
1341
    if (!updated && op.selectionChanged) updateSelection(cm);
1342
    if (op.updateScrollPos) {
1343
      display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = newScrollPos.scrollTop;
1344
      display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = newScrollPos.scrollLeft;
1345
      alignHorizontally(cm);
1346
      if (op.scrollToPos)
1347
        scrollPosIntoView(cm, clipPos(cm.doc, op.scrollToPos), op.scrollToPosMargin);
1348
    } else if (newScrollPos) {
1349
      scrollCursorIntoView(cm);
1350
    }
1351
    if (op.selectionChanged) restartBlink(cm);
1352
1353
    if (cm.state.focused && op.updateInput)
1354
      resetInput(cm, op.userSelChange);
1355
1356
    var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
1357
    if (hidden) for (var i = 0; i < hidden.length; ++i)
1358
      if (!hidden[i].lines.length) signal(hidden[i], "hide");
1359
    if (unhidden) for (var i = 0; i < unhidden.length; ++i)
1360
      if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
1361
1362
    var delayed;
1363
    if (!--delayedCallbackDepth) {
1364
      delayed = delayedCallbacks;
1365
      delayedCallbacks = null;
1366
    }
1367
    if (op.textChanged)
1368
      signal(cm, "change", cm, op.textChanged);
1369
    if (op.cursorActivity) signal(cm, "cursorActivity", cm);
1370
    if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i]();
1371
  }
1372
1373
  // Wraps a function in an operation. Returns the wrapped function.
1374
  function operation(cm1, f) {
1375
    return function() {
1376
      var cm = cm1 || this, withOp = !cm.curOp;
1377
      if (withOp) startOperation(cm);
1378
      try { var result = f.apply(cm, arguments); }
1379
      finally { if (withOp) endOperation(cm); }
1380
      return result;
1381
    };
1382
  }
1383
  function docOperation(f) {
1384
    return function() {
1385
      var withOp = this.cm && !this.cm.curOp, result;
1386
      if (withOp) startOperation(this.cm);
1387
      try { result = f.apply(this, arguments); }
1388
      finally { if (withOp) endOperation(this.cm); }
1389
      return result;
1390
    };
1391
  }
1392
  function runInOp(cm, f) {
1393
    var withOp = !cm.curOp, result;
1394
    if (withOp) startOperation(cm);
1395
    try { result = f(); }
1396
    finally { if (withOp) endOperation(cm); }
1397
    return result;
1398
  }
1399
1400
  function regChange(cm, from, to, lendiff) {
1401
    if (from == null) from = cm.doc.first;
1402
    if (to == null) to = cm.doc.first + cm.doc.size;
1403
    cm.curOp.changes.push({from: from, to: to, diff: lendiff});
1404
  }
1405
1406
  // INPUT HANDLING
1407
1408
  function slowPoll(cm) {
1409
    if (cm.display.pollingFast) return;
1410
    cm.display.poll.set(cm.options.pollInterval, function() {
1411
      readInput(cm);
1412
      if (cm.state.focused) slowPoll(cm);
1413
    });
1414
  }
1415
1416
  function fastPoll(cm) {
1417
    var missed = false;
1418
    cm.display.pollingFast = true;
1419
    function p() {
1420
      var changed = readInput(cm);
1421
      if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);}
1422
      else {cm.display.pollingFast = false; slowPoll(cm);}
1423
    }
1424
    cm.display.poll.set(20, p);
1425
  }
1426
1427
  // prevInput is a hack to work with IME. If we reset the textarea
1428
  // on every change, that breaks IME. So we look for changes
1429
  // compared to the previous content instead. (Modern browsers have
1430
  // events that indicate IME taking place, but these are not widely
1431
  // supported or compatible enough yet to rely on.)
1432
  function readInput(cm) {
1433
    var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc, sel = doc.sel;
1434
    if (!cm.state.focused || hasSelection(input) || isReadOnly(cm) || cm.state.disableInput) return false;
1435
    var text = input.value;
1436
    if (text == prevInput && posEq(sel.from, sel.to)) return false;
1437
    if (ie && !ie_lt9 && cm.display.inputHasSelection === text) {
1438
      resetInput(cm, true);
1439
      return false;
1440
    }
1441
1442
    var withOp = !cm.curOp;
1443
    if (withOp) startOperation(cm);
1444
    sel.shift = false;
1445
    var same = 0, l = Math.min(prevInput.length, text.length);
1446
    while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
1447
    var from = sel.from, to = sel.to;
1448
    if (same < prevInput.length)
1449
      from = Pos(from.line, from.ch - (prevInput.length - same));
1450
    else if (cm.state.overwrite && posEq(from, to) && !cm.state.pasteIncoming)
1451
      to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + (text.length - same)));
1452
1453
    var updateInput = cm.curOp.updateInput;
1454
    var changeEvent = {from: from, to: to, text: splitLines(text.slice(same)),
1455
                       origin: cm.state.pasteIncoming ? "paste" : "+input"};
1456
    makeChange(cm.doc, changeEvent, "end");
1457
    cm.curOp.updateInput = updateInput;
1458
    signalLater(cm, "inputRead", cm, changeEvent);
1459
1460
    if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.prevInput = "";
1461
    else cm.display.prevInput = text;
1462
    if (withOp) endOperation(cm);
1463
    cm.state.pasteIncoming = false;
1464
    return true;
1465
  }
1466
1467
  function resetInput(cm, user) {
1468
    var minimal, selected, doc = cm.doc;
1469
    if (!posEq(doc.sel.from, doc.sel.to)) {
1470
      cm.display.prevInput = "";
1471
      minimal = hasCopyEvent &&
1472
        (doc.sel.to.line - doc.sel.from.line > 100 || (selected = cm.getSelection()).length > 1000);
1473
      var content = minimal ? "-" : selected || cm.getSelection();
1474
      cm.display.input.value = content;
1475
      if (cm.state.focused) selectInput(cm.display.input);
1476
      if (ie && !ie_lt9) cm.display.inputHasSelection = content;
1477
    } else if (user) {
1478
      cm.display.prevInput = cm.display.input.value = "";
1479
      if (ie && !ie_lt9) cm.display.inputHasSelection = null;
1480
    }
1481
    cm.display.inaccurateSelection = minimal;
1482
  }
1483
1484
  function focusInput(cm) {
1485
    if (cm.options.readOnly != "nocursor" && (!mobile || document.activeElement != cm.display.input))
1486
      cm.display.input.focus();
1487
  }
1488
1489
  function isReadOnly(cm) {
1490
    return cm.options.readOnly || cm.doc.cantEdit;
1491
  }
1492
1493
  // EVENT HANDLERS
1494
1495
  function registerEventHandlers(cm) {
1496
    var d = cm.display;
1497
    on(d.scroller, "mousedown", operation(cm, onMouseDown));
1498
    if (ie)
1499
      on(d.scroller, "dblclick", operation(cm, function(e) {
1500
        if (signalDOMEvent(cm, e)) return;
1501
        var pos = posFromMouse(cm, e);
1502
        if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
1503
        e_preventDefault(e);
1504
        var word = findWordAt(getLine(cm.doc, pos.line).text, pos);
1505
        extendSelection(cm.doc, word.from, word.to);
1506
      }));
1507
    else
1508
      on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
1509
    on(d.lineSpace, "selectstart", function(e) {
1510
      if (!eventInWidget(d, e)) e_preventDefault(e);
1511
    });
1512
    // Gecko browsers fire contextmenu *after* opening the menu, at
1513
    // which point we can't mess with it anymore. Context menu is
1514
    // handled in onMouseDown for Gecko.
1515
    if (!captureMiddleClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
1516
1517
    on(d.scroller, "scroll", function() {
1518
      if (d.scroller.clientHeight) {
1519
        setScrollTop(cm, d.scroller.scrollTop);
1520
        setScrollLeft(cm, d.scroller.scrollLeft, true);
1521
        signal(cm, "scroll", cm);
1522
      }
1523
    });
1524
    on(d.scrollbarV, "scroll", function() {
1525
      if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop);
1526
    });
1527
    on(d.scrollbarH, "scroll", function() {
1528
      if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft);
1529
    });
1530
1531
    on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
1532
    on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
1533
1534
    function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm), 0); }
1535
    on(d.scrollbarH, "mousedown", reFocus);
1536
    on(d.scrollbarV, "mousedown", reFocus);
1537
    // Prevent wrapper from ever scrolling
1538
    on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
1539
1540
    var resizeTimer;
1541
    function onResize() {
1542
      if (resizeTimer == null) resizeTimer = setTimeout(function() {
1543
        resizeTimer = null;
1544
        // Might be a text scaling operation, clear size caches.
1545
        d.cachedCharWidth = d.cachedTextHeight = knownScrollbarWidth = null;
1546
        clearCaches(cm);
1547
        runInOp(cm, bind(regChange, cm));
1548
      }, 100);
1549
    }
1550
    on(window, "resize", onResize);
1551
    // Above handler holds on to the editor and its data structures.
1552
    // Here we poll to unregister it when the editor is no longer in
1553
    // the document, so that it can be garbage-collected.
1554
    function unregister() {
1555
      for (var p = d.wrapper.parentNode; p && p != document.body; p = p.parentNode) {}
1556
      if (p) setTimeout(unregister, 5000);
1557
      else off(window, "resize", onResize);
1558
    }
1559
    setTimeout(unregister, 5000);
1560
1561
    on(d.input, "keyup", operation(cm, function(e) {
1562
      if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
1563
      if (e.keyCode == 16) cm.doc.sel.shift = false;
1564
    }));
1565
    on(d.input, "input", bind(fastPoll, cm));
1566
    on(d.input, "keydown", operation(cm, onKeyDown));
1567
    on(d.input, "keypress", operation(cm, onKeyPress));
1568
    on(d.input, "focus", bind(onFocus, cm));
1569
    on(d.input, "blur", bind(onBlur, cm));
1570
1571
    function drag_(e) {
1572
      if (signalDOMEvent(cm, e) || cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return;
1573
      e_stop(e);
1574
    }
1575
    if (cm.options.dragDrop) {
1576
      on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});
1577
      on(d.scroller, "dragenter", drag_);
1578
      on(d.scroller, "dragover", drag_);
1579
      on(d.scroller, "drop", operation(cm, onDrop));
1580
    }
1581
    on(d.scroller, "paste", function(e){
1582
      if (eventInWidget(d, e)) return;
1583
      focusInput(cm);
1584
      fastPoll(cm);
1585
    });
1586
    on(d.input, "paste", function() {
1587
      cm.state.pasteIncoming = true;
1588
      fastPoll(cm);
1589
    });
1590
1591
    function prepareCopy() {
1592
      if (d.inaccurateSelection) {
1593
        d.prevInput = "";
1594
        d.inaccurateSelection = false;
1595
        d.input.value = cm.getSelection();
1596
        selectInput(d.input);
1597
      }
1598
    }
1599
    on(d.input, "cut", prepareCopy);
1600
    on(d.input, "copy", prepareCopy);
1601
1602
    // Needed to handle Tab key in KHTML
1603
    if (khtml) on(d.sizer, "mouseup", function() {
1604
        if (document.activeElement == d.input) d.input.blur();
1605
        focusInput(cm);
1606
    });
1607
  }
1608
1609
  function eventInWidget(display, e) {
1610
    for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
1611
      if (!n || n.ignoreEvents || n.parentNode == display.sizer && n != display.mover) return true;
1612
    }
1613
  }
1614
1615
  function posFromMouse(cm, e, liberal) {
1616
    var display = cm.display;
1617
    if (!liberal) {
1618
      var target = e_target(e);
1619
      if (target == display.scrollbarH || target == display.scrollbarH.firstChild ||
1620
          target == display.scrollbarV || target == display.scrollbarV.firstChild ||
1621
          target == display.scrollbarFiller || target == display.gutterFiller) return null;
1622
    }
1623
    var x, y, space = getRect(display.lineSpace);
1624
    // Fails unpredictably on IE[67] when mouse is dragged around quickly.
1625
    try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
1626
    return coordsChar(cm, x - space.left, y - space.top);
1627
  }
1628
1629
  var lastClick, lastDoubleClick;
1630
  function onMouseDown(e) {
1631
    if (signalDOMEvent(this, e)) return;
1632
    var cm = this, display = cm.display, doc = cm.doc, sel = doc.sel;
1633
    sel.shift = e.shiftKey;
1634
1635
    if (eventInWidget(display, e)) {
1636
      if (!webkit) {
1637
        display.scroller.draggable = false;
1638
        setTimeout(function(){display.scroller.draggable = true;}, 100);
1639
      }
1640
      return;
1641
    }
1642
    if (clickInGutter(cm, e)) return;
1643
    var start = posFromMouse(cm, e);
1644
1645
    switch (e_button(e)) {
1646
    case 3:
1647
      if (captureMiddleClick) onContextMenu.call(cm, cm, e);
1648
      return;
1649
    case 2:
1650
      if (start) extendSelection(cm.doc, start);
1651
      setTimeout(bind(focusInput, cm), 20);
1652
      e_preventDefault(e);
1653
      return;
1654
    }
1655
    // For button 1, if it was clicked inside the editor
1656
    // (posFromMouse returning non-null), we have to adjust the
1657
    // selection.
1658
    if (!start) {if (e_target(e) == display.scroller) e_preventDefault(e); return;}
1659
1660
    if (!cm.state.focused) onFocus(cm);
1661
1662
    var now = +new Date, type = "single";
1663
    if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) {
1664
      type = "triple";
1665
      e_preventDefault(e);
1666
      setTimeout(bind(focusInput, cm), 20);
1667
      selectLine(cm, start.line);
1668
    } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) {
1669
      type = "double";
1670
      lastDoubleClick = {time: now, pos: start};
1671
      e_preventDefault(e);
1672
      var word = findWordAt(getLine(doc, start.line).text, start);
1673
      extendSelection(cm.doc, word.from, word.to);
1674
    } else { lastClick = {time: now, pos: start}; }
1675
1676
    var last = start;
1677
    if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && !posEq(sel.from, sel.to) &&
1678
        !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") {
1679
      var dragEnd = operation(cm, function(e2) {
1680
        if (webkit) display.scroller.draggable = false;
1681
        cm.state.draggingText = false;
1682
        off(document, "mouseup", dragEnd);
1683
        off(display.scroller, "drop", dragEnd);
1684
        if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
1685
          e_preventDefault(e2);
1686
          extendSelection(cm.doc, start);
1687
          focusInput(cm);
1688
        }
1689
      });
1690
      // Let the drag handler handle this.
1691
      if (webkit) display.scroller.draggable = true;
1692
      cm.state.draggingText = dragEnd;
1693
      // IE's approach to draggable
1694
      if (display.scroller.dragDrop) display.scroller.dragDrop();
1695
      on(document, "mouseup", dragEnd);
1696
      on(display.scroller, "drop", dragEnd);
1697
      return;
1698
    }
1699
    e_preventDefault(e);
1700
    if (type == "single") extendSelection(cm.doc, clipPos(doc, start));
1701
1702
    var startstart = sel.from, startend = sel.to, lastPos = start;
1703
1704
    function doSelect(cur) {
1705
      if (posEq(lastPos, cur)) return;
1706
      lastPos = cur;
1707
1708
      if (type == "single") {
1709
        extendSelection(cm.doc, clipPos(doc, start), cur);
1710
        return;
1711
      }
1712
1713
      startstart = clipPos(doc, startstart);
1714
      startend = clipPos(doc, startend);
1715
      if (type == "double") {
1716
        var word = findWordAt(getLine(doc, cur.line).text, cur);
1717
        if (posLess(cur, startstart)) extendSelection(cm.doc, word.from, startend);
1718
        else extendSelection(cm.doc, startstart, word.to);
1719
      } else if (type == "triple") {
1720
        if (posLess(cur, startstart)) extendSelection(cm.doc, startend, clipPos(doc, Pos(cur.line, 0)));
1721
        else extendSelection(cm.doc, startstart, clipPos(doc, Pos(cur.line + 1, 0)));
1722
      }
1723
    }
1724
1725
    var editorSize = getRect(display.wrapper);
1726
    // Used to ensure timeout re-tries don't fire when another extend
1727
    // happened in the meantime (clearTimeout isn't reliable -- at
1728
    // least on Chrome, the timeouts still happen even when cleared,
1729
    // if the clear happens after their scheduled firing time).
1730
    var counter = 0;
1731
1732
    function extend(e) {
1733
      var curCount = ++counter;
1734
      var cur = posFromMouse(cm, e, true);
1735
      if (!cur) return;
1736
      if (!posEq(cur, last)) {
1737
        if (!cm.state.focused) onFocus(cm);
1738
        last = cur;
1739
        doSelect(cur);
1740
        var visible = visibleLines(display, doc);
1741
        if (cur.line >= visible.to || cur.line < visible.from)
1742
          setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
1743
      } else {
1744
        var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
1745
        if (outside) setTimeout(operation(cm, function() {
1746
          if (counter != curCount) return;
1747
          display.scroller.scrollTop += outside;
1748
          extend(e);
1749
        }), 50);
1750
      }
1751
    }
1752
1753
    function done(e) {
1754
      counter = Infinity;
1755
      e_preventDefault(e);
1756
      focusInput(cm);
1757
      off(document, "mousemove", move);
1758
      off(document, "mouseup", up);
1759
    }
1760
1761
    var move = operation(cm, function(e) {
1762
      if (!ie && !e_button(e)) done(e);
1763
      else extend(e);
1764
    });
1765
    var up = operation(cm, done);
1766
    on(document, "mousemove", move);
1767
    on(document, "mouseup", up);
1768
  }
1769
1770
  function clickInGutter(cm, e) {
1771
    var display = cm.display;
1772
    try { var mX = e.clientX, mY = e.clientY; }
1773
    catch(e) { return false; }
1774
1775
    if (mX >= Math.floor(getRect(display.gutters).right)) return false;
1776
    e_preventDefault(e);
1777
    if (!hasHandler(cm, "gutterClick")) return true;
1778
1779
    var lineBox = getRect(display.lineDiv);
1780
    if (mY > lineBox.bottom) return true;
1781
    mY -= lineBox.top - display.viewOffset;
1782
1783
    for (var i = 0; i < cm.options.gutters.length; ++i) {
1784
      var g = display.gutters.childNodes[i];
1785
      if (g && getRect(g).right >= mX) {
1786
        var line = lineAtHeight(cm.doc, mY);
1787
        var gutter = cm.options.gutters[i];
1788
        signalLater(cm, "gutterClick", cm, line, gutter, e);
1789
        break;
1790
      }
1791
    }
1792
    return true;
1793
  }
1794
1795
  // Kludge to work around strange IE behavior where it'll sometimes
1796
  // re-fire a series of drag-related events right after the drop (#1551)
1797
  var lastDrop = 0;
1798
1799
  function onDrop(e) {
1800
    var cm = this;
1801
    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e) || (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))))
1802
      return;
1803
    e_preventDefault(e);
1804
    if (ie) lastDrop = +new Date;
1805
    var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
1806
    if (!pos || isReadOnly(cm)) return;
1807
    if (files && files.length && window.FileReader && window.File) {
1808
      var n = files.length, text = Array(n), read = 0;
1809
      var loadFile = function(file, i) {
1810
        var reader = new FileReader;
1811
        reader.onload = function() {
1812
          text[i] = reader.result;
1813
          if (++read == n) {
1814
            pos = clipPos(cm.doc, pos);
1815
            makeChange(cm.doc, {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"}, "around");
1816
          }
1817
        };
1818
        reader.readAsText(file);
1819
      };
1820
      for (var i = 0; i < n; ++i) loadFile(files[i], i);
1821
    } else {
1822
      // Don't do a replace if the drop happened inside of the selected text.
1823
      if (cm.state.draggingText && !(posLess(pos, cm.doc.sel.from) || posLess(cm.doc.sel.to, pos))) {
1824
        cm.state.draggingText(e);
1825
        // Ensure the editor is re-focused
1826
        setTimeout(bind(focusInput, cm), 20);
1827
        return;
1828
      }
1829
      try {
1830
        var text = e.dataTransfer.getData("Text");
1831
        if (text) {
1832
          var curFrom = cm.doc.sel.from, curTo = cm.doc.sel.to;
1833
          setSelection(cm.doc, pos, pos);
1834
          if (cm.state.draggingText) replaceRange(cm.doc, "", curFrom, curTo, "paste");
1835
          cm.replaceSelection(text, null, "paste");
1836
          focusInput(cm);
1837
          onFocus(cm);
1838
        }
1839
      }
1840
      catch(e){}
1841
    }
1842
  }
1843
1844
  function onDragStart(cm, e) {
1845
    if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
1846
    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
1847
1848
    var txt = cm.getSelection();
1849
    e.dataTransfer.setData("Text", txt);
1850
1851
    // Use dummy image instead of default browsers image.
1852
    // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
1853
    if (e.dataTransfer.setDragImage && !safari) {
1854
      var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
1855
      if (opera) {
1856
        img.width = img.height = 1;
1857
        cm.display.wrapper.appendChild(img);
1858
        // Force a relayout, or Opera won't use our image for some obscure reason
1859
        img._top = img.offsetTop;
1860
      }
1861
      e.dataTransfer.setDragImage(img, 0, 0);
1862
      if (opera) img.parentNode.removeChild(img);
1863
    }
1864
  }
1865
1866
  function setScrollTop(cm, val) {
1867
    if (Math.abs(cm.doc.scrollTop - val) < 2) return;
1868
    cm.doc.scrollTop = val;
1869
    if (!gecko) updateDisplay(cm, [], val);
1870
    if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
1871
    if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val;
1872
    if (gecko) updateDisplay(cm, []);
1873
    startWorker(cm, 100);
1874
  }
1875
  function setScrollLeft(cm, val, isScroller) {
1876
    if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
1877
    val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
1878
    cm.doc.scrollLeft = val;
1879
    alignHorizontally(cm);
1880
    if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
1881
    if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val;
1882
  }
1883
1884
  // Since the delta values reported on mouse wheel events are
1885
  // unstandardized between browsers and even browser versions, and
1886
  // generally horribly unpredictable, this code starts by measuring
1887
  // the scroll effect that the first few mouse wheel events have,
1888
  // and, from that, detects the way it can convert deltas to pixel
1889
  // offsets afterwards.
1890
  //
1891
  // The reason we want to know the amount a wheel event will scroll
1892
  // is that it gives us a chance to update the display before the
1893
  // actual scrolling happens, reducing flickering.
1894
1895
  var wheelSamples = 0, wheelPixelsPerUnit = null;
1896
  // Fill in a browser-detected starting value on browsers where we
1897
  // know one. These don't have to be accurate -- the result of them
1898
  // being wrong would just be a slight flicker on the first wheel
1899
  // scroll (if it is large enough).
1900
  if (ie) wheelPixelsPerUnit = -.53;
1901
  else if (gecko) wheelPixelsPerUnit = 15;
1902
  else if (chrome) wheelPixelsPerUnit = -.7;
1903
  else if (safari) wheelPixelsPerUnit = -1/3;
1904
1905
  function onScrollWheel(cm, e) {
1906
    var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
1907
    if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
1908
    if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
1909
    else if (dy == null) dy = e.wheelDelta;
1910
1911
    var display = cm.display, scroll = display.scroller;
1912
    // Quit if there's nothing to scroll here
1913
    if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
1914
          dy && scroll.scrollHeight > scroll.clientHeight)) return;
1915
1916
    // Webkit browsers on OS X abort momentum scrolls when the target
1917
    // of the scroll event is removed from the scrollable element.
1918
    // This hack (see related code in patchDisplay) makes sure the
1919
    // element is kept around.
1920
    if (dy && mac && webkit) {
1921
      for (var cur = e.target; cur != scroll; cur = cur.parentNode) {
1922
        if (cur.lineObj) {
1923
          cm.display.currentWheelTarget = cur;
1924
          break;
1925
        }
1926
      }
1927
    }
1928
1929
    // On some browsers, horizontal scrolling will cause redraws to
1930
    // happen before the gutter has been realigned, causing it to
1931
    // wriggle around in a most unseemly way. When we have an
1932
    // estimated pixels/delta value, we just handle horizontal
1933
    // scrolling entirely here. It'll be slightly off from native, but
1934
    // better than glitching out.
1935
    if (dx && !gecko && !opera && wheelPixelsPerUnit != null) {
1936
      if (dy)
1937
        setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
1938
      setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
1939
      e_preventDefault(e);
1940
      display.wheelStartX = null; // Abort measurement, if in progress
1941
      return;
1942
    }
1943
1944
    if (dy && wheelPixelsPerUnit != null) {
1945
      var pixels = dy * wheelPixelsPerUnit;
1946
      var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
1947
      if (pixels < 0) top = Math.max(0, top + pixels - 50);
1948
      else bot = Math.min(cm.doc.height, bot + pixels + 50);
1949
      updateDisplay(cm, [], {top: top, bottom: bot});
1950
    }
1951
1952
    if (wheelSamples < 20) {
1953
      if (display.wheelStartX == null) {
1954
        display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
1955
        display.wheelDX = dx; display.wheelDY = dy;
1956
        setTimeout(function() {
1957
          if (display.wheelStartX == null) return;
1958
          var movedX = scroll.scrollLeft - display.wheelStartX;
1959
          var movedY = scroll.scrollTop - display.wheelStartY;
1960
          var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
1961
            (movedX && display.wheelDX && movedX / display.wheelDX);
1962
          display.wheelStartX = display.wheelStartY = null;
1963
          if (!sample) return;
1964
          wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
1965
          ++wheelSamples;
1966
        }, 200);
1967
      } else {
1968
        display.wheelDX += dx; display.wheelDY += dy;
1969
      }
1970
    }
1971
  }
1972
1973
  function doHandleBinding(cm, bound, dropShift) {
1974
    if (typeof bound == "string") {
1975
      bound = commands[bound];
1976
      if (!bound) return false;
1977
    }
1978
    // Ensure previous input has been read, so that the handler sees a
1979
    // consistent view of the document
1980
    if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false;
1981
    var doc = cm.doc, prevShift = doc.sel.shift, done = false;
1982
    try {
1983
      if (isReadOnly(cm)) cm.state.suppressEdits = true;
1984
      if (dropShift) doc.sel.shift = false;
1985
      done = bound(cm) != Pass;
1986
    } finally {
1987
      doc.sel.shift = prevShift;
1988
      cm.state.suppressEdits = false;
1989
    }
1990
    return done;
1991
  }
1992
1993
  function allKeyMaps(cm) {
1994
    var maps = cm.state.keyMaps.slice(0);
1995
    if (cm.options.extraKeys) maps.push(cm.options.extraKeys);
1996
    maps.push(cm.options.keyMap);
1997
    return maps;
1998
  }
1999
2000
  var maybeTransition;
2001
  function handleKeyBinding(cm, e) {
2002
    // Handle auto keymap transitions
2003
    var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto;
2004
    clearTimeout(maybeTransition);
2005
    if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
2006
      if (getKeyMap(cm.options.keyMap) == startMap) {
2007
        cm.options.keyMap = (next.call ? next.call(null, cm) : next);
2008
        keyMapChanged(cm);
2009
      }
2010
    }, 50);
2011
2012
    var name = keyName(e, true), handled = false;
2013
    if (!name) return false;
2014
    var keymaps = allKeyMaps(cm);
2015
2016
    if (e.shiftKey) {
2017
      // First try to resolve full name (including 'Shift-'). Failing
2018
      // that, see if there is a cursor-motion command (starting with
2019
      // 'go') bound to the keyname without 'Shift-'.
2020
      handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandleBinding(cm, b, true);})
2021
             || lookupKey(name, keymaps, function(b) {
2022
                  if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
2023
                    return doHandleBinding(cm, b);
2024
                });
2025
    } else {
2026
      handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm, b); });
2027
    }
2028
2029
    if (handled) {
2030
      e_preventDefault(e);
2031
      restartBlink(cm);
2032
      if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; }
2033
      signalLater(cm, "keyHandled", cm, name, e);
2034
    }
2035
    return handled;
2036
  }
2037
2038
  function handleCharBinding(cm, e, ch) {
2039
    var handled = lookupKey("'" + ch + "'", allKeyMaps(cm),
2040
                            function(b) { return doHandleBinding(cm, b, true); });
2041
    if (handled) {
2042
      e_preventDefault(e);
2043
      restartBlink(cm);
2044
      signalLater(cm, "keyHandled", cm, "'" + ch + "'", e);
2045
    }
2046
    return handled;
2047
  }
2048
2049
  var lastStoppedKey = null;
2050
  function onKeyDown(e) {
2051
    var cm = this;
2052
    if (!cm.state.focused) onFocus(cm);
2053
    if (ie && e.keyCode == 27) { e.returnValue = false; }
2054
    if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
2055
    var code = e.keyCode;
2056
    // IE does strange things with escape.
2057
    cm.doc.sel.shift = code == 16 || e.shiftKey;
2058
    // First give onKeyEvent option a chance to handle this.
2059
    var handled = handleKeyBinding(cm, e);
2060
    if (opera) {
2061
      lastStoppedKey = handled ? code : null;
2062
      // Opera has no cut event... we try to at least catch the key combo
2063
      if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
2064
        cm.replaceSelection("");
2065
    }
2066
  }
2067
2068
  function onKeyPress(e) {
2069
    var cm = this;
2070
    if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
2071
    var keyCode = e.keyCode, charCode = e.charCode;
2072
    if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
2073
    if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return;
2074
    var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
2075
    if (this.options.electricChars && this.doc.mode.electricChars &&
2076
        this.options.smartIndent && !isReadOnly(this) &&
2077
        this.doc.mode.electricChars.indexOf(ch) > -1)
2078
      setTimeout(operation(cm, function() {indentLine(cm, cm.doc.sel.to.line, "smart");}), 75);
2079
    if (handleCharBinding(cm, e, ch)) return;
2080
    if (ie && !ie_lt9) cm.display.inputHasSelection = null;
2081
    fastPoll(cm);
2082
  }
2083
2084
  function onFocus(cm) {
2085
    if (cm.options.readOnly == "nocursor") return;
2086
    if (!cm.state.focused) {
2087
      signal(cm, "focus", cm);
2088
      cm.state.focused = true;
2089
      if (cm.display.wrapper.className.search(/\bCodeMirror-focused\b/) == -1)
2090
        cm.display.wrapper.className += " CodeMirror-focused";
2091
      resetInput(cm, true);
2092
    }
2093
    slowPoll(cm);
2094
    restartBlink(cm);
2095
  }
2096
  function onBlur(cm) {
2097
    if (cm.state.focused) {
2098
      signal(cm, "blur", cm);
2099
      cm.state.focused = false;
2100
      cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-focused", "");
2101
    }
2102
    clearInterval(cm.display.blinker);
2103
    setTimeout(function() {if (!cm.state.focused) cm.doc.sel.shift = false;}, 150);
2104
  }
2105
2106
  var detectingSelectAll;
2107
  function onContextMenu(cm, e) {
2108
    var display = cm.display, sel = cm.doc.sel;
2109
    if (eventInWidget(display, e)) return;
2110
2111
    var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
2112
    if (!pos || opera) return; // Opera is difficult.
2113
    if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
2114
      operation(cm, setSelection)(cm.doc, pos, pos);
2115
2116
    var oldCSS = display.input.style.cssText;
2117
    display.inputDiv.style.position = "absolute";
2118
    display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
2119
      "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; outline: none;" +
2120
      "border-width: 0; outline: none; overflow: hidden; opacity: .05; -ms-opacity: .05; filter: alpha(opacity=5);";
2121
    focusInput(cm);
2122
    resetInput(cm, true);
2123
    // Adds "Select all" to context menu in FF
2124
    if (posEq(sel.from, sel.to)) display.input.value = display.prevInput = " ";
2125
2126
    function prepareSelectAllHack() {
2127
      if (display.input.selectionStart != null) {
2128
        var extval = display.input.value = " " + (posEq(sel.from, sel.to) ? "" : display.input.value);
2129
        display.prevInput = " ";
2130
        display.input.selectionStart = 1; display.input.selectionEnd = extval.length;
2131
      }
2132
    }
2133
    function rehide() {
2134
      display.inputDiv.style.position = "relative";
2135
      display.input.style.cssText = oldCSS;
2136
      if (ie_lt9) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos;
2137
      slowPoll(cm);
2138
2139
      // Try to detect the user choosing select-all
2140
      if (display.input.selectionStart != null) {
2141
        if (!ie || ie_lt9) prepareSelectAllHack();
2142
        clearTimeout(detectingSelectAll);
2143
        var i = 0, poll = function(){
2144
          if (display.prevInput == " " && display.input.selectionStart == 0)
2145
            operation(cm, commands.selectAll)(cm);
2146
          else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500);
2147
          else resetInput(cm);
2148
        };
2149
        detectingSelectAll = setTimeout(poll, 200);
2150
      }
2151
    }
2152
2153
    if (ie && !ie_lt9) prepareSelectAllHack();
2154
    if (captureMiddleClick) {
2155
      e_stop(e);
2156
      var mouseup = function() {
2157
        off(window, "mouseup", mouseup);
2158
        setTimeout(rehide, 20);
2159
      };
2160
      on(window, "mouseup", mouseup);
2161
    } else {
2162
      setTimeout(rehide, 50);
2163
    }
2164
  }
2165
2166
  // UPDATING
2167
2168
  var changeEnd = CodeMirror.changeEnd = function(change) {
2169
    if (!change.text) return change.to;
2170
    return Pos(change.from.line + change.text.length - 1,
2171
               lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
2172
  };
2173
2174
  // Make sure a position will be valid after the given change.
2175
  function clipPostChange(doc, change, pos) {
2176
    if (!posLess(change.from, pos)) return clipPos(doc, pos);
2177
    var diff = (change.text.length - 1) - (change.to.line - change.from.line);
2178
    if (pos.line > change.to.line + diff) {
2179
      var preLine = pos.line - diff, lastLine = doc.first + doc.size - 1;
2180
      if (preLine > lastLine) return Pos(lastLine, getLine(doc, lastLine).text.length);
2181
      return clipToLen(pos, getLine(doc, preLine).text.length);
2182
    }
2183
    if (pos.line == change.to.line + diff)
2184
      return clipToLen(pos, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0) +
2185
                       getLine(doc, change.to.line).text.length - change.to.ch);
2186
    var inside = pos.line - change.from.line;
2187
    return clipToLen(pos, change.text[inside].length + (inside ? 0 : change.from.ch));
2188
  }
2189
2190
  // Hint can be null|"end"|"start"|"around"|{anchor,head}
2191
  function computeSelAfterChange(doc, change, hint) {
2192
    if (hint && typeof hint == "object") // Assumed to be {anchor, head} object
2193
      return {anchor: clipPostChange(doc, change, hint.anchor),
2194
              head: clipPostChange(doc, change, hint.head)};
2195
2196
    if (hint == "start") return {anchor: change.from, head: change.from};
2197
2198
    var end = changeEnd(change);
2199
    if (hint == "around") return {anchor: change.from, head: end};
2200
    if (hint == "end") return {anchor: end, head: end};
2201
2202
    // hint is null, leave the selection alone as much as possible
2203
    var adjustPos = function(pos) {
2204
      if (posLess(pos, change.from)) return pos;
2205
      if (!posLess(change.to, pos)) return end;
2206
2207
      var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
2208
      if (pos.line == change.to.line) ch += end.ch - change.to.ch;
2209
      return Pos(line, ch);
2210
    };
2211
    return {anchor: adjustPos(doc.sel.anchor), head: adjustPos(doc.sel.head)};
2212
  }
2213
2214
  function filterChange(doc, change, update) {
2215
    var obj = {
2216
      canceled: false,
2217
      from: change.from,
2218
      to: change.to,
2219
      text: change.text,
2220
      origin: change.origin,
2221
      cancel: function() { this.canceled = true; }
2222
    };
2223
    if (update) obj.update = function(from, to, text, origin) {
2224
      if (from) this.from = clipPos(doc, from);
2225
      if (to) this.to = clipPos(doc, to);
2226
      if (text) this.text = text;
2227
      if (origin !== undefined) this.origin = origin;
2228
    };
2229
    signal(doc, "beforeChange", doc, obj);
2230
    if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
2231
2232
    if (obj.canceled) return null;
2233
    return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
2234
  }
2235
2236
  // Replace the range from from to to by the strings in replacement.
2237
  // change is a {from, to, text [, origin]} object
2238
  function makeChange(doc, change, selUpdate, ignoreReadOnly) {
2239
    if (doc.cm) {
2240
      if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, selUpdate, ignoreReadOnly);
2241
      if (doc.cm.state.suppressEdits) return;
2242
    }
2243
2244
    if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
2245
      change = filterChange(doc, change, true);
2246
      if (!change) return;
2247
    }
2248
2249
    // Possibly split or suppress the update based on the presence
2250
    // of read-only spans in its range.
2251
    var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
2252
    if (split) {
2253
      for (var i = split.length - 1; i >= 1; --i)
2254
        makeChangeNoReadonly(doc, {from: split[i].from, to: split[i].to, text: [""]});
2255
      if (split.length)
2256
        makeChangeNoReadonly(doc, {from: split[0].from, to: split[0].to, text: change.text}, selUpdate);
2257
    } else {
2258
      makeChangeNoReadonly(doc, change, selUpdate);
2259
    }
2260
  }
2261
2262
  function makeChangeNoReadonly(doc, change, selUpdate) {
2263
    var selAfter = computeSelAfterChange(doc, change, selUpdate);
2264
    addToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
2265
2266
    makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
2267
    var rebased = [];
2268
2269
    linkedDocs(doc, function(doc, sharedHist) {
2270
      if (!sharedHist && indexOf(rebased, doc.history) == -1) {
2271
        rebaseHist(doc.history, change);
2272
        rebased.push(doc.history);
2273
      }
2274
      makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
2275
    });
2276
  }
2277
2278
  function makeChangeFromHistory(doc, type) {
2279
    if (doc.cm && doc.cm.state.suppressEdits) return;
2280
2281
    var hist = doc.history;
2282
    var event = (type == "undo" ? hist.done : hist.undone).pop();
2283
    if (!event) return;
2284
2285
    var anti = {changes: [], anchorBefore: event.anchorAfter, headBefore: event.headAfter,
2286
                anchorAfter: event.anchorBefore, headAfter: event.headBefore,
2287
                generation: hist.generation};
2288
    (type == "undo" ? hist.undone : hist.done).push(anti);
2289
    hist.generation = event.generation || ++hist.maxGeneration;
2290
2291
    var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
2292
2293
    for (var i = event.changes.length - 1; i >= 0; --i) {
2294
      var change = event.changes[i];
2295
      change.origin = type;
2296
      if (filter && !filterChange(doc, change, false)) {
2297
        (type == "undo" ? hist.done : hist.undone).length = 0;
2298
        return;
2299
      }
2300
2301
      anti.changes.push(historyChangeFromChange(doc, change));
2302
2303
      var after = i ? computeSelAfterChange(doc, change, null)
2304
                    : {anchor: event.anchorBefore, head: event.headBefore};
2305
      makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
2306
      var rebased = [];
2307
2308
      linkedDocs(doc, function(doc, sharedHist) {
2309
        if (!sharedHist && indexOf(rebased, doc.history) == -1) {
2310
          rebaseHist(doc.history, change);
2311
          rebased.push(doc.history);
2312
        }
2313
        makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
2314
      });
2315
    }
2316
  }
2317
2318
  function shiftDoc(doc, distance) {
2319
    function shiftPos(pos) {return Pos(pos.line + distance, pos.ch);}
2320
    doc.first += distance;
2321
    if (doc.cm) regChange(doc.cm, doc.first, doc.first, distance);
2322
    doc.sel.head = shiftPos(doc.sel.head); doc.sel.anchor = shiftPos(doc.sel.anchor);
2323
    doc.sel.from = shiftPos(doc.sel.from); doc.sel.to = shiftPos(doc.sel.to);
2324
  }
2325
2326
  function makeChangeSingleDoc(doc, change, selAfter, spans) {
2327
    if (doc.cm && !doc.cm.curOp)
2328
      return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
2329
2330
    if (change.to.line < doc.first) {
2331
      shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
2332
      return;
2333
    }
2334
    if (change.from.line > doc.lastLine()) return;
2335
2336
    // Clip the change to the size of this doc
2337
    if (change.from.line < doc.first) {
2338
      var shift = change.text.length - 1 - (doc.first - change.from.line);
2339
      shiftDoc(doc, shift);
2340
      change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
2341
                text: [lst(change.text)], origin: change.origin};
2342
    }
2343
    var last = doc.lastLine();
2344
    if (change.to.line > last) {
2345
      change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
2346
                text: [change.text[0]], origin: change.origin};
2347
    }
2348
2349
    change.removed = getBetween(doc, change.from, change.to);
2350
2351
    if (!selAfter) selAfter = computeSelAfterChange(doc, change, null);
2352
    if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans, selAfter);
2353
    else updateDoc(doc, change, spans, selAfter);
2354
  }
2355
2356
  function makeChangeSingleDocInEditor(cm, change, spans, selAfter) {
2357
    var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
2358
2359
    var recomputeMaxLength = false, checkWidthStart = from.line;
2360
    if (!cm.options.lineWrapping) {
2361
      checkWidthStart = lineNo(visualLine(doc, getLine(doc, from.line)));
2362
      doc.iter(checkWidthStart, to.line + 1, function(line) {
2363
        if (line == display.maxLine) {
2364
          recomputeMaxLength = true;
2365
          return true;
2366
        }
2367
      });
2368
    }
2369
2370
    if (!posLess(doc.sel.head, change.from) && !posLess(change.to, doc.sel.head))
2371
      cm.curOp.cursorActivity = true;
2372
2373
    updateDoc(doc, change, spans, selAfter, estimateHeight(cm));
2374
2375
    if (!cm.options.lineWrapping) {
2376
      doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
2377
        var len = lineLength(doc, line);
2378
        if (len > display.maxLineLength) {
2379
          display.maxLine = line;
2380
          display.maxLineLength = len;
2381
          display.maxLineChanged = true;
2382
          recomputeMaxLength = false;
2383
        }
2384
      });
2385
      if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
2386
    }
2387
2388
    // Adjust frontier, schedule worker
2389
    doc.frontier = Math.min(doc.frontier, from.line);
2390
    startWorker(cm, 400);
2391
2392
    var lendiff = change.text.length - (to.line - from.line) - 1;
2393
    // Remember that these lines changed, for updating the display
2394
    regChange(cm, from.line, to.line + 1, lendiff);
2395
2396
    if (hasHandler(cm, "change")) {
2397
      var changeObj = {from: from, to: to,
2398
                       text: change.text,
2399
                       removed: change.removed,
2400
                       origin: change.origin};
2401
      if (cm.curOp.textChanged) {
2402
        for (var cur = cm.curOp.textChanged; cur.next; cur = cur.next) {}
2403
        cur.next = changeObj;
2404
      } else cm.curOp.textChanged = changeObj;
2405
    }
2406
  }
2407
2408
  function replaceRange(doc, code, from, to, origin) {
2409
    if (!to) to = from;
2410
    if (posLess(to, from)) { var tmp = to; to = from; from = tmp; }
2411
    if (typeof code == "string") code = splitLines(code);
2412
    makeChange(doc, {from: from, to: to, text: code, origin: origin}, null);
2413
  }
2414
2415
  // POSITION OBJECT
2416
2417
  function Pos(line, ch) {
2418
    if (!(this instanceof Pos)) return new Pos(line, ch);
2419
    this.line = line; this.ch = ch;
2420
  }
2421
  CodeMirror.Pos = Pos;
2422
2423
  function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
2424
  function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
2425
  function copyPos(x) {return Pos(x.line, x.ch);}
2426
2427
  // SELECTION
2428
2429
  function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
2430
  function clipPos(doc, pos) {
2431
    if (pos.line < doc.first) return Pos(doc.first, 0);
2432
    var last = doc.first + doc.size - 1;
2433
    if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
2434
    return clipToLen(pos, getLine(doc, pos.line).text.length);
2435
  }
2436
  function clipToLen(pos, linelen) {
2437
    var ch = pos.ch;
2438
    if (ch == null || ch > linelen) return Pos(pos.line, linelen);
2439
    else if (ch < 0) return Pos(pos.line, 0);
2440
    else return pos;
2441
  }
2442
  function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
2443
2444
  // If shift is held, this will move the selection anchor. Otherwise,
2445
  // it'll set the whole selection.
2446
  function extendSelection(doc, pos, other, bias) {
2447
    if (doc.sel.shift || doc.sel.extend) {
2448
      var anchor = doc.sel.anchor;
2449
      if (other) {
2450
        var posBefore = posLess(pos, anchor);
2451
        if (posBefore != posLess(other, anchor)) {
2452
          anchor = pos;
2453
          pos = other;
2454
        } else if (posBefore != posLess(pos, other)) {
2455
          pos = other;
2456
        }
2457
      }
2458
      setSelection(doc, anchor, pos, bias);
2459
    } else {
2460
      setSelection(doc, pos, other || pos, bias);
2461
    }
2462
    if (doc.cm) doc.cm.curOp.userSelChange = true;
2463
  }
2464
2465
  function filterSelectionChange(doc, anchor, head) {
2466
    var obj = {anchor: anchor, head: head};
2467
    signal(doc, "beforeSelectionChange", doc, obj);
2468
    if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
2469
    obj.anchor = clipPos(doc, obj.anchor); obj.head = clipPos(doc, obj.head);
2470
    return obj;
2471
  }
2472
2473
  // Update the selection. Last two args are only used by
2474
  // updateDoc, since they have to be expressed in the line
2475
  // numbers before the update.
2476
  function setSelection(doc, anchor, head, bias, checkAtomic) {
2477
    if (!checkAtomic && hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) {
2478
      var filtered = filterSelectionChange(doc, anchor, head);
2479
      head = filtered.head;
2480
      anchor = filtered.anchor;
2481
    }
2482
2483
    var sel = doc.sel;
2484
    sel.goalColumn = null;
2485
    // Skip over atomic spans.
2486
    if (checkAtomic || !posEq(anchor, sel.anchor))
2487
      anchor = skipAtomic(doc, anchor, bias, checkAtomic != "push");
2488
    if (checkAtomic || !posEq(head, sel.head))
2489
      head = skipAtomic(doc, head, bias, checkAtomic != "push");
2490
2491
    if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return;
2492
2493
    sel.anchor = anchor; sel.head = head;
2494
    var inv = posLess(head, anchor);
2495
    sel.from = inv ? head : anchor;
2496
    sel.to = inv ? anchor : head;
2497
2498
    if (doc.cm)
2499
      doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged =
2500
        doc.cm.curOp.cursorActivity = true;
2501
2502
    signalLater(doc, "cursorActivity", doc);
2503
  }
2504
2505
  function reCheckSelection(cm) {
2506
    setSelection(cm.doc, cm.doc.sel.from, cm.doc.sel.to, null, "push");
2507
  }
2508
2509
  function skipAtomic(doc, pos, bias, mayClear) {
2510
    var flipped = false, curPos = pos;
2511
    var dir = bias || 1;
2512
    doc.cantEdit = false;
2513
    search: for (;;) {
2514
      var line = getLine(doc, curPos.line);
2515
      if (line.markedSpans) {
2516
        for (var i = 0; i < line.markedSpans.length; ++i) {
2517
          var sp = line.markedSpans[i], m = sp.marker;
2518
          if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
2519
              (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
2520
            if (mayClear) {
2521
              signal(m, "beforeCursorEnter");
2522
              if (m.explicitlyCleared) {
2523
                if (!line.markedSpans) break;
2524
                else {--i; continue;}
2525
              }
2526
            }
2527
            if (!m.atomic) continue;
2528
            var newPos = m.find()[dir < 0 ? "from" : "to"];
2529
            if (posEq(newPos, curPos)) {
2530
              newPos.ch += dir;
2531
              if (newPos.ch < 0) {
2532
                if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
2533
                else newPos = null;
2534
              } else if (newPos.ch > line.text.length) {
2535
                if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
2536
                else newPos = null;
2537
              }
2538
              if (!newPos) {
2539
                if (flipped) {
2540
                  // Driven in a corner -- no valid cursor position found at all
2541
                  // -- try again *with* clearing, if we didn't already
2542
                  if (!mayClear) return skipAtomic(doc, pos, bias, true);
2543
                  // Otherwise, turn off editing until further notice, and return the start of the doc
2544
                  doc.cantEdit = true;
2545
                  return Pos(doc.first, 0);
2546
                }
2547
                flipped = true; newPos = pos; dir = -dir;
2548
              }
2549
            }
2550
            curPos = newPos;
2551
            continue search;
2552
          }
2553
        }
2554
      }
2555
      return curPos;
2556
    }
2557
  }
2558
2559
  // SCROLLING
2560
2561
  function scrollCursorIntoView(cm) {
2562
    var coords = scrollPosIntoView(cm, cm.doc.sel.head, cm.options.cursorScrollMargin);
2563
    if (!cm.state.focused) return;
2564
    var display = cm.display, box = getRect(display.sizer), doScroll = null;
2565
    if (coords.top + box.top < 0) doScroll = true;
2566
    else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
2567
    if (doScroll != null && !phantom) {
2568
      var hidden = display.cursor.style.display == "none";
2569
      if (hidden) {
2570
        display.cursor.style.display = "";
2571
        display.cursor.style.left = coords.left + "px";
2572
        display.cursor.style.top = (coords.top - display.viewOffset) + "px";
2573
      }
2574
      display.cursor.scrollIntoView(doScroll);
2575
      if (hidden) display.cursor.style.display = "none";
2576
    }
2577
  }
2578
2579
  function scrollPosIntoView(cm, pos, margin) {
2580
    if (margin == null) margin = 0;
2581
    for (;;) {
2582
      var changed = false, coords = cursorCoords(cm, pos);
2583
      var scrollPos = calculateScrollPos(cm, coords.left, coords.top - margin, coords.left, coords.bottom + margin);
2584
      var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
2585
      if (scrollPos.scrollTop != null) {
2586
        setScrollTop(cm, scrollPos.scrollTop);
2587
        if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
2588
      }
2589
      if (scrollPos.scrollLeft != null) {
2590
        setScrollLeft(cm, scrollPos.scrollLeft);
2591
        if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
2592
      }
2593
      if (!changed) return coords;
2594
    }
2595
  }
2596
2597
  function scrollIntoView(cm, x1, y1, x2, y2) {
2598
    var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
2599
    if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
2600
    if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
2601
  }
2602
2603
  function calculateScrollPos(cm, x1, y1, x2, y2) {
2604
    var display = cm.display, snapMargin = textHeight(cm.display);
2605
    if (y1 < 0) y1 = 0;
2606
    var screen = display.scroller.clientHeight - scrollerCutOff, screentop = display.scroller.scrollTop, result = {};
2607
    var docBottom = cm.doc.height + paddingVert(display);
2608
    var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
2609
    if (y1 < screentop) {
2610
      result.scrollTop = atTop ? 0 : y1;
2611
    } else if (y2 > screentop + screen) {
2612
      var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
2613
      if (newTop != screentop) result.scrollTop = newTop;
2614
    }
2615
2616
    var screenw = display.scroller.clientWidth - scrollerCutOff, screenleft = display.scroller.scrollLeft;
2617
    x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth;
2618
    var gutterw = display.gutters.offsetWidth;
2619
    var atLeft = x1 < gutterw + 10;
2620
    if (x1 < screenleft + gutterw || atLeft) {
2621
      if (atLeft) x1 = 0;
2622
      result.scrollLeft = Math.max(0, x1 - 10 - gutterw);
2623
    } else if (x2 > screenw + screenleft - 3) {
2624
      result.scrollLeft = x2 + 10 - screenw;
2625
    }
2626
    return result;
2627
  }
2628
2629
  function updateScrollPos(cm, left, top) {
2630
    cm.curOp.updateScrollPos = {scrollLeft: left == null ? cm.doc.scrollLeft : left,
2631
                                scrollTop: top == null ? cm.doc.scrollTop : top};
2632
  }
2633
2634
  function addToScrollPos(cm, left, top) {
2635
    var pos = cm.curOp.updateScrollPos || (cm.curOp.updateScrollPos = {scrollLeft: cm.doc.scrollLeft, scrollTop: cm.doc.scrollTop});
2636
    var scroll = cm.display.scroller;
2637
    pos.scrollTop = Math.max(0, Math.min(scroll.scrollHeight - scroll.clientHeight, pos.scrollTop + top));
2638
    pos.scrollLeft = Math.max(0, Math.min(scroll.scrollWidth - scroll.clientWidth, pos.scrollLeft + left));
2639
  }
2640
2641
  // API UTILITIES
2642
2643
  function indentLine(cm, n, how, aggressive) {
2644
    var doc = cm.doc;
2645
    if (how == null) how = "add";
2646
    if (how == "smart") {
2647
      if (!cm.doc.mode.indent) how = "prev";
2648
      else var state = getStateBefore(cm, n);
2649
    }
2650
2651
    var tabSize = cm.options.tabSize;
2652
    var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
2653
    var curSpaceString = line.text.match(/^\s*/)[0], indentation;
2654
    if (how == "smart") {
2655
      indentation = cm.doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
2656
      if (indentation == Pass) {
2657
        if (!aggressive) return;
2658
        how = "prev";
2659
      }
2660
    }
2661
    if (how == "prev") {
2662
      if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
2663
      else indentation = 0;
2664
    } else if (how == "add") {
2665
      indentation = curSpace + cm.options.indentUnit;
2666
    } else if (how == "subtract") {
2667
      indentation = curSpace - cm.options.indentUnit;
2668
    } else if (typeof how == "number") {
2669
      indentation = curSpace + how;
2670
    }
2671
    indentation = Math.max(0, indentation);
2672
2673
    var indentString = "", pos = 0;
2674
    if (cm.options.indentWithTabs)
2675
      for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
2676
    if (pos < indentation) indentString += spaceStr(indentation - pos);
2677
2678
    if (indentString != curSpaceString)
2679
      replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
2680
    line.stateAfter = null;
2681
  }
2682
2683
  function changeLine(cm, handle, op) {
2684
    var no = handle, line = handle, doc = cm.doc;
2685
    if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
2686
    else no = lineNo(handle);
2687
    if (no == null) return null;
2688
    if (op(line, no)) regChange(cm, no, no + 1);
2689
    else return null;
2690
    return line;
2691
  }
2692
2693
  function findPosH(doc, pos, dir, unit, visually) {
2694
    var line = pos.line, ch = pos.ch, origDir = dir;
2695
    var lineObj = getLine(doc, line);
2696
    var possible = true;
2697
    function findNextLine() {
2698
      var l = line + dir;
2699
      if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
2700
      line = l;
2701
      return lineObj = getLine(doc, l);
2702
    }
2703
    function moveOnce(boundToLine) {
2704
      var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
2705
      if (next == null) {
2706
        if (!boundToLine && findNextLine()) {
2707
          if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
2708
          else ch = dir < 0 ? lineObj.text.length : 0;
2709
        } else return (possible = false);
2710
      } else ch = next;
2711
      return true;
2712
    }
2713
2714
    if (unit == "char") moveOnce();
2715
    else if (unit == "column") moveOnce(true);
2716
    else if (unit == "word" || unit == "group") {
2717
      var sawType = null, group = unit == "group";
2718
      for (var first = true;; first = false) {
2719
        if (dir < 0 && !moveOnce(!first)) break;
2720
        var cur = lineObj.text.charAt(ch) || "\n";
2721
        var type = isWordChar(cur) ? "w"
2722
          : !group ? null
2723
          : /\s/.test(cur) ? null
2724
          : "p";
2725
        if (sawType && sawType != type) {
2726
          if (dir < 0) {dir = 1; moveOnce();}
2727
          break;
2728
        }
2729
        if (type) sawType = type;
2730
        if (dir > 0 && !moveOnce(!first)) break;
2731
      }
2732
    }
2733
    var result = skipAtomic(doc, Pos(line, ch), origDir, true);
2734
    if (!possible) result.hitSide = true;
2735
    return result;
2736
  }
2737
2738
  function findPosV(cm, pos, dir, unit) {
2739
    var doc = cm.doc, x = pos.left, y;
2740
    if (unit == "page") {
2741
      var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
2742
      y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
2743
    } else if (unit == "line") {
2744
      y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
2745
    }
2746
    for (;;) {
2747
      var target = coordsChar(cm, x, y);
2748
      if (!target.outside) break;
2749
      if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
2750
      y += dir * 5;
2751
    }
2752
    return target;
2753
  }
2754
2755
  function findWordAt(line, pos) {
2756
    var start = pos.ch, end = pos.ch;
2757
    if (line) {
2758
      if (pos.xRel < 0 || end == line.length) --start; else ++end;
2759
      var startChar = line.charAt(start);
2760
      var check = isWordChar(startChar) ? isWordChar
2761
        : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
2762
        : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
2763
      while (start > 0 && check(line.charAt(start - 1))) --start;
2764
      while (end < line.length && check(line.charAt(end))) ++end;
2765
    }
2766
    return {from: Pos(pos.line, start), to: Pos(pos.line, end)};
2767
  }
2768
2769
  function selectLine(cm, line) {
2770
    extendSelection(cm.doc, Pos(line, 0), clipPos(cm.doc, Pos(line + 1, 0)));
2771
  }
2772
2773
  // PROTOTYPE
2774
2775
  // The publicly visible API. Note that operation(null, f) means
2776
  // 'wrap f in an operation, performed on its `this` parameter'
2777
2778
  CodeMirror.prototype = {
2779
    constructor: CodeMirror,
2780
    focus: function(){window.focus(); focusInput(this); onFocus(this); fastPoll(this);},
2781
2782
    setOption: function(option, value) {
2783
      var options = this.options, old = options[option];
2784
      if (options[option] == value && option != "mode") return;
2785
      options[option] = value;
2786
      if (optionHandlers.hasOwnProperty(option))
2787
        operation(this, optionHandlers[option])(this, value, old);
2788
    },
2789
2790
    getOption: function(option) {return this.options[option];},
2791
    getDoc: function() {return this.doc;},
2792
2793
    addKeyMap: function(map, bottom) {
2794
      this.state.keyMaps[bottom ? "push" : "unshift"](map);
2795
    },
2796
    removeKeyMap: function(map) {
2797
      var maps = this.state.keyMaps;
2798
      for (var i = 0; i < maps.length; ++i)
2799
        if ((typeof map == "string" ? maps[i].name : maps[i]) == map) {
2800
          maps.splice(i, 1);
2801
          return true;
2802
        }
2803
    },
2804
2805
    addOverlay: operation(null, function(spec, options) {
2806
      var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
2807
      if (mode.startState) throw new Error("Overlays may not be stateful.");
2808
      this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
2809
      this.state.modeGen++;
2810
      regChange(this);
2811
    }),
2812
    removeOverlay: operation(null, function(spec) {
2813
      var overlays = this.state.overlays;
2814
      for (var i = 0; i < overlays.length; ++i) {
2815
        var cur = overlays[i].modeSpec;
2816
        if (cur == spec || typeof spec == "string" && cur.name == spec) {
2817
          overlays.splice(i, 1);
2818
          this.state.modeGen++;
2819
          regChange(this);
2820
          return;
2821
        }
2822
      }
2823
    }),
2824
2825
    indentLine: operation(null, function(n, dir, aggressive) {
2826
      if (typeof dir != "string" && typeof dir != "number") {
2827
        if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
2828
        else dir = dir ? "add" : "subtract";
2829
      }
2830
      if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
2831
    }),
2832
    indentSelection: operation(null, function(how) {
2833
      var sel = this.doc.sel;
2834
      if (posEq(sel.from, sel.to)) return indentLine(this, sel.from.line, how);
2835
      var e = sel.to.line - (sel.to.ch ? 0 : 1);
2836
      for (var i = sel.from.line; i <= e; ++i) indentLine(this, i, how);
2837
    }),
2838
2839
    // Fetch the parser token for a given character. Useful for hacks
2840
    // that want to inspect the mode state (say, for completion).
2841
    getTokenAt: function(pos, precise) {
2842
      var doc = this.doc;
2843
      pos = clipPos(doc, pos);
2844
      var state = getStateBefore(this, pos.line, precise), mode = this.doc.mode;
2845
      var line = getLine(doc, pos.line);
2846
      var stream = new StringStream(line.text, this.options.tabSize);
2847
      while (stream.pos < pos.ch && !stream.eol()) {
2848
        stream.start = stream.pos;
2849
        var style = mode.token(stream, state);
2850
      }
2851
      return {start: stream.start,
2852
              end: stream.pos,
2853
              string: stream.current(),
2854
              className: style || null, // Deprecated, use 'type' instead
2855
              type: style || null,
2856
              state: state};
2857
    },
2858
2859
    getTokenTypeAt: function(pos) {
2860
      pos = clipPos(this.doc, pos);
2861
      var styles = getLineStyles(this, getLine(this.doc, pos.line));
2862
      var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
2863
      for (;;) {
2864
        var mid = (before + after) >> 1;
2865
        if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
2866
        else if (styles[mid * 2 + 1] < ch) before = mid + 1;
2867
        else return styles[mid * 2 + 2];
2868
      }
2869
    },
2870
2871
    getStateAfter: function(line, precise) {
2872
      var doc = this.doc;
2873
      line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
2874
      return getStateBefore(this, line + 1, precise);
2875
    },
2876
2877
    cursorCoords: function(start, mode) {
2878
      var pos, sel = this.doc.sel;
2879
      if (start == null) pos = sel.head;
2880
      else if (typeof start == "object") pos = clipPos(this.doc, start);
2881
      else pos = start ? sel.from : sel.to;
2882
      return cursorCoords(this, pos, mode || "page");
2883
    },
2884
2885
    charCoords: function(pos, mode) {
2886
      return charCoords(this, clipPos(this.doc, pos), mode || "page");
2887
    },
2888
2889
    coordsChar: function(coords, mode) {
2890
      coords = fromCoordSystem(this, coords, mode || "page");
2891
      return coordsChar(this, coords.left, coords.top);
2892
    },
2893
2894
    lineAtHeight: function(height, mode) {
2895
      height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
2896
      return lineAtHeight(this.doc, height + this.display.viewOffset);
2897
    },
2898
    heightAtLine: function(line, mode) {
2899
      var end = false, last = this.doc.first + this.doc.size - 1;
2900
      if (line < this.doc.first) line = this.doc.first;
2901
      else if (line > last) { line = last; end = true; }
2902
      var lineObj = getLine(this.doc, line);
2903
      return intoCoordSystem(this, getLine(this.doc, line), {top: 0, left: 0}, mode || "page").top +
2904
        (end ? lineObj.height : 0);
2905
    },
2906
2907
    defaultTextHeight: function() { return textHeight(this.display); },
2908
    defaultCharWidth: function() { return charWidth(this.display); },
2909
2910
    setGutterMarker: operation(null, function(line, gutterID, value) {
2911
      return changeLine(this, line, function(line) {
2912
        var markers = line.gutterMarkers || (line.gutterMarkers = {});
2913
        markers[gutterID] = value;
2914
        if (!value && isEmpty(markers)) line.gutterMarkers = null;
2915
        return true;
2916
      });
2917
    }),
2918
2919
    clearGutter: operation(null, function(gutterID) {
2920
      var cm = this, doc = cm.doc, i = doc.first;
2921
      doc.iter(function(line) {
2922
        if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
2923
          line.gutterMarkers[gutterID] = null;
2924
          regChange(cm, i, i + 1);
2925
          if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
2926
        }
2927
        ++i;
2928
      });
2929
    }),
2930
2931
    addLineClass: operation(null, function(handle, where, cls) {
2932
      return changeLine(this, handle, function(line) {
2933
        var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
2934
        if (!line[prop]) line[prop] = cls;
2935
        else if (new RegExp("(?:^|\\s)" + cls + "(?:$|\\s)").test(line[prop])) return false;
2936
        else line[prop] += " " + cls;
2937
        return true;
2938
      });
2939
    }),
2940
2941
    removeLineClass: operation(null, function(handle, where, cls) {
2942
      return changeLine(this, handle, function(line) {
2943
        var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
2944
        var cur = line[prop];
2945
        if (!cur) return false;
2946
        else if (cls == null) line[prop] = null;
2947
        else {
2948
          var found = cur.match(new RegExp("(?:^|\\s+)" + cls + "(?:$|\\s+)"));
2949
          if (!found) return false;
2950
          var end = found.index + found[0].length;
2951
          line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
2952
        }
2953
        return true;
2954
      });
2955
    }),
2956
2957
    addLineWidget: operation(null, function(handle, node, options) {
2958
      return addLineWidget(this, handle, node, options);
2959
    }),
2960
2961
    removeLineWidget: function(widget) { widget.clear(); },
2962
2963
    lineInfo: function(line) {
2964
      if (typeof line == "number") {
2965
        if (!isLine(this.doc, line)) return null;
2966
        var n = line;
2967
        line = getLine(this.doc, line);
2968
        if (!line) return null;
2969
      } else {
2970
        var n = lineNo(line);
2971
        if (n == null) return null;
2972
      }
2973
      return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
2974
              textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
2975
              widgets: line.widgets};
2976
    },
2977
2978
    getViewport: function() { return {from: this.display.showingFrom, to: this.display.showingTo};},
2979
2980
    addWidget: function(pos, node, scroll, vert, horiz) {
2981
      var display = this.display;
2982
      pos = cursorCoords(this, clipPos(this.doc, pos));
2983
      var top = pos.bottom, left = pos.left;
2984
      node.style.position = "absolute";
2985
      display.sizer.appendChild(node);
2986
      if (vert == "over") {
2987
        top = pos.top;
2988
      } else if (vert == "above" || vert == "near") {
2989
        var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
2990
        hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
2991
        // Default to positioning above (if specified and possible); otherwise default to positioning below
2992
        if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
2993
          top = pos.top - node.offsetHeight;
2994
        else if (pos.bottom + node.offsetHeight <= vspace)
2995
          top = pos.bottom;
2996
        if (left + node.offsetWidth > hspace)
2997
          left = hspace - node.offsetWidth;
2998
      }
2999
      node.style.top = top + "px";
3000
      node.style.left = node.style.right = "";
3001
      if (horiz == "right") {
3002
        left = display.sizer.clientWidth - node.offsetWidth;
3003
        node.style.right = "0px";
3004
      } else {
3005
        if (horiz == "left") left = 0;
3006
        else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
3007
        node.style.left = left + "px";
3008
      }
3009
      if (scroll)
3010
        scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
3011
    },
3012
3013
    triggerOnKeyDown: operation(null, onKeyDown),
3014
3015
    execCommand: function(cmd) {return commands[cmd](this);},
3016
3017
    findPosH: function(from, amount, unit, visually) {
3018
      var dir = 1;
3019
      if (amount < 0) { dir = -1; amount = -amount; }
3020
      for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
3021
        cur = findPosH(this.doc, cur, dir, unit, visually);
3022
        if (cur.hitSide) break;
3023
      }
3024
      return cur;
3025
    },
3026
3027
    moveH: operation(null, function(dir, unit) {
3028
      var sel = this.doc.sel, pos;
3029
      if (sel.shift || sel.extend || posEq(sel.from, sel.to))
3030
        pos = findPosH(this.doc, sel.head, dir, unit, this.options.rtlMoveVisually);
3031
      else
3032
        pos = dir < 0 ? sel.from : sel.to;
3033
      extendSelection(this.doc, pos, pos, dir);
3034
    }),
3035
3036
    deleteH: operation(null, function(dir, unit) {
3037
      var sel = this.doc.sel;
3038
      if (!posEq(sel.from, sel.to)) replaceRange(this.doc, "", sel.from, sel.to, "+delete");
3039
      else replaceRange(this.doc, "", sel.from, findPosH(this.doc, sel.head, dir, unit, false), "+delete");
3040
      this.curOp.userSelChange = true;
3041
    }),
3042
3043
    findPosV: function(from, amount, unit, goalColumn) {
3044
      var dir = 1, x = goalColumn;
3045
      if (amount < 0) { dir = -1; amount = -amount; }
3046
      for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
3047
        var coords = cursorCoords(this, cur, "div");
3048
        if (x == null) x = coords.left;
3049
        else coords.left = x;
3050
        cur = findPosV(this, coords, dir, unit);
3051
        if (cur.hitSide) break;
3052
      }
3053
      return cur;
3054
    },
3055
3056
    moveV: operation(null, function(dir, unit) {
3057
      var sel = this.doc.sel;
3058
      var pos = cursorCoords(this, sel.head, "div");
3059
      if (sel.goalColumn != null) pos.left = sel.goalColumn;
3060
      var target = findPosV(this, pos, dir, unit);
3061
3062
      if (unit == "page") addToScrollPos(this, 0, charCoords(this, target, "div").top - pos.top);
3063
      extendSelection(this.doc, target, target, dir);
3064
      sel.goalColumn = pos.left;
3065
    }),
3066
3067
    toggleOverwrite: function(value) {
3068
      if (value != null && value == this.state.overwrite) return;
3069
      if (this.state.overwrite = !this.state.overwrite)
3070
        this.display.cursor.className += " CodeMirror-overwrite";
3071
      else
3072
        this.display.cursor.className = this.display.cursor.className.replace(" CodeMirror-overwrite", "");
3073
    },
3074
    hasFocus: function() { return this.state.focused; },
3075
3076
    scrollTo: operation(null, function(x, y) {
3077
      updateScrollPos(this, x, y);
3078
    }),
3079
    getScrollInfo: function() {
3080
      var scroller = this.display.scroller, co = scrollerCutOff;
3081
      return {left: scroller.scrollLeft, top: scroller.scrollTop,
3082
              height: scroller.scrollHeight - co, width: scroller.scrollWidth - co,
3083
              clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co};
3084
    },
3085
3086
    scrollIntoView: operation(null, function(pos, margin) {
3087
      if (typeof pos == "number") pos = Pos(pos, 0);
3088
      if (!margin) margin = 0;
3089
      var coords = pos;
3090
3091
      if (!pos || pos.line != null) {
3092
        this.curOp.scrollToPos = pos ? clipPos(this.doc, pos) : this.doc.sel.head;
3093
        this.curOp.scrollToPosMargin = margin;
3094
        coords = cursorCoords(this, this.curOp.scrollToPos);
3095
      }
3096
      var sPos = calculateScrollPos(this, coords.left, coords.top - margin, coords.right, coords.bottom + margin);
3097
      updateScrollPos(this, sPos.scrollLeft, sPos.scrollTop);
3098
    }),
3099
3100
    setSize: function(width, height) {
3101
      function interpret(val) {
3102
        return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
3103
      }
3104
      if (width != null) this.display.wrapper.style.width = interpret(width);
3105
      if (height != null) this.display.wrapper.style.height = interpret(height);
3106
      this.refresh();
3107
    },
3108
3109
    on: function(type, f) {on(this, type, f);},
3110
    off: function(type, f) {off(this, type, f);},
3111
3112
    operation: function(f){return runInOp(this, f);},
3113
3114
    refresh: operation(null, function() {
3115
      clearCaches(this);
3116
      updateScrollPos(this, this.doc.scrollLeft, this.doc.scrollTop);
3117
      regChange(this);
3118
    }),
3119
3120
    swapDoc: operation(null, function(doc) {
3121
      var old = this.doc;
3122
      old.cm = null;
3123
      attachDoc(this, doc);
3124
      clearCaches(this);
3125
      resetInput(this, true);
3126
      updateScrollPos(this, doc.scrollLeft, doc.scrollTop);
3127
      return old;
3128
    }),
3129
3130
    getInputField: function(){return this.display.input;},
3131
    getWrapperElement: function(){return this.display.wrapper;},
3132
    getScrollerElement: function(){return this.display.scroller;},
3133
    getGutterElement: function(){return this.display.gutters;}
3134
  };
3135
3136
  // OPTION DEFAULTS
3137
3138
  var optionHandlers = CodeMirror.optionHandlers = {};
3139
3140
  // The default configuration options.
3141
  var defaults = CodeMirror.defaults = {};
3142
3143
  function option(name, deflt, handle, notOnInit) {
3144
    CodeMirror.defaults[name] = deflt;
3145
    if (handle) optionHandlers[name] =
3146
      notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
3147
  }
3148
3149
  var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
3150
3151
  // These two are, on init, called from the constructor because they
3152
  // have to be initialized before the editor can start at all.
3153
  option("value", "", function(cm, val) {
3154
    cm.setValue(val);
3155
  }, true);
3156
  option("mode", null, function(cm, val) {
3157
    cm.doc.modeOption = val;
3158
    loadMode(cm);
3159
  }, true);
3160
3161
  option("indentUnit", 2, loadMode, true);
3162
  option("indentWithTabs", false);
3163
  option("smartIndent", true);
3164
  option("tabSize", 4, function(cm) {
3165
    loadMode(cm);
3166
    clearCaches(cm);
3167
    regChange(cm);
3168
  }, true);
3169
  option("electricChars", true);
3170
  option("rtlMoveVisually", !windows);
3171
3172
  option("theme", "default", function(cm) {
3173
    themeChanged(cm);
3174
    guttersChanged(cm);
3175
  }, true);
3176
  option("keyMap", "default", keyMapChanged);
3177
  option("extraKeys", null);
3178
3179
  option("onKeyEvent", null);
3180
  option("onDragEvent", null);
3181
3182
  option("lineWrapping", false, wrappingChanged, true);
3183
  option("gutters", [], function(cm) {
3184
    setGuttersForLineNumbers(cm.options);
3185
    guttersChanged(cm);
3186
  }, true);
3187
  option("fixedGutter", true, function(cm, val) {
3188
    cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
3189
    cm.refresh();
3190
  }, true);
3191
  option("coverGutterNextToScrollbar", false, updateScrollbars, true);
3192
  option("lineNumbers", false, function(cm) {
3193
    setGuttersForLineNumbers(cm.options);
3194
    guttersChanged(cm);
3195
  }, true);
3196
  option("firstLineNumber", 1, guttersChanged, true);
3197
  option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
3198
  option("showCursorWhenSelecting", false, updateSelection, true);
3199
3200
  option("readOnly", false, function(cm, val) {
3201
    if (val == "nocursor") {onBlur(cm); cm.display.input.blur();}
3202
    else if (!val) resetInput(cm, true);
3203
  });
3204
  option("dragDrop", true);
3205
3206
  option("cursorBlinkRate", 530);
3207
  option("cursorScrollMargin", 0);
3208
  option("cursorHeight", 1);
3209
  option("workTime", 100);
3210
  option("workDelay", 100);
3211
  option("flattenSpans", true);
3212
  option("pollInterval", 100);
3213
  option("undoDepth", 40, function(cm, val){cm.doc.history.undoDepth = val;});
3214
  option("historyEventDelay", 500);
3215
  option("viewportMargin", 10, function(cm){cm.refresh();}, true);
3216
  option("maxHighlightLength", 10000, function(cm){loadMode(cm); cm.refresh();}, true);
3217
  option("moveInputWithCursor", true, function(cm, val) {
3218
    if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0;
3219
  });
3220
3221
  option("tabindex", null, function(cm, val) {
3222
    cm.display.input.tabIndex = val || "";
3223
  });
3224
  option("autofocus", null);
3225
3226
  // MODE DEFINITION AND QUERYING
3227
3228
  // Known modes, by name and by MIME
3229
  var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
3230
3231
  CodeMirror.defineMode = function(name, mode) {
3232
    if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
3233
    if (arguments.length > 2) {
3234
      mode.dependencies = [];
3235
      for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
3236
    }
3237
    modes[name] = mode;
3238
  };
3239
3240
  CodeMirror.defineMIME = function(mime, spec) {
3241
    mimeModes[mime] = spec;
3242
  };
3243
3244
  CodeMirror.resolveMode = function(spec) {
3245
    if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
3246
      spec = mimeModes[spec];
3247
    } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
3248
      var found = mimeModes[spec.name];
3249
      spec = createObj(found, spec);
3250
      spec.name = found.name;
3251
    } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
3252
      return CodeMirror.resolveMode("application/xml");
3253
    }
3254
    if (typeof spec == "string") return {name: spec};
3255
    else return spec || {name: "null"};
3256
  };
3257
3258
  CodeMirror.getMode = function(options, spec) {
3259
    spec = CodeMirror.resolveMode(spec);
3260
    var mfactory = modes[spec.name];
3261
    if (!mfactory) return CodeMirror.getMode(options, "text/plain");
3262
    var modeObj = mfactory(options, spec);
3263
    if (modeExtensions.hasOwnProperty(spec.name)) {
3264
      var exts = modeExtensions[spec.name];
3265
      for (var prop in exts) {
3266
        if (!exts.hasOwnProperty(prop)) continue;
3267
        if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
3268
        modeObj[prop] = exts[prop];
3269
      }
3270
    }
3271
    modeObj.name = spec.name;
3272
    return modeObj;
3273
  };
3274
3275
  CodeMirror.defineMode("null", function() {
3276
    return {token: function(stream) {stream.skipToEnd();}};
3277
  });
3278
  CodeMirror.defineMIME("text/plain", "null");
3279
3280
  var modeExtensions = CodeMirror.modeExtensions = {};
3281
  CodeMirror.extendMode = function(mode, properties) {
3282
    var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
3283
    copyObj(properties, exts);
3284
  };
3285
3286
  // EXTENSIONS
3287
3288
  CodeMirror.defineExtension = function(name, func) {
3289
    CodeMirror.prototype[name] = func;
3290
  };
3291
  CodeMirror.defineDocExtension = function(name, func) {
3292
    Doc.prototype[name] = func;
3293
  };
3294
  CodeMirror.defineOption = option;
3295
3296
  var initHooks = [];
3297
  CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
3298
3299
  // MODE STATE HANDLING
3300
3301
  // Utility functions for working with state. Exported because modes
3302
  // sometimes need to do this.
3303
  function copyState(mode, state) {
3304
    if (state === true) return state;
3305
    if (mode.copyState) return mode.copyState(state);
3306
    var nstate = {};
3307
    for (var n in state) {
3308
      var val = state[n];
3309
      if (val instanceof Array) val = val.concat([]);
3310
      nstate[n] = val;
3311
    }
3312
    return nstate;
3313
  }
3314
  CodeMirror.copyState = copyState;
3315
3316
  function startState(mode, a1, a2) {
3317
    return mode.startState ? mode.startState(a1, a2) : true;
3318
  }
3319
  CodeMirror.startState = startState;
3320
3321
  CodeMirror.innerMode = function(mode, state) {
3322
    while (mode.innerMode) {
3323
      var info = mode.innerMode(state);
3324
      state = info.state;
3325
      mode = info.mode;
3326
    }
3327
    return info || {mode: mode, state: state};
3328
  };
3329
3330
  // STANDARD COMMANDS
3331
3332
  var commands = CodeMirror.commands = {
3333
    selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()));},
3334
    killLine: function(cm) {
3335
      var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
3336
      if (!sel && cm.getLine(from.line).length == from.ch)
3337
        cm.replaceRange("", from, Pos(from.line + 1, 0), "+delete");
3338
      else cm.replaceRange("", from, sel ? to : Pos(from.line), "+delete");
3339
    },
3340
    deleteLine: function(cm) {
3341
      var l = cm.getCursor().line;
3342
      cm.replaceRange("", Pos(l, 0), Pos(l), "+delete");
3343
    },
3344
    delLineLeft: function(cm) {
3345
      var cur = cm.getCursor();
3346
      cm.replaceRange("", Pos(cur.line, 0), cur, "+delete");
3347
    },
3348
    undo: function(cm) {cm.undo();},
3349
    redo: function(cm) {cm.redo();},
3350
    goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
3351
    goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
3352
    goLineStart: function(cm) {
3353
      cm.extendSelection(lineStart(cm, cm.getCursor().line));
3354
    },
3355
    goLineStartSmart: function(cm) {
3356
      var cur = cm.getCursor(), start = lineStart(cm, cur.line);
3357
      var line = cm.getLineHandle(start.line);
3358
      var order = getOrder(line);
3359
      if (!order || order[0].level == 0) {
3360
        var firstNonWS = Math.max(0, line.text.search(/\S/));
3361
        var inWS = cur.line == start.line && cur.ch <= firstNonWS && cur.ch;
3362
        cm.extendSelection(Pos(start.line, inWS ? 0 : firstNonWS));
3363
      } else cm.extendSelection(start);
3364
    },
3365
    goLineEnd: function(cm) {
3366
      cm.extendSelection(lineEnd(cm, cm.getCursor().line));
3367
    },
3368
    goLineRight: function(cm) {
3369
      var top = cm.charCoords(cm.getCursor(), "div").top + 5;
3370
      cm.extendSelection(cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"));
3371
    },
3372
    goLineLeft: function(cm) {
3373
      var top = cm.charCoords(cm.getCursor(), "div").top + 5;
3374
      cm.extendSelection(cm.coordsChar({left: 0, top: top}, "div"));
3375
    },
3376
    goLineUp: function(cm) {cm.moveV(-1, "line");},
3377
    goLineDown: function(cm) {cm.moveV(1, "line");},
3378
    goPageUp: function(cm) {cm.moveV(-1, "page");},
3379
    goPageDown: function(cm) {cm.moveV(1, "page");},
3380
    goCharLeft: function(cm) {cm.moveH(-1, "char");},
3381
    goCharRight: function(cm) {cm.moveH(1, "char");},
3382
    goColumnLeft: function(cm) {cm.moveH(-1, "column");},
3383
    goColumnRight: function(cm) {cm.moveH(1, "column");},
3384
    goWordLeft: function(cm) {cm.moveH(-1, "word");},
3385
    goGroupRight: function(cm) {cm.moveH(1, "group");},
3386
    goGroupLeft: function(cm) {cm.moveH(-1, "group");},
3387
    goWordRight: function(cm) {cm.moveH(1, "word");},
3388
    delCharBefore: function(cm) {cm.deleteH(-1, "char");},
3389
    delCharAfter: function(cm) {cm.deleteH(1, "char");},
3390
    delWordBefore: function(cm) {cm.deleteH(-1, "word");},
3391
    delWordAfter: function(cm) {cm.deleteH(1, "word");},
3392
    delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
3393
    delGroupAfter: function(cm) {cm.deleteH(1, "group");},
3394
    indentAuto: function(cm) {cm.indentSelection("smart");},
3395
    indentMore: function(cm) {cm.indentSelection("add");},
3396
    indentLess: function(cm) {cm.indentSelection("subtract");},
3397
    insertTab: function(cm) {cm.replaceSelection("\t", "end", "+input");},
3398
    defaultTab: function(cm) {
3399
      if (cm.somethingSelected()) cm.indentSelection("add");
3400
      else cm.replaceSelection("\t", "end", "+input");
3401
    },
3402
    transposeChars: function(cm) {
3403
      var cur = cm.getCursor(), line = cm.getLine(cur.line);
3404
      if (cur.ch > 0 && cur.ch < line.length - 1)
3405
        cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1),
3406
                        Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1));
3407
    },
3408
    newlineAndIndent: function(cm) {
3409
      operation(cm, function() {
3410
        cm.replaceSelection("\n", "end", "+input");
3411
        cm.indentLine(cm.getCursor().line, null, true);
3412
      })();
3413
    },
3414
    toggleOverwrite: function(cm) {cm.toggleOverwrite();}
3415
  };
3416
3417
  // STANDARD KEYMAPS
3418
3419
  var keyMap = CodeMirror.keyMap = {};
3420
  keyMap.basic = {
3421
    "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
3422
    "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
3423
    "Delete": "delCharAfter", "Backspace": "delCharBefore", "Tab": "defaultTab", "Shift-Tab": "indentAuto",
3424
    "Enter": "newlineAndIndent", "Insert": "toggleOverwrite"
3425
  };
3426
  // Note that the save and find-related commands aren't defined by
3427
  // default. Unknown commands are simply ignored.
3428
  keyMap.pcDefault = {
3429
    "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
3430
    "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
3431
    "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
3432
    "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
3433
    "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
3434
    "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
3435
    fallthrough: "basic"
3436
  };
3437
  keyMap.macDefault = {
3438
    "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
3439
    "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
3440
    "Alt-Right": "goGroupRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delGroupBefore",
3441
    "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
3442
    "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
3443
    "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delLineLeft",
3444
    fallthrough: ["basic", "emacsy"]
3445
  };
3446
  keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
3447
  keyMap.emacsy = {
3448
    "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
3449
    "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
3450
    "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
3451
    "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
3452
  };
3453
3454
  // KEYMAP DISPATCH
3455
3456
  function getKeyMap(val) {
3457
    if (typeof val == "string") return keyMap[val];
3458
    else return val;
3459
  }
3460
3461
  function lookupKey(name, maps, handle) {
3462
    function lookup(map) {
3463
      map = getKeyMap(map);
3464
      var found = map[name];
3465
      if (found === false) return "stop";
3466
      if (found != null && handle(found)) return true;
3467
      if (map.nofallthrough) return "stop";
3468
3469
      var fallthrough = map.fallthrough;
3470
      if (fallthrough == null) return false;
3471
      if (Object.prototype.toString.call(fallthrough) != "[object Array]")
3472
        return lookup(fallthrough);
3473
      for (var i = 0, e = fallthrough.length; i < e; ++i) {
3474
        var done = lookup(fallthrough[i]);
3475
        if (done) return done;
3476
      }
3477
      return false;
3478
    }
3479
3480
    for (var i = 0; i < maps.length; ++i) {
3481
      var done = lookup(maps[i]);
3482
      if (done) return done != "stop";
3483
    }
3484
  }
3485
  function isModifierKey(event) {
3486
    var name = keyNames[event.keyCode];
3487
    return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
3488
  }
3489
  function keyName(event, noShift) {
3490
    if (opera && event.keyCode == 34 && event["char"]) return false;
3491
    var name = keyNames[event.keyCode];
3492
    if (name == null || event.altGraphKey) return false;
3493
    if (event.altKey) name = "Alt-" + name;
3494
    if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name;
3495
    if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name;
3496
    if (!noShift && event.shiftKey) name = "Shift-" + name;
3497
    return name;
3498
  }
3499
  CodeMirror.lookupKey = lookupKey;
3500
  CodeMirror.isModifierKey = isModifierKey;
3501
  CodeMirror.keyName = keyName;
3502
3503
  // FROMTEXTAREA
3504
3505
  CodeMirror.fromTextArea = function(textarea, options) {
3506
    if (!options) options = {};
3507
    options.value = textarea.value;
3508
    if (!options.tabindex && textarea.tabindex)
3509
      options.tabindex = textarea.tabindex;
3510
    if (!options.placeholder && textarea.placeholder)
3511
      options.placeholder = textarea.placeholder;
3512
    // Set autofocus to true if this textarea is focused, or if it has
3513
    // autofocus and no other element is focused.
3514
    if (options.autofocus == null) {
3515
      var hasFocus = document.body;
3516
      // doc.activeElement occasionally throws on IE
3517
      try { hasFocus = document.activeElement; } catch(e) {}
3518
      options.autofocus = hasFocus == textarea ||
3519
        textarea.getAttribute("autofocus") != null && hasFocus == document.body;
3520
    }
3521
3522
    function save() {textarea.value = cm.getValue();}
3523
    if (textarea.form) {
3524
      on(textarea.form, "submit", save);
3525
      // Deplorable hack to make the submit method do the right thing.
3526
      if (!options.leaveSubmitMethodAlone) {
3527
        var form = textarea.form, realSubmit = form.submit;
3528
        try {
3529
          var wrappedSubmit = form.submit = function() {
3530
            save();
3531
            form.submit = realSubmit;
3532
            form.submit();
3533
            form.submit = wrappedSubmit;
3534
          };
3535
        } catch(e) {}
3536
      }
3537
    }
3538
3539
    textarea.style.display = "none";
3540
    var cm = CodeMirror(function(node) {
3541
      textarea.parentNode.insertBefore(node, textarea.nextSibling);
3542
    }, options);
3543
    cm.save = save;
3544
    cm.getTextArea = function() { return textarea; };
3545
    cm.toTextArea = function() {
3546
      save();
3547
      textarea.parentNode.removeChild(cm.getWrapperElement());
3548
      textarea.style.display = "";
3549
      if (textarea.form) {
3550
        off(textarea.form, "submit", save);
3551
        if (typeof textarea.form.submit == "function")
3552
          textarea.form.submit = realSubmit;
3553
      }
3554
    };
3555
    return cm;
3556
  };
3557
3558
  // STRING STREAM
3559
3560
  // Fed to the mode parsers, provides helper functions to make
3561
  // parsers more succinct.
3562
3563
  // The character stream used by a mode's parser.
3564
  function StringStream(string, tabSize) {
3565
    this.pos = this.start = 0;
3566
    this.string = string;
3567
    this.tabSize = tabSize || 8;
3568
    this.lastColumnPos = this.lastColumnValue = 0;
3569
  }
3570
3571
  StringStream.prototype = {
3572
    eol: function() {return this.pos >= this.string.length;},
3573
    sol: function() {return this.pos == 0;},
3574
    peek: function() {return this.string.charAt(this.pos) || undefined;},
3575
    next: function() {
3576
      if (this.pos < this.string.length)
3577
        return this.string.charAt(this.pos++);
3578
    },
3579
    eat: function(match) {
3580
      var ch = this.string.charAt(this.pos);
3581
      if (typeof match == "string") var ok = ch == match;
3582
      else var ok = ch && (match.test ? match.test(ch) : match(ch));
3583
      if (ok) {++this.pos; return ch;}
3584
    },
3585
    eatWhile: function(match) {
3586
      var start = this.pos;
3587
      while (this.eat(match)){}
3588
      return this.pos > start;
3589
    },
3590
    eatSpace: function() {
3591
      var start = this.pos;
3592
      while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
3593
      return this.pos > start;
3594
    },
3595
    skipToEnd: function() {this.pos = this.string.length;},
3596
    skipTo: function(ch) {
3597
      var found = this.string.indexOf(ch, this.pos);
3598
      if (found > -1) {this.pos = found; return true;}
3599
    },
3600
    backUp: function(n) {this.pos -= n;},
3601
    column: function() {
3602
      if (this.lastColumnPos < this.start) {
3603
        this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
3604
        this.lastColumnPos = this.start;
3605
      }
3606
      return this.lastColumnValue;
3607
    },
3608
    indentation: function() {return countColumn(this.string, null, this.tabSize);},
3609
    match: function(pattern, consume, caseInsensitive) {
3610
      if (typeof pattern == "string") {
3611
        var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
3612
        var substr = this.string.substr(this.pos, pattern.length);
3613
        if (cased(substr) == cased(pattern)) {
3614
          if (consume !== false) this.pos += pattern.length;
3615
          return true;
3616
        }
3617
      } else {
3618
        var match = this.string.slice(this.pos).match(pattern);
3619
        if (match && match.index > 0) return null;
3620
        if (match && consume !== false) this.pos += match[0].length;
3621
        return match;
3622
      }
3623
    },
3624
    current: function(){return this.string.slice(this.start, this.pos);}
3625
  };
3626
  CodeMirror.StringStream = StringStream;
3627
3628
  // TEXTMARKERS
3629
3630
  function TextMarker(doc, type) {
3631
    this.lines = [];
3632
    this.type = type;
3633
    this.doc = doc;
3634
  }
3635
  CodeMirror.TextMarker = TextMarker;
3636
3637
  TextMarker.prototype.clear = function() {
3638
    if (this.explicitlyCleared) return;
3639
    var cm = this.doc.cm, withOp = cm && !cm.curOp;
3640
    if (withOp) startOperation(cm);
3641
    var min = null, max = null;
3642
    for (var i = 0; i < this.lines.length; ++i) {
3643
      var line = this.lines[i];
3644
      var span = getMarkedSpanFor(line.markedSpans, this);
3645
      if (span.to != null) max = lineNo(line);
3646
      line.markedSpans = removeMarkedSpan(line.markedSpans, span);
3647
      if (span.from != null)
3648
        min = lineNo(line);
3649
      else if (this.collapsed && !lineIsHidden(this.doc, line) && cm)
3650
        updateLineHeight(line, textHeight(cm.display));
3651
    }
3652
    if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
3653
      var visual = visualLine(cm.doc, this.lines[i]), len = lineLength(cm.doc, visual);
3654
      if (len > cm.display.maxLineLength) {
3655
        cm.display.maxLine = visual;
3656
        cm.display.maxLineLength = len;
3657
        cm.display.maxLineChanged = true;
3658
      }
3659
    }
3660
3661
    if (min != null && cm) regChange(cm, min, max + 1);
3662
    this.lines.length = 0;
3663
    this.explicitlyCleared = true;
3664
    if (this.atomic && this.doc.cantEdit) {
3665
      this.doc.cantEdit = false;
3666
      if (cm) reCheckSelection(cm);
3667
    }
3668
    if (withOp) endOperation(cm);
3669
    signalLater(this, "clear");
3670
  };
3671
3672
  TextMarker.prototype.find = function() {
3673
    var from, to;
3674
    for (var i = 0; i < this.lines.length; ++i) {
3675
      var line = this.lines[i];
3676
      var span = getMarkedSpanFor(line.markedSpans, this);
3677
      if (span.from != null || span.to != null) {
3678
        var found = lineNo(line);
3679
        if (span.from != null) from = Pos(found, span.from);
3680
        if (span.to != null) to = Pos(found, span.to);
3681
      }
3682
    }
3683
    if (this.type == "bookmark") return from;
3684
    return from && {from: from, to: to};
3685
  };
3686
3687
  TextMarker.prototype.changed = function() {
3688
    var pos = this.find(), cm = this.doc.cm;
3689
    if (!pos || !cm) return;
3690
    var line = getLine(this.doc, pos.from.line);
3691
    clearCachedMeasurement(cm, line);
3692
    if (pos.from.line >= cm.display.showingFrom && pos.from.line < cm.display.showingTo) {
3693
      for (var node = cm.display.lineDiv.firstChild; node; node = node.nextSibling) if (node.lineObj == line) {
3694
        if (node.offsetHeight != line.height) updateLineHeight(line, node.offsetHeight);
3695
        break;
3696
      }
3697
      runInOp(cm, function() { cm.curOp.selectionChanged = true; });
3698
    }
3699
  };
3700
3701
  TextMarker.prototype.attachLine = function(line) {
3702
    if (!this.lines.length && this.doc.cm) {
3703
      var op = this.doc.cm.curOp;
3704
      if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
3705
        (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
3706
    }
3707
    this.lines.push(line);
3708
  };
3709
  TextMarker.prototype.detachLine = function(line) {
3710
    this.lines.splice(indexOf(this.lines, line), 1);
3711
    if (!this.lines.length && this.doc.cm) {
3712
      var op = this.doc.cm.curOp;
3713
      (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
3714
    }
3715
  };
3716
3717
  function markText(doc, from, to, options, type) {
3718
    if (options && options.shared) return markTextShared(doc, from, to, options, type);
3719
    if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
3720
3721
    var marker = new TextMarker(doc, type);
3722
    if (type == "range" && !posLess(from, to)) return marker;
3723
    if (options) copyObj(options, marker);
3724
    if (marker.replacedWith) {
3725
      marker.collapsed = true;
3726
      marker.replacedWith = elt("span", [marker.replacedWith], "CodeMirror-widget");
3727
      if (!options.handleMouseEvents) marker.replacedWith.ignoreEvents = true;
3728
    }
3729
    if (marker.collapsed) sawCollapsedSpans = true;
3730
3731
    if (marker.addToHistory)
3732
      addToHistory(doc, {from: from, to: to, origin: "markText"},
3733
                   {head: doc.sel.head, anchor: doc.sel.anchor}, NaN);
3734
3735
    var curLine = from.line, size = 0, collapsedAtStart, collapsedAtEnd, cm = doc.cm, updateMaxLine;
3736
    doc.iter(curLine, to.line + 1, function(line) {
3737
      if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(doc, line) == cm.display.maxLine)
3738
        updateMaxLine = true;
3739
      var span = {from: null, to: null, marker: marker};
3740
      size += line.text.length;
3741
      if (curLine == from.line) {span.from = from.ch; size -= from.ch;}
3742
      if (curLine == to.line) {span.to = to.ch; size -= line.text.length - to.ch;}
3743
      if (marker.collapsed) {
3744
        if (curLine == to.line) collapsedAtEnd = collapsedSpanAt(line, to.ch);
3745
        if (curLine == from.line) collapsedAtStart = collapsedSpanAt(line, from.ch);
3746
        else updateLineHeight(line, 0);
3747
      }
3748
      addMarkedSpan(line, span);
3749
      ++curLine;
3750
    });
3751
    if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
3752
      if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
3753
    });
3754
3755
    if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
3756
3757
    if (marker.readOnly) {
3758
      sawReadOnlySpans = true;
3759
      if (doc.history.done.length || doc.history.undone.length)
3760
        doc.clearHistory();
3761
    }
3762
    if (marker.collapsed) {
3763
      if (collapsedAtStart != collapsedAtEnd)
3764
        throw new Error("Inserting collapsed marker overlapping an existing one");
3765
      marker.size = size;
3766
      marker.atomic = true;
3767
    }
3768
    if (cm) {
3769
      if (updateMaxLine) cm.curOp.updateMaxLine = true;
3770
      if (marker.className || marker.startStyle || marker.endStyle || marker.collapsed)
3771
        regChange(cm, from.line, to.line + 1);
3772
      if (marker.atomic) reCheckSelection(cm);
3773
    }
3774
    return marker;
3775
  }
3776
3777
  // SHARED TEXTMARKERS
3778
3779
  function SharedTextMarker(markers, primary) {
3780
    this.markers = markers;
3781
    this.primary = primary;
3782
    for (var i = 0, me = this; i < markers.length; ++i) {
3783
      markers[i].parent = this;
3784
      on(markers[i], "clear", function(){me.clear();});
3785
    }
3786
  }
3787
  CodeMirror.SharedTextMarker = SharedTextMarker;
3788
3789
  SharedTextMarker.prototype.clear = function() {
3790
    if (this.explicitlyCleared) return;
3791
    this.explicitlyCleared = true;
3792
    for (var i = 0; i < this.markers.length; ++i)
3793
      this.markers[i].clear();
3794
    signalLater(this, "clear");
3795
  };
3796
  SharedTextMarker.prototype.find = function() {
3797
    return this.primary.find();
3798
  };
3799
3800
  function markTextShared(doc, from, to, options, type) {
3801
    options = copyObj(options);
3802
    options.shared = false;
3803
    var markers = [markText(doc, from, to, options, type)], primary = markers[0];
3804
    var widget = options.replacedWith;
3805
    linkedDocs(doc, function(doc) {
3806
      if (widget) options.replacedWith = widget.cloneNode(true);
3807
      markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
3808
      for (var i = 0; i < doc.linked.length; ++i)
3809
        if (doc.linked[i].isParent) return;
3810
      primary = lst(markers);
3811
    });
3812
    return new SharedTextMarker(markers, primary);
3813
  }
3814
3815
  // TEXTMARKER SPANS
3816
3817
  function getMarkedSpanFor(spans, marker) {
3818
    if (spans) for (var i = 0; i < spans.length; ++i) {
3819
      var span = spans[i];
3820
      if (span.marker == marker) return span;
3821
    }
3822
  }
3823
  function removeMarkedSpan(spans, span) {
3824
    for (var r, i = 0; i < spans.length; ++i)
3825
      if (spans[i] != span) (r || (r = [])).push(spans[i]);
3826
    return r;
3827
  }
3828
  function addMarkedSpan(line, span) {
3829
    line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
3830
    span.marker.attachLine(line);
3831
  }
3832
3833
  function markedSpansBefore(old, startCh, isInsert) {
3834
    if (old) for (var i = 0, nw; i < old.length; ++i) {
3835
      var span = old[i], marker = span.marker;
3836
      var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
3837
      if (startsBefore || marker.type == "bookmark" && span.from == startCh && (!isInsert || !span.marker.insertLeft)) {
3838
        var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
3839
        (nw || (nw = [])).push({from: span.from,
3840
                                to: endsAfter ? null : span.to,
3841
                                marker: marker});
3842
      }
3843
    }
3844
    return nw;
3845
  }
3846
3847
  function markedSpansAfter(old, endCh, isInsert) {
3848
    if (old) for (var i = 0, nw; i < old.length; ++i) {
3849
      var span = old[i], marker = span.marker;
3850
      var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
3851
      if (endsAfter || marker.type == "bookmark" && span.from == endCh && (!isInsert || span.marker.insertLeft)) {
3852
        var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
3853
        (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh,
3854
                                to: span.to == null ? null : span.to - endCh,
3855
                                marker: marker});
3856
      }
3857
    }
3858
    return nw;
3859
  }
3860
3861
  function stretchSpansOverChange(doc, change) {
3862
    var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
3863
    var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
3864
    if (!oldFirst && !oldLast) return null;
3865
3866
    var startCh = change.from.ch, endCh = change.to.ch, isInsert = posEq(change.from, change.to);
3867
    // Get the spans that 'stick out' on both sides
3868
    var first = markedSpansBefore(oldFirst, startCh, isInsert);
3869
    var last = markedSpansAfter(oldLast, endCh, isInsert);
3870
3871
    // Next, merge those two ends
3872
    var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
3873
    if (first) {
3874
      // Fix up .to properties of first
3875
      for (var i = 0; i < first.length; ++i) {
3876
        var span = first[i];
3877
        if (span.to == null) {
3878
          var found = getMarkedSpanFor(last, span.marker);
3879
          if (!found) span.to = startCh;
3880
          else if (sameLine) span.to = found.to == null ? null : found.to + offset;
3881
        }
3882
      }
3883
    }
3884
    if (last) {
3885
      // Fix up .from in last (or move them into first in case of sameLine)
3886
      for (var i = 0; i < last.length; ++i) {
3887
        var span = last[i];
3888
        if (span.to != null) span.to += offset;
3889
        if (span.from == null) {
3890
          var found = getMarkedSpanFor(first, span.marker);
3891
          if (!found) {
3892
            span.from = offset;
3893
            if (sameLine) (first || (first = [])).push(span);
3894
          }
3895
        } else {
3896
          span.from += offset;
3897
          if (sameLine) (first || (first = [])).push(span);
3898
        }
3899
      }
3900
    }
3901
    if (sameLine && first) {
3902
      // Make sure we didn't create any zero-length spans
3903
      for (var i = 0; i < first.length; ++i)
3904
        if (first[i].from != null && first[i].from == first[i].to && first[i].marker.type != "bookmark")
3905
          first.splice(i--, 1);
3906
      if (!first.length) first = null;
3907
    }
3908
3909
    var newMarkers = [first];
3910
    if (!sameLine) {
3911
      // Fill gap with whole-line-spans
3912
      var gap = change.text.length - 2, gapMarkers;
3913
      if (gap > 0 && first)
3914
        for (var i = 0; i < first.length; ++i)
3915
          if (first[i].to == null)
3916
            (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker});
3917
      for (var i = 0; i < gap; ++i)
3918
        newMarkers.push(gapMarkers);
3919
      newMarkers.push(last);
3920
    }
3921
    return newMarkers;
3922
  }
3923
3924
  function mergeOldSpans(doc, change) {
3925
    var old = getOldSpans(doc, change);
3926
    var stretched = stretchSpansOverChange(doc, change);
3927
    if (!old) return stretched;
3928
    if (!stretched) return old;
3929
3930
    for (var i = 0; i < old.length; ++i) {
3931
      var oldCur = old[i], stretchCur = stretched[i];
3932
      if (oldCur && stretchCur) {
3933
        spans: for (var j = 0; j < stretchCur.length; ++j) {
3934
          var span = stretchCur[j];
3935
          for (var k = 0; k < oldCur.length; ++k)
3936
            if (oldCur[k].marker == span.marker) continue spans;
3937
          oldCur.push(span);
3938
        }
3939
      } else if (stretchCur) {
3940
        old[i] = stretchCur;
3941
      }
3942
    }
3943
    return old;
3944
  }
3945
3946
  function removeReadOnlyRanges(doc, from, to) {
3947
    var markers = null;
3948
    doc.iter(from.line, to.line + 1, function(line) {
3949
      if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
3950
        var mark = line.markedSpans[i].marker;
3951
        if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
3952
          (markers || (markers = [])).push(mark);
3953
      }
3954
    });
3955
    if (!markers) return null;
3956
    var parts = [{from: from, to: to}];
3957
    for (var i = 0; i < markers.length; ++i) {
3958
      var mk = markers[i], m = mk.find();
3959
      for (var j = 0; j < parts.length; ++j) {
3960
        var p = parts[j];
3961
        if (posLess(p.to, m.from) || posLess(m.to, p.from)) continue;
3962
        var newParts = [j, 1];
3963
        if (posLess(p.from, m.from) || !mk.inclusiveLeft && posEq(p.from, m.from))
3964
          newParts.push({from: p.from, to: m.from});
3965
        if (posLess(m.to, p.to) || !mk.inclusiveRight && posEq(p.to, m.to))
3966
          newParts.push({from: m.to, to: p.to});
3967
        parts.splice.apply(parts, newParts);
3968
        j += newParts.length - 1;
3969
      }
3970
    }
3971
    return parts;
3972
  }
3973
3974
  function collapsedSpanAt(line, ch) {
3975
    var sps = sawCollapsedSpans && line.markedSpans, found;
3976
    if (sps) for (var sp, i = 0; i < sps.length; ++i) {
3977
      sp = sps[i];
3978
      if (!sp.marker.collapsed) continue;
3979
      if ((sp.from == null || sp.from < ch) &&
3980
          (sp.to == null || sp.to > ch) &&
3981
          (!found || found.width < sp.marker.width))
3982
        found = sp.marker;
3983
    }
3984
    return found;
3985
  }
3986
  function collapsedSpanAtStart(line) { return collapsedSpanAt(line, -1); }
3987
  function collapsedSpanAtEnd(line) { return collapsedSpanAt(line, line.text.length + 1); }
3988
3989
  function visualLine(doc, line) {
3990
    var merged;
3991
    while (merged = collapsedSpanAtStart(line))
3992
      line = getLine(doc, merged.find().from.line);
3993
    return line;
3994
  }
3995
3996
  function lineIsHidden(doc, line) {
3997
    var sps = sawCollapsedSpans && line.markedSpans;
3998
    if (sps) for (var sp, i = 0; i < sps.length; ++i) {
3999
      sp = sps[i];
4000
      if (!sp.marker.collapsed) continue;
4001
      if (sp.from == null) return true;
4002
      if (sp.marker.replacedWith) continue;
4003
      if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
4004
        return true;
4005
    }
4006
  }
4007
  function lineIsHiddenInner(doc, line, span) {
4008
    if (span.to == null) {
4009
      var end = span.marker.find().to, endLine = getLine(doc, end.line);
4010
      return lineIsHiddenInner(doc, endLine, getMarkedSpanFor(endLine.markedSpans, span.marker));
4011
    }
4012
    if (span.marker.inclusiveRight && span.to == line.text.length)
4013
      return true;
4014
    for (var sp, i = 0; i < line.markedSpans.length; ++i) {
4015
      sp = line.markedSpans[i];
4016
      if (sp.marker.collapsed && !sp.marker.replacedWith && sp.from == span.to &&
4017
          (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
4018
          lineIsHiddenInner(doc, line, sp)) return true;
4019
    }
4020
  }
4021
4022
  function detachMarkedSpans(line) {
4023
    var spans = line.markedSpans;
4024
    if (!spans) return;
4025
    for (var i = 0; i < spans.length; ++i)
4026
      spans[i].marker.detachLine(line);
4027
    line.markedSpans = null;
4028
  }
4029
4030
  function attachMarkedSpans(line, spans) {
4031
    if (!spans) return;
4032
    for (var i = 0; i < spans.length; ++i)
4033
      spans[i].marker.attachLine(line);
4034
    line.markedSpans = spans;
4035
  }
4036
4037
  // LINE WIDGETS
4038
4039
  var LineWidget = CodeMirror.LineWidget = function(cm, node, options) {
4040
    for (var opt in options) if (options.hasOwnProperty(opt))
4041
      this[opt] = options[opt];
4042
    this.cm = cm;
4043
    this.node = node;
4044
  };
4045
  function widgetOperation(f) {
4046
    return function() {
4047
      var withOp = !this.cm.curOp;
4048
      if (withOp) startOperation(this.cm);
4049
      try {var result = f.apply(this, arguments);}
4050
      finally {if (withOp) endOperation(this.cm);}
4051
      return result;
4052
    };
4053
  }
4054
  LineWidget.prototype.clear = widgetOperation(function() {
4055
    var ws = this.line.widgets, no = lineNo(this.line);
4056
    if (no == null || !ws) return;
4057
    for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
4058
    if (!ws.length) this.line.widgets = null;
4059
    updateLineHeight(this.line, Math.max(0, this.line.height - widgetHeight(this)));
4060
    regChange(this.cm, no, no + 1);
4061
  });
4062
  LineWidget.prototype.changed = widgetOperation(function() {
4063
    var oldH = this.height;
4064
    this.height = null;
4065
    var diff = widgetHeight(this) - oldH;
4066
    if (!diff) return;
4067
    updateLineHeight(this.line, this.line.height + diff);
4068
    var no = lineNo(this.line);
4069
    regChange(this.cm, no, no + 1);
4070
  });
4071
4072
  function widgetHeight(widget) {
4073
    if (widget.height != null) return widget.height;
4074
    if (!widget.node.parentNode || widget.node.parentNode.nodeType != 1)
4075
      removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, "position: relative"));
4076
    return widget.height = widget.node.offsetHeight;
4077
  }
4078
4079
  function addLineWidget(cm, handle, node, options) {
4080
    var widget = new LineWidget(cm, node, options);
4081
    if (widget.noHScroll) cm.display.alignWidgets = true;
4082
    changeLine(cm, handle, function(line) {
4083
      (line.widgets || (line.widgets = [])).push(widget);
4084
      widget.line = line;
4085
      if (!lineIsHidden(cm.doc, line) || widget.showIfHidden) {
4086
        var aboveVisible = heightAtLine(cm, line) < cm.display.scroller.scrollTop;
4087
        updateLineHeight(line, line.height + widgetHeight(widget));
4088
        if (aboveVisible) addToScrollPos(cm, 0, widget.height);
4089
      }
4090
      return true;
4091
    });
4092
    return widget;
4093
  }
4094
4095
  // LINE DATA STRUCTURE
4096
4097
  // Line objects. These hold state related to a line, including
4098
  // highlighting info (the styles array).
4099
  function makeLine(text, markedSpans, estimateHeight) {
4100
    var line = {text: text};
4101
    attachMarkedSpans(line, markedSpans);
4102
    line.height = estimateHeight ? estimateHeight(line) : 1;
4103
    return line;
4104
  }
4105
4106
  function updateLine(line, text, markedSpans, estimateHeight) {
4107
    line.text = text;
4108
    if (line.stateAfter) line.stateAfter = null;
4109
    if (line.styles) line.styles = null;
4110
    if (line.order != null) line.order = null;
4111
    detachMarkedSpans(line);
4112
    attachMarkedSpans(line, markedSpans);
4113
    var estHeight = estimateHeight ? estimateHeight(line) : 1;
4114
    if (estHeight != line.height) updateLineHeight(line, estHeight);
4115
  }
4116
4117
  function cleanUpLine(line) {
4118
    line.parent = null;
4119
    detachMarkedSpans(line);
4120
  }
4121
4122
  // Run the given mode's parser over a line, update the styles
4123
  // array, which contains alternating fragments of text and CSS
4124
  // classes.
4125
  function runMode(cm, text, mode, state, f) {
4126
    var flattenSpans = mode.flattenSpans;
4127
    if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
4128
    var curStart = 0, curStyle = null;
4129
    var stream = new StringStream(text, cm.options.tabSize), style;
4130
    if (text == "" && mode.blankLine) mode.blankLine(state);
4131
    while (!stream.eol()) {
4132
      if (stream.pos > cm.options.maxHighlightLength) {
4133
        flattenSpans = false;
4134
        // Webkit seems to refuse to render text nodes longer than 57444 characters
4135
        stream.pos = Math.min(text.length, stream.start + 50000);
4136
        style = null;
4137
      } else {
4138
        style = mode.token(stream, state);
4139
      }
4140
      if (!flattenSpans || curStyle != style) {
4141
        if (curStart < stream.start) f(stream.start, curStyle);
4142
        curStart = stream.start; curStyle = style;
4143
      }
4144
      stream.start = stream.pos;
4145
    }
4146
    if (curStart < stream.pos) f(stream.pos, curStyle);
4147
  }
4148
4149
  function highlightLine(cm, line, state) {
4150
    // A styles array always starts with a number identifying the
4151
    // mode/overlays that it is based on (for easy invalidation).
4152
    var st = [cm.state.modeGen];
4153
    // Compute the base array of styles
4154
    runMode(cm, line.text, cm.doc.mode, state, function(end, style) {st.push(end, style);});
4155
4156
    // Run overlays, adjust style array.
4157
    for (var o = 0; o < cm.state.overlays.length; ++o) {
4158
      var overlay = cm.state.overlays[o], i = 1, at = 0;
4159
      runMode(cm, line.text, overlay.mode, true, function(end, style) {
4160
        var start = i;
4161
        // Ensure there's a token end at the current position, and that i points at it
4162
        while (at < end) {
4163
          var i_end = st[i];
4164
          if (i_end > end)
4165
            st.splice(i, 1, end, st[i+1], i_end);
4166
          i += 2;
4167
          at = Math.min(end, i_end);
4168
        }
4169
        if (!style) return;
4170
        if (overlay.opaque) {
4171
          st.splice(start, i - start, end, style);
4172
          i = start + 2;
4173
        } else {
4174
          for (; start < i; start += 2) {
4175
            var cur = st[start+1];
4176
            st[start+1] = cur ? cur + " " + style : style;
4177
          }
4178
        }
4179
      });
4180
    }
4181
4182
    return st;
4183
  }
4184
4185
  function getLineStyles(cm, line) {
4186
    if (!line.styles || line.styles[0] != cm.state.modeGen)
4187
      line.styles = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
4188
    return line.styles;
4189
  }
4190
4191
  // Lightweight form of highlight -- proceed over this line and
4192
  // update state, but don't save a style array.
4193
  function processLine(cm, line, state) {
4194
    var mode = cm.doc.mode;
4195
    var stream = new StringStream(line.text, cm.options.tabSize);
4196
    if (line.text == "" && mode.blankLine) mode.blankLine(state);
4197
    while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) {
4198
      mode.token(stream, state);
4199
      stream.start = stream.pos;
4200
    }
4201
  }
4202
4203
  var styleToClassCache = {};
4204
  function styleToClass(style) {
4205
    if (!style) return null;
4206
    return styleToClassCache[style] ||
4207
      (styleToClassCache[style] = "cm-" + style.replace(/ +/g, " cm-"));
4208
  }
4209
4210
  function lineContent(cm, realLine, measure) {
4211
    var merged, line = realLine, empty = true;
4212
    while (merged = collapsedSpanAtStart(line))
4213
      line = getLine(cm.doc, merged.find().from.line);
4214
4215
    var builder = {pre: elt("pre"), col: 0, pos: 0, display: !measure,
4216
                   measure: null, measuredSomething: false, cm: cm};
4217
    if (line.textClass) builder.pre.className = line.textClass;
4218
4219
    do {
4220
      if (line.text) empty = false;
4221
      builder.measure = line == realLine && measure;
4222
      builder.pos = 0;
4223
      builder.addToken = builder.measure ? buildTokenMeasure : buildToken;
4224
      if ((ie || webkit) && cm.getOption("lineWrapping"))
4225
        builder.addToken = buildTokenSplitSpaces(builder.addToken);
4226
      var next = insertLineContent(line, builder, getLineStyles(cm, line));
4227
      if (measure && line == realLine && !builder.measuredSomething) {
4228
        measure[0] = builder.pre.appendChild(zeroWidthElement(cm.display.measure));
4229
        builder.measuredSomething = true;
4230
      }
4231
      if (next) line = getLine(cm.doc, next.to.line);
4232
    } while (next);
4233
4234
    if (measure && !builder.measuredSomething && !measure[0])
4235
      measure[0] = builder.pre.appendChild(empty ? elt("span", "\u00a0") : zeroWidthElement(cm.display.measure));
4236
    if (!builder.pre.firstChild && !lineIsHidden(cm.doc, realLine))
4237
      builder.pre.appendChild(document.createTextNode("\u00a0"));
4238
4239
    var order;
4240
    // Work around problem with the reported dimensions of single-char
4241
    // direction spans on IE (issue #1129). See also the comment in
4242
    // cursorCoords.
4243
    if (measure && ie && (order = getOrder(line))) {
4244
      var l = order.length - 1;
4245
      if (order[l].from == order[l].to) --l;
4246
      var last = order[l], prev = order[l - 1];
4247
      if (last.from + 1 == last.to && prev && last.level < prev.level) {
4248
        var span = measure[builder.pos - 1];
4249
        if (span) span.parentNode.insertBefore(span.measureRight = zeroWidthElement(cm.display.measure),
4250
                                               span.nextSibling);
4251
      }
4252
    }
4253
4254
    signal(cm, "renderLine", cm, realLine, builder.pre);
4255
    return builder.pre;
4256
  }
4257
4258
  var tokenSpecialChars = /[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\uFEFF]/g;
4259
  function buildToken(builder, text, style, startStyle, endStyle) {
4260
    if (!text) return;
4261
    if (!tokenSpecialChars.test(text)) {
4262
      builder.col += text.length;
4263
      var content = document.createTextNode(text);
4264
    } else {
4265
      var content = document.createDocumentFragment(), pos = 0;
4266
      while (true) {
4267
        tokenSpecialChars.lastIndex = pos;
4268
        var m = tokenSpecialChars.exec(text);
4269
        var skipped = m ? m.index - pos : text.length - pos;
4270
        if (skipped) {
4271
          content.appendChild(document.createTextNode(text.slice(pos, pos + skipped)));
4272
          builder.col += skipped;
4273
        }
4274
        if (!m) break;
4275
        pos += skipped + 1;
4276
        if (m[0] == "\t") {
4277
          var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
4278
          content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
4279
          builder.col += tabWidth;
4280
        } else {
4281
          var token = elt("span", "\u2022", "cm-invalidchar");
4282
          token.title = "\\u" + m[0].charCodeAt(0).toString(16);
4283
          content.appendChild(token);
4284
          builder.col += 1;
4285
        }
4286
      }
4287
    }
4288
    if (style || startStyle || endStyle || builder.measure) {
4289
      var fullStyle = style || "";
4290
      if (startStyle) fullStyle += startStyle;
4291
      if (endStyle) fullStyle += endStyle;
4292
      return builder.pre.appendChild(elt("span", [content], fullStyle));
4293
    }
4294
    builder.pre.appendChild(content);
4295
  }
4296
4297
  function buildTokenMeasure(builder, text, style, startStyle, endStyle) {
4298
    var wrapping = builder.cm.options.lineWrapping;
4299
    for (var i = 0; i < text.length; ++i) {
4300
      var ch = text.charAt(i), start = i == 0;
4301
      if (ch >= "\ud800" && ch < "\udbff" && i < text.length - 1) {
4302
        ch = text.slice(i, i + 2);
4303
        ++i;
4304
      } else if (i && wrapping && spanAffectsWrapping(text, i)) {
4305
        builder.pre.appendChild(elt("wbr"));
4306
      }
4307
      var span = builder.measure[builder.pos] =
4308
        buildToken(builder, ch, style,
4309
                   start && startStyle, i == text.length - 1 && endStyle);
4310
      // In IE single-space nodes wrap differently than spaces
4311
      // embedded in larger text nodes, except when set to
4312
      // white-space: normal (issue #1268).
4313
      if (ie && wrapping && ch == " " && i && !/\s/.test(text.charAt(i - 1)) &&
4314
          i < text.length - 1 && !/\s/.test(text.charAt(i + 1)))
4315
        span.style.whiteSpace = "normal";
4316
      builder.pos += ch.length;
4317
    }
4318
    if (text.length) builder.measuredSomething = true;
4319
  }
4320
4321
  function buildTokenSplitSpaces(inner) {
4322
    function split(old) {
4323
      var out = " ";
4324
      for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
4325
      out += " ";
4326
      return out;
4327
    }
4328
    return function(builder, text, style, startStyle, endStyle) {
4329
      return inner(builder, text.replace(/ {3,}/, split), style, startStyle, endStyle);
4330
    };
4331
  }
4332
4333
  function buildCollapsedSpan(builder, size, widget) {
4334
    if (widget) {
4335
      if (!builder.display) widget = widget.cloneNode(true);
4336
      if (builder.measure) {
4337
        builder.measure[builder.pos] = size ? widget
4338
          : builder.pre.appendChild(zeroWidthElement(builder.cm.display.measure));
4339
        builder.measuredSomething = true;
4340
      }
4341
      builder.pre.appendChild(widget);
4342
    }
4343
    builder.pos += size;
4344
  }
4345
4346
  // Outputs a number of spans to make up a line, taking highlighting
4347
  // and marked text into account.
4348
  function insertLineContent(line, builder, styles) {
4349
    var spans = line.markedSpans, allText = line.text, at = 0;
4350
    if (!spans) {
4351
      for (var i = 1; i < styles.length; i+=2)
4352
        builder.addToken(builder, allText.slice(at, at = styles[i]), styleToClass(styles[i+1]));
4353
      return;
4354
    }
4355
4356
    var len = allText.length, pos = 0, i = 1, text = "", style;
4357
    var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed;
4358
    for (;;) {
4359
      if (nextChange == pos) { // Update current marker set
4360
        spanStyle = spanEndStyle = spanStartStyle = "";
4361
        collapsed = null; nextChange = Infinity;
4362
        var foundBookmark = null;
4363
        for (var j = 0; j < spans.length; ++j) {
4364
          var sp = spans[j], m = sp.marker;
4365
          if (sp.from <= pos && (sp.to == null || sp.to > pos)) {
4366
            if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }
4367
            if (m.className) spanStyle += " " + m.className;
4368
            if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
4369
            if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
4370
            if (m.collapsed && (!collapsed || collapsed.marker.size < m.size))
4371
              collapsed = sp;
4372
          } else if (sp.from > pos && nextChange > sp.from) {
4373
            nextChange = sp.from;
4374
          }
4375
          if (m.type == "bookmark" && sp.from == pos && m.replacedWith)
4376
            foundBookmark = m.replacedWith;
4377
        }
4378
        if (collapsed && (collapsed.from || 0) == pos) {
4379
          buildCollapsedSpan(builder, (collapsed.to == null ? len : collapsed.to) - pos,
4380
                             collapsed.from != null && collapsed.marker.replacedWith);
4381
          if (collapsed.to == null) return collapsed.marker.find();
4382
        }
4383
        if (foundBookmark && !collapsed) buildCollapsedSpan(builder, 0, foundBookmark);
4384
      }
4385
      if (pos >= len) break;
4386
4387
      var upto = Math.min(len, nextChange);
4388
      while (true) {
4389
        if (text) {
4390
          var end = pos + text.length;
4391
          if (!collapsed) {
4392
            var tokenText = end > upto ? text.slice(0, upto - pos) : text;
4393
            builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
4394
                             spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "");
4395
          }
4396
          if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
4397
          pos = end;
4398
          spanStartStyle = "";
4399
        }
4400
        text = allText.slice(at, at = styles[i++]);
4401
        style = styleToClass(styles[i++]);
4402
      }
4403
    }
4404
  }
4405
4406
  // DOCUMENT DATA STRUCTURE
4407
4408
  function updateDoc(doc, change, markedSpans, selAfter, estimateHeight) {
4409
    function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
4410
    function update(line, text, spans) {
4411
      updateLine(line, text, spans, estimateHeight);
4412
      signalLater(line, "change", line, change);
4413
    }
4414
4415
    var from = change.from, to = change.to, text = change.text;
4416
    var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
4417
    var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
4418
4419
    // First adjust the line structure
4420
    if (from.ch == 0 && to.ch == 0 && lastText == "") {
4421
      // This is a whole-line replace. Treated specially to make
4422
      // sure line objects move the way they are supposed to.
4423
      for (var i = 0, e = text.length - 1, added = []; i < e; ++i)
4424
        added.push(makeLine(text[i], spansFor(i), estimateHeight));
4425
      update(lastLine, lastLine.text, lastSpans);
4426
      if (nlines) doc.remove(from.line, nlines);
4427
      if (added.length) doc.insert(from.line, added);
4428
    } else if (firstLine == lastLine) {
4429
      if (text.length == 1) {
4430
        update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
4431
      } else {
4432
        for (var added = [], i = 1, e = text.length - 1; i < e; ++i)
4433
          added.push(makeLine(text[i], spansFor(i), estimateHeight));
4434
        added.push(makeLine(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
4435
        update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
4436
        doc.insert(from.line + 1, added);
4437
      }
4438
    } else if (text.length == 1) {
4439
      update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
4440
      doc.remove(from.line + 1, nlines);
4441
    } else {
4442
      update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
4443
      update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
4444
      for (var i = 1, e = text.length - 1, added = []; i < e; ++i)
4445
        added.push(makeLine(text[i], spansFor(i), estimateHeight));
4446
      if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
4447
      doc.insert(from.line + 1, added);
4448
    }
4449
4450
    signalLater(doc, "change", doc, change);
4451
    setSelection(doc, selAfter.anchor, selAfter.head, null, true);
4452
  }
4453
4454
  function LeafChunk(lines) {
4455
    this.lines = lines;
4456
    this.parent = null;
4457
    for (var i = 0, e = lines.length, height = 0; i < e; ++i) {
4458
      lines[i].parent = this;
4459
      height += lines[i].height;
4460
    }
4461
    this.height = height;
4462
  }
4463
4464
  LeafChunk.prototype = {
4465
    chunkSize: function() { return this.lines.length; },
4466
    removeInner: function(at, n) {
4467
      for (var i = at, e = at + n; i < e; ++i) {
4468
        var line = this.lines[i];
4469
        this.height -= line.height;
4470
        cleanUpLine(line);
4471
        signalLater(line, "delete");
4472
      }
4473
      this.lines.splice(at, n);
4474
    },
4475
    collapse: function(lines) {
4476
      lines.splice.apply(lines, [lines.length, 0].concat(this.lines));
4477
    },
4478
    insertInner: function(at, lines, height) {
4479
      this.height += height;
4480
      this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
4481
      for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this;
4482
    },
4483
    iterN: function(at, n, op) {
4484
      for (var e = at + n; at < e; ++at)
4485
        if (op(this.lines[at])) return true;
4486
    }
4487
  };
4488
4489
  function BranchChunk(children) {
4490
    this.children = children;
4491
    var size = 0, height = 0;
4492
    for (var i = 0, e = children.length; i < e; ++i) {
4493
      var ch = children[i];
4494
      size += ch.chunkSize(); height += ch.height;
4495
      ch.parent = this;
4496
    }
4497
    this.size = size;
4498
    this.height = height;
4499
    this.parent = null;
4500
  }
4501
4502
  BranchChunk.prototype = {
4503
    chunkSize: function() { return this.size; },
4504
    removeInner: function(at, n) {
4505
      this.size -= n;
4506
      for (var i = 0; i < this.children.length; ++i) {
4507
        var child = this.children[i], sz = child.chunkSize();
4508
        if (at < sz) {
4509
          var rm = Math.min(n, sz - at), oldHeight = child.height;
4510
          child.removeInner(at, rm);
4511
          this.height -= oldHeight - child.height;
4512
          if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
4513
          if ((n -= rm) == 0) break;
4514
          at = 0;
4515
        } else at -= sz;
4516
      }
4517
      if (this.size - n < 25) {
4518
        var lines = [];
4519
        this.collapse(lines);
4520
        this.children = [new LeafChunk(lines)];
4521
        this.children[0].parent = this;
4522
      }
4523
    },
4524
    collapse: function(lines) {
4525
      for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines);
4526
    },
4527
    insertInner: function(at, lines, height) {
4528
      this.size += lines.length;
4529
      this.height += height;
4530
      for (var i = 0, e = this.children.length; i < e; ++i) {
4531
        var child = this.children[i], sz = child.chunkSize();
4532
        if (at <= sz) {
4533
          child.insertInner(at, lines, height);
4534
          if (child.lines && child.lines.length > 50) {
4535
            while (child.lines.length > 50) {
4536
              var spilled = child.lines.splice(child.lines.length - 25, 25);
4537
              var newleaf = new LeafChunk(spilled);
4538
              child.height -= newleaf.height;
4539
              this.children.splice(i + 1, 0, newleaf);
4540
              newleaf.parent = this;
4541
            }
4542
            this.maybeSpill();
4543
          }
4544
          break;
4545
        }
4546
        at -= sz;
4547
      }
4548
    },
4549
    maybeSpill: function() {
4550
      if (this.children.length <= 10) return;
4551
      var me = this;
4552
      do {
4553
        var spilled = me.children.splice(me.children.length - 5, 5);
4554
        var sibling = new BranchChunk(spilled);
4555
        if (!me.parent) { // Become the parent node
4556
          var copy = new BranchChunk(me.children);
4557
          copy.parent = me;
4558
          me.children = [copy, sibling];
4559
          me = copy;
4560
        } else {
4561
          me.size -= sibling.size;
4562
          me.height -= sibling.height;
4563
          var myIndex = indexOf(me.parent.children, me);
4564
          me.parent.children.splice(myIndex + 1, 0, sibling);
4565
        }
4566
        sibling.parent = me.parent;
4567
      } while (me.children.length > 10);
4568
      me.parent.maybeSpill();
4569
    },
4570
    iterN: function(at, n, op) {
4571
      for (var i = 0, e = this.children.length; i < e; ++i) {
4572
        var child = this.children[i], sz = child.chunkSize();
4573
        if (at < sz) {
4574
          var used = Math.min(n, sz - at);
4575
          if (child.iterN(at, used, op)) return true;
4576
          if ((n -= used) == 0) break;
4577
          at = 0;
4578
        } else at -= sz;
4579
      }
4580
    }
4581
  };
4582
4583
  var nextDocId = 0;
4584
  var Doc = CodeMirror.Doc = function(text, mode, firstLine) {
4585
    if (!(this instanceof Doc)) return new Doc(text, mode, firstLine);
4586
    if (firstLine == null) firstLine = 0;
4587
4588
    BranchChunk.call(this, [new LeafChunk([makeLine("", null)])]);
4589
    this.first = firstLine;
4590
    this.scrollTop = this.scrollLeft = 0;
4591
    this.cantEdit = false;
4592
    this.history = makeHistory();
4593
    this.cleanGeneration = 1;
4594
    this.frontier = firstLine;
4595
    var start = Pos(firstLine, 0);
4596
    this.sel = {from: start, to: start, head: start, anchor: start, shift: false, extend: false, goalColumn: null};
4597
    this.id = ++nextDocId;
4598
    this.modeOption = mode;
4599
4600
    if (typeof text == "string") text = splitLines(text);
4601
    updateDoc(this, {from: start, to: start, text: text}, null, {head: start, anchor: start});
4602
  };
4603
4604
  Doc.prototype = createObj(BranchChunk.prototype, {
4605
    constructor: Doc,
4606
    iter: function(from, to, op) {
4607
      if (op) this.iterN(from - this.first, to - from, op);
4608
      else this.iterN(this.first, this.first + this.size, from);
4609
    },
4610
4611
    insert: function(at, lines) {
4612
      var height = 0;
4613
      for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height;
4614
      this.insertInner(at - this.first, lines, height);
4615
    },
4616
    remove: function(at, n) { this.removeInner(at - this.first, n); },
4617
4618
    getValue: function(lineSep) {
4619
      var lines = getLines(this, this.first, this.first + this.size);
4620
      if (lineSep === false) return lines;
4621
      return lines.join(lineSep || "\n");
4622
    },
4623
    setValue: function(code) {
4624
      var top = Pos(this.first, 0), last = this.first + this.size - 1;
4625
      makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
4626
                        text: splitLines(code), origin: "setValue"},
4627
                 {head: top, anchor: top}, true);
4628
    },
4629
    replaceRange: function(code, from, to, origin) {
4630
      from = clipPos(this, from);
4631
      to = to ? clipPos(this, to) : from;
4632
      replaceRange(this, code, from, to, origin);
4633
    },
4634
    getRange: function(from, to, lineSep) {
4635
      var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
4636
      if (lineSep === false) return lines;
4637
      return lines.join(lineSep || "\n");
4638
    },
4639
4640
    getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
4641
    setLine: function(line, text) {
4642
      if (isLine(this, line))
4643
        replaceRange(this, text, Pos(line, 0), clipPos(this, Pos(line)));
4644
    },
4645
    removeLine: function(line) {
4646
      if (line) replaceRange(this, "", clipPos(this, Pos(line - 1)), clipPos(this, Pos(line)));
4647
      else replaceRange(this, "", Pos(0, 0), clipPos(this, Pos(1, 0)));
4648
    },
4649
4650
    getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
4651
    getLineNumber: function(line) {return lineNo(line);},
4652
4653
    lineCount: function() {return this.size;},
4654
    firstLine: function() {return this.first;},
4655
    lastLine: function() {return this.first + this.size - 1;},
4656
4657
    clipPos: function(pos) {return clipPos(this, pos);},
4658
4659
    getCursor: function(start) {
4660
      var sel = this.sel, pos;
4661
      if (start == null || start == "head") pos = sel.head;
4662
      else if (start == "anchor") pos = sel.anchor;
4663
      else if (start == "end" || start === false) pos = sel.to;
4664
      else pos = sel.from;
4665
      return copyPos(pos);
4666
    },
4667
    somethingSelected: function() {return !posEq(this.sel.head, this.sel.anchor);},
4668
4669
    setCursor: docOperation(function(line, ch, extend) {
4670
      var pos = clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line);
4671
      if (extend) extendSelection(this, pos);
4672
      else setSelection(this, pos, pos);
4673
    }),
4674
    setSelection: docOperation(function(anchor, head) {
4675
      setSelection(this, clipPos(this, anchor), clipPos(this, head || anchor));
4676
    }),
4677
    extendSelection: docOperation(function(from, to) {
4678
      extendSelection(this, clipPos(this, from), to && clipPos(this, to));
4679
    }),
4680
4681
    getSelection: function(lineSep) {return this.getRange(this.sel.from, this.sel.to, lineSep);},
4682
    replaceSelection: function(code, collapse, origin) {
4683
      makeChange(this, {from: this.sel.from, to: this.sel.to, text: splitLines(code), origin: origin}, collapse || "around");
4684
    },
4685
    undo: docOperation(function() {makeChangeFromHistory(this, "undo");}),
4686
    redo: docOperation(function() {makeChangeFromHistory(this, "redo");}),
4687
4688
    setExtending: function(val) {this.sel.extend = val;},
4689
4690
    historySize: function() {
4691
      var hist = this.history;
4692
      return {undo: hist.done.length, redo: hist.undone.length};
4693
    },
4694
    clearHistory: function() {this.history = makeHistory(this.history.maxGeneration);},
4695
4696
    markClean: function() {
4697
      this.cleanGeneration = this.changeGeneration();
4698
    },
4699
    changeGeneration: function() {
4700
      this.history.lastOp = this.history.lastOrigin = null;
4701
      return this.history.generation;
4702
    },
4703
    isClean: function (gen) {
4704
      return this.history.generation == (gen || this.cleanGeneration);
4705
    },
4706
4707
    getHistory: function() {
4708
      return {done: copyHistoryArray(this.history.done),
4709
              undone: copyHistoryArray(this.history.undone)};
4710
    },
4711
    setHistory: function(histData) {
4712
      var hist = this.history = makeHistory(this.history.maxGeneration);
4713
      hist.done = histData.done.slice(0);
4714
      hist.undone = histData.undone.slice(0);
4715
    },
4716
4717
    markText: function(from, to, options) {
4718
      return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
4719
    },
4720
    setBookmark: function(pos, options) {
4721
      var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
4722
                      insertLeft: options && options.insertLeft};
4723
      pos = clipPos(this, pos);
4724
      return markText(this, pos, pos, realOpts, "bookmark");
4725
    },
4726
    findMarksAt: function(pos) {
4727
      pos = clipPos(this, pos);
4728
      var markers = [], spans = getLine(this, pos.line).markedSpans;
4729
      if (spans) for (var i = 0; i < spans.length; ++i) {
4730
        var span = spans[i];
4731
        if ((span.from == null || span.from <= pos.ch) &&
4732
            (span.to == null || span.to >= pos.ch))
4733
          markers.push(span.marker.parent || span.marker);
4734
      }
4735
      return markers;
4736
    },
4737
    getAllMarks: function() {
4738
      var markers = [];
4739
      this.iter(function(line) {
4740
        var sps = line.markedSpans;
4741
        if (sps) for (var i = 0; i < sps.length; ++i)
4742
          if (sps[i].from != null) markers.push(sps[i].marker);
4743
      });
4744
      return markers;
4745
    },
4746
4747
    posFromIndex: function(off) {
4748
      var ch, lineNo = this.first;
4749
      this.iter(function(line) {
4750
        var sz = line.text.length + 1;
4751
        if (sz > off) { ch = off; return true; }
4752
        off -= sz;
4753
        ++lineNo;
4754
      });
4755
      return clipPos(this, Pos(lineNo, ch));
4756
    },
4757
    indexFromPos: function (coords) {
4758
      coords = clipPos(this, coords);
4759
      var index = coords.ch;
4760
      if (coords.line < this.first || coords.ch < 0) return 0;
4761
      this.iter(this.first, coords.line, function (line) {
4762
        index += line.text.length + 1;
4763
      });
4764
      return index;
4765
    },
4766
4767
    copy: function(copyHistory) {
4768
      var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first);
4769
      doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
4770
      doc.sel = {from: this.sel.from, to: this.sel.to, head: this.sel.head, anchor: this.sel.anchor,
4771
                 shift: this.sel.shift, extend: false, goalColumn: this.sel.goalColumn};
4772
      if (copyHistory) {
4773
        doc.history.undoDepth = this.history.undoDepth;
4774
        doc.setHistory(this.getHistory());
4775
      }
4776
      return doc;
4777
    },
4778
4779
    linkedDoc: function(options) {
4780
      if (!options) options = {};
4781
      var from = this.first, to = this.first + this.size;
4782
      if (options.from != null && options.from > from) from = options.from;
4783
      if (options.to != null && options.to < to) to = options.to;
4784
      var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from);
4785
      if (options.sharedHist) copy.history = this.history;
4786
      (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
4787
      copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
4788
      return copy;
4789
    },
4790
    unlinkDoc: function(other) {
4791
      if (other instanceof CodeMirror) other = other.doc;
4792
      if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
4793
        var link = this.linked[i];
4794
        if (link.doc != other) continue;
4795
        this.linked.splice(i, 1);
4796
        other.unlinkDoc(this);
4797
        break;
4798
      }
4799
      // If the histories were shared, split them again
4800
      if (other.history == this.history) {
4801
        var splitIds = [other.id];
4802
        linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
4803
        other.history = makeHistory();
4804
        other.history.done = copyHistoryArray(this.history.done, splitIds);
4805
        other.history.undone = copyHistoryArray(this.history.undone, splitIds);
4806
      }
4807
    },
4808
    iterLinkedDocs: function(f) {linkedDocs(this, f);},
4809
4810
    getMode: function() {return this.mode;},
4811
    getEditor: function() {return this.cm;}
4812
  });
4813
4814
  Doc.prototype.eachLine = Doc.prototype.iter;
4815
4816
  // The Doc methods that should be available on CodeMirror instances
4817
  var dontDelegate = "iter insert remove copy getEditor".split(" ");
4818
  for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
4819
    CodeMirror.prototype[prop] = (function(method) {
4820
      return function() {return method.apply(this.doc, arguments);};
4821
    })(Doc.prototype[prop]);
4822
4823
  function linkedDocs(doc, f, sharedHistOnly) {
4824
    function propagate(doc, skip, sharedHist) {
4825
      if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
4826
        var rel = doc.linked[i];
4827
        if (rel.doc == skip) continue;
4828
        var shared = sharedHist && rel.sharedHist;
4829
        if (sharedHistOnly && !shared) continue;
4830
        f(rel.doc, shared);
4831
        propagate(rel.doc, doc, shared);
4832
      }
4833
    }
4834
    propagate(doc, null, true);
4835
  }
4836
4837
  function attachDoc(cm, doc) {
4838
    if (doc.cm) throw new Error("This document is already in use.");
4839
    cm.doc = doc;
4840
    doc.cm = cm;
4841
    estimateLineHeights(cm);
4842
    loadMode(cm);
4843
    if (!cm.options.lineWrapping) computeMaxLength(cm);
4844
    cm.options.mode = doc.modeOption;
4845
    regChange(cm);
4846
  }
4847
4848
  // LINE UTILITIES
4849
4850
  function getLine(chunk, n) {
4851
    n -= chunk.first;
4852
    while (!chunk.lines) {
4853
      for (var i = 0;; ++i) {
4854
        var child = chunk.children[i], sz = child.chunkSize();
4855
        if (n < sz) { chunk = child; break; }
4856
        n -= sz;
4857
      }
4858
    }
4859
    return chunk.lines[n];
4860
  }
4861
4862
  function getBetween(doc, start, end) {
4863
    var out = [], n = start.line;
4864
    doc.iter(start.line, end.line + 1, function(line) {
4865
      var text = line.text;
4866
      if (n == end.line) text = text.slice(0, end.ch);
4867
      if (n == start.line) text = text.slice(start.ch);
4868
      out.push(text);
4869
      ++n;
4870
    });
4871
    return out;
4872
  }
4873
  function getLines(doc, from, to) {
4874
    var out = [];
4875
    doc.iter(from, to, function(line) { out.push(line.text); });
4876
    return out;
4877
  }
4878
4879
  function updateLineHeight(line, height) {
4880
    var diff = height - line.height;
4881
    for (var n = line; n; n = n.parent) n.height += diff;
4882
  }
4883
4884
  function lineNo(line) {
4885
    if (line.parent == null) return null;
4886
    var cur = line.parent, no = indexOf(cur.lines, line);
4887
    for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
4888
      for (var i = 0;; ++i) {
4889
        if (chunk.children[i] == cur) break;
4890
        no += chunk.children[i].chunkSize();
4891
      }
4892
    }
4893
    return no + cur.first;
4894
  }
4895
4896
  function lineAtHeight(chunk, h) {
4897
    var n = chunk.first;
4898
    outer: do {
4899
      for (var i = 0, e = chunk.children.length; i < e; ++i) {
4900
        var child = chunk.children[i], ch = child.height;
4901
        if (h < ch) { chunk = child; continue outer; }
4902
        h -= ch;
4903
        n += child.chunkSize();
4904
      }
4905
      return n;
4906
    } while (!chunk.lines);
4907
    for (var i = 0, e = chunk.lines.length; i < e; ++i) {
4908
      var line = chunk.lines[i], lh = line.height;
4909
      if (h < lh) break;
4910
      h -= lh;
4911
    }
4912
    return n + i;
4913
  }
4914
4915
  function heightAtLine(cm, lineObj) {
4916
    lineObj = visualLine(cm.doc, lineObj);
4917
4918
    var h = 0, chunk = lineObj.parent;
4919
    for (var i = 0; i < chunk.lines.length; ++i) {
4920
      var line = chunk.lines[i];
4921
      if (line == lineObj) break;
4922
      else h += line.height;
4923
    }
4924
    for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
4925
      for (var i = 0; i < p.children.length; ++i) {
4926
        var cur = p.children[i];
4927
        if (cur == chunk) break;
4928
        else h += cur.height;
4929
      }
4930
    }
4931
    return h;
4932
  }
4933
4934
  function getOrder(line) {
4935
    var order = line.order;
4936
    if (order == null) order = line.order = bidiOrdering(line.text);
4937
    return order;
4938
  }
4939
4940
  // HISTORY
4941
4942
  function makeHistory(startGen) {
4943
    return {
4944
      // Arrays of history events. Doing something adds an event to
4945
      // done and clears undo. Undoing moves events from done to
4946
      // undone, redoing moves them in the other direction.
4947
      done: [], undone: [], undoDepth: Infinity,
4948
      // Used to track when changes can be merged into a single undo
4949
      // event
4950
      lastTime: 0, lastOp: null, lastOrigin: null,
4951
      // Used by the isClean() method
4952
      generation: startGen || 1, maxGeneration: startGen || 1
4953
    };
4954
  }
4955
4956
  function attachLocalSpans(doc, change, from, to) {
4957
    var existing = change["spans_" + doc.id], n = 0;
4958
    doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
4959
      if (line.markedSpans)
4960
        (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
4961
      ++n;
4962
    });
4963
  }
4964
4965
  function historyChangeFromChange(doc, change) {
4966
    var histChange = {from: change.from, to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
4967
    attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
4968
    linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
4969
    return histChange;
4970
  }
4971
4972
  function addToHistory(doc, change, selAfter, opId) {
4973
    var hist = doc.history;
4974
    hist.undone.length = 0;
4975
    var time = +new Date, cur = lst(hist.done);
4976
4977
    if (cur &&
4978
        (hist.lastOp == opId ||
4979
         hist.lastOrigin == change.origin && change.origin &&
4980
         ((change.origin.charAt(0) == "+" && doc.cm && hist.lastTime > time - doc.cm.options.historyEventDelay) ||
4981
          change.origin.charAt(0) == "*"))) {
4982
      // Merge this change into the last event
4983
      var last = lst(cur.changes);
4984
      if (posEq(change.from, change.to) && posEq(change.from, last.to)) {
4985
        // Optimized case for simple insertion -- don't want to add
4986
        // new changesets for every character typed
4987
        last.to = changeEnd(change);
4988
      } else {
4989
        // Add new sub-event
4990
        cur.changes.push(historyChangeFromChange(doc, change));
4991
      }
4992
      cur.anchorAfter = selAfter.anchor; cur.headAfter = selAfter.head;
4993
    } else {
4994
      // Can not be merged, start a new event.
4995
      cur = {changes: [historyChangeFromChange(doc, change)],
4996
             generation: hist.generation,
4997
             anchorBefore: doc.sel.anchor, headBefore: doc.sel.head,
4998
             anchorAfter: selAfter.anchor, headAfter: selAfter.head};
4999
      hist.done.push(cur);
5000
      hist.generation = ++hist.maxGeneration;
5001
      while (hist.done.length > hist.undoDepth)
5002
        hist.done.shift();
5003
    }
5004
    hist.lastTime = time;
5005
    hist.lastOp = opId;
5006
    hist.lastOrigin = change.origin;
5007
  }
5008
5009
  function removeClearedSpans(spans) {
5010
    if (!spans) return null;
5011
    for (var i = 0, out; i < spans.length; ++i) {
5012
      if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
5013
      else if (out) out.push(spans[i]);
5014
    }
5015
    return !out ? spans : out.length ? out : null;
5016
  }
5017
5018
  function getOldSpans(doc, change) {
5019
    var found = change["spans_" + doc.id];
5020
    if (!found) return null;
5021
    for (var i = 0, nw = []; i < change.text.length; ++i)
5022
      nw.push(removeClearedSpans(found[i]));
5023
    return nw;
5024
  }
5025
5026
  // Used both to provide a JSON-safe object in .getHistory, and, when
5027
  // detaching a document, to split the history in two
5028
  function copyHistoryArray(events, newGroup) {
5029
    for (var i = 0, copy = []; i < events.length; ++i) {
5030
      var event = events[i], changes = event.changes, newChanges = [];
5031
      copy.push({changes: newChanges, anchorBefore: event.anchorBefore, headBefore: event.headBefore,
5032
                 anchorAfter: event.anchorAfter, headAfter: event.headAfter});
5033
      for (var j = 0; j < changes.length; ++j) {
5034
        var change = changes[j], m;
5035
        newChanges.push({from: change.from, to: change.to, text: change.text});
5036
        if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
5037
          if (indexOf(newGroup, Number(m[1])) > -1) {
5038
            lst(newChanges)[prop] = change[prop];
5039
            delete change[prop];
5040
          }
5041
        }
5042
      }
5043
    }
5044
    return copy;
5045
  }
5046
5047
  // Rebasing/resetting history to deal with externally-sourced changes
5048
5049
  function rebaseHistSel(pos, from, to, diff) {
5050
    if (to < pos.line) {
5051
      pos.line += diff;
5052
    } else if (from < pos.line) {
5053
      pos.line = from;
5054
      pos.ch = 0;
5055
    }
5056
  }
5057
5058
  // Tries to rebase an array of history events given a change in the
5059
  // document. If the change touches the same lines as the event, the
5060
  // event, and everything 'behind' it, is discarded. If the change is
5061
  // before the event, the event's positions are updated. Uses a
5062
  // copy-on-write scheme for the positions, to avoid having to
5063
  // reallocate them all on every rebase, but also avoid problems with
5064
  // shared position objects being unsafely updated.
5065
  function rebaseHistArray(array, from, to, diff) {
5066
    for (var i = 0; i < array.length; ++i) {
5067
      var sub = array[i], ok = true;
5068
      for (var j = 0; j < sub.changes.length; ++j) {
5069
        var cur = sub.changes[j];
5070
        if (!sub.copied) { cur.from = copyPos(cur.from); cur.to = copyPos(cur.to); }
5071
        if (to < cur.from.line) {
5072
          cur.from.line += diff;
5073
          cur.to.line += diff;
5074
        } else if (from <= cur.to.line) {
5075
          ok = false;
5076
          break;
5077
        }
5078
      }
5079
      if (!sub.copied) {
5080
        sub.anchorBefore = copyPos(sub.anchorBefore); sub.headBefore = copyPos(sub.headBefore);
5081
        sub.anchorAfter = copyPos(sub.anchorAfter); sub.readAfter = copyPos(sub.headAfter);
5082
        sub.copied = true;
5083
      }
5084
      if (!ok) {
5085
        array.splice(0, i + 1);
5086
        i = 0;
5087
      } else {
5088
        rebaseHistSel(sub.anchorBefore); rebaseHistSel(sub.headBefore);
5089
        rebaseHistSel(sub.anchorAfter); rebaseHistSel(sub.headAfter);
5090
      }
5091
    }
5092
  }
5093
5094
  function rebaseHist(hist, change) {
5095
    var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
5096
    rebaseHistArray(hist.done, from, to, diff);
5097
    rebaseHistArray(hist.undone, from, to, diff);
5098
  }
5099
5100
  // EVENT OPERATORS
5101
5102
  function stopMethod() {e_stop(this);}
5103
  // Ensure an event has a stop method.
5104
  function addStop(event) {
5105
    if (!event.stop) event.stop = stopMethod;
5106
    return event;
5107
  }
5108
5109
  function e_preventDefault(e) {
5110
    if (e.preventDefault) e.preventDefault();
5111
    else e.returnValue = false;
5112
  }
5113
  function e_stopPropagation(e) {
5114
    if (e.stopPropagation) e.stopPropagation();
5115
    else e.cancelBubble = true;
5116
  }
5117
  function e_defaultPrevented(e) {
5118
    return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
5119
  }
5120
  function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
5121
  CodeMirror.e_stop = e_stop;
5122
  CodeMirror.e_preventDefault = e_preventDefault;
5123
  CodeMirror.e_stopPropagation = e_stopPropagation;
5124
5125
  function e_target(e) {return e.target || e.srcElement;}
5126
  function e_button(e) {
5127
    var b = e.which;
5128
    if (b == null) {
5129
      if (e.button & 1) b = 1;
5130
      else if (e.button & 2) b = 3;
5131
      else if (e.button & 4) b = 2;
5132
    }
5133
    if (mac && e.ctrlKey && b == 1) b = 3;
5134
    return b;
5135
  }
5136
5137
  // EVENT HANDLING
5138
5139
  function on(emitter, type, f) {
5140
    if (emitter.addEventListener)
5141
      emitter.addEventListener(type, f, false);
5142
    else if (emitter.attachEvent)
5143
      emitter.attachEvent("on" + type, f);
5144
    else {
5145
      var map = emitter._handlers || (emitter._handlers = {});
5146
      var arr = map[type] || (map[type] = []);
5147
      arr.push(f);
5148
    }
5149
  }
5150
5151
  function off(emitter, type, f) {
5152
    if (emitter.removeEventListener)
5153
      emitter.removeEventListener(type, f, false);
5154
    else if (emitter.detachEvent)
5155
      emitter.detachEvent("on" + type, f);
5156
    else {
5157
      var arr = emitter._handlers && emitter._handlers[type];
5158
      if (!arr) return;
5159
      for (var i = 0; i < arr.length; ++i)
5160
        if (arr[i] == f) { arr.splice(i, 1); break; }
5161
    }
5162
  }
5163
5164
  function signal(emitter, type /*, values...*/) {
5165
    var arr = emitter._handlers && emitter._handlers[type];
5166
    if (!arr) return;
5167
    var args = Array.prototype.slice.call(arguments, 2);
5168
    for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
5169
  }
5170
5171
  var delayedCallbacks, delayedCallbackDepth = 0;
5172
  function signalLater(emitter, type /*, values...*/) {
5173
    var arr = emitter._handlers && emitter._handlers[type];
5174
    if (!arr) return;
5175
    var args = Array.prototype.slice.call(arguments, 2);
5176
    if (!delayedCallbacks) {
5177
      ++delayedCallbackDepth;
5178
      delayedCallbacks = [];
5179
      setTimeout(fireDelayed, 0);
5180
    }
5181
    function bnd(f) {return function(){f.apply(null, args);};};
5182
    for (var i = 0; i < arr.length; ++i)
5183
      delayedCallbacks.push(bnd(arr[i]));
5184
  }
5185
5186
  function signalDOMEvent(cm, e) {
5187
    signal(cm, e.type, cm, e);
5188
    return e_defaultPrevented(e);
5189
  }
5190
5191
  function fireDelayed() {
5192
    --delayedCallbackDepth;
5193
    var delayed = delayedCallbacks;
5194
    delayedCallbacks = null;
5195
    for (var i = 0; i < delayed.length; ++i) delayed[i]();
5196
  }
5197
5198
  function hasHandler(emitter, type) {
5199
    var arr = emitter._handlers && emitter._handlers[type];
5200
    return arr && arr.length > 0;
5201
  }
5202
5203
  CodeMirror.on = on; CodeMirror.off = off; CodeMirror.signal = signal;
5204
5205
  // MISC UTILITIES
5206
5207
  // Number of pixels added to scroller and sizer to hide scrollbar
5208
  var scrollerCutOff = 30;
5209
5210
  // Returned or thrown by various protocols to signal 'I'm not
5211
  // handling this'.
5212
  var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
5213
5214
  function Delayed() {this.id = null;}
5215
  Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
5216
5217
  // Counts the column offset in a string, taking tabs into account.
5218
  // Used mostly to find indentation.
5219
  function countColumn(string, end, tabSize, startIndex, startValue) {
5220
    if (end == null) {
5221
      end = string.search(/[^\s\u00a0]/);
5222
      if (end == -1) end = string.length;
5223
    }
5224
    for (var i = startIndex || 0, n = startValue || 0; i < end; ++i) {
5225
      if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
5226
      else ++n;
5227
    }
5228
    return n;
5229
  }
5230
  CodeMirror.countColumn = countColumn;
5231
5232
  var spaceStrs = [""];
5233
  function spaceStr(n) {
5234
    while (spaceStrs.length <= n)
5235
      spaceStrs.push(lst(spaceStrs) + " ");
5236
    return spaceStrs[n];
5237
  }
5238
5239
  function lst(arr) { return arr[arr.length-1]; }
5240
5241
  function selectInput(node) {
5242
    if (ios) { // Mobile Safari apparently has a bug where select() is broken.
5243
      node.selectionStart = 0;
5244
      node.selectionEnd = node.value.length;
5245
    } else {
5246
      // Suppress mysterious IE10 errors
5247
      try { node.select(); }
5248
      catch(_e) {}
5249
    }
5250
  }
5251
5252
  function indexOf(collection, elt) {
5253
    if (collection.indexOf) return collection.indexOf(elt);
5254
    for (var i = 0, e = collection.length; i < e; ++i)
5255
      if (collection[i] == elt) return i;
5256
    return -1;
5257
  }
5258
5259
  function createObj(base, props) {
5260
    function Obj() {}
5261
    Obj.prototype = base;
5262
    var inst = new Obj();
5263
    if (props) copyObj(props, inst);
5264
    return inst;
5265
  }
5266
5267
  function copyObj(obj, target) {
5268
    if (!target) target = {};
5269
    for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop];
5270
    return target;
5271
  }
5272
5273
  function emptyArray(size) {
5274
    for (var a = [], i = 0; i < size; ++i) a.push(undefined);
5275
    return a;
5276
  }
5277
5278
  function bind(f) {
5279
    var args = Array.prototype.slice.call(arguments, 1);
5280
    return function(){return f.apply(null, args);};
5281
  }
5282
5283
  var nonASCIISingleCaseWordChar = /[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
5284
  function isWordChar(ch) {
5285
    return /\w/.test(ch) || ch > "\x80" &&
5286
      (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
5287
  }
5288
5289
  function isEmpty(obj) {
5290
    for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
5291
    return true;
5292
  }
5293
5294
  var isExtendingChar = /[\u0300-\u036F\u0483-\u0487\u0488-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\uA66F\uA670-\uA672\uA674-\uA67D\uA69F\udc00-\udfff]/;
5295
5296
  // DOM UTILITIES
5297
5298
  function elt(tag, content, className, style) {
5299
    var e = document.createElement(tag);
5300
    if (className) e.className = className;
5301
    if (style) e.style.cssText = style;
5302
    if (typeof content == "string") setTextContent(e, content);
5303
    else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
5304
    return e;
5305
  }
5306
5307
  function removeChildren(e) {
5308
    for (var count = e.childNodes.length; count > 0; --count)
5309
      e.removeChild(e.firstChild);
5310
    return e;
5311
  }
5312
5313
  function removeChildrenAndAdd(parent, e) {
5314
    return removeChildren(parent).appendChild(e);
5315
  }
5316
5317
  function setTextContent(e, str) {
5318
    if (ie_lt9) {
5319
      e.innerHTML = "";
5320
      e.appendChild(document.createTextNode(str));
5321
    } else e.textContent = str;
5322
  }
5323
5324
  function getRect(node) {
5325
    return node.getBoundingClientRect();
5326
  }
5327
  CodeMirror.replaceGetRect = function(f) { getRect = f; };
5328
5329
  // FEATURE DETECTION
5330
5331
  // Detect drag-and-drop
5332
  var dragAndDrop = function() {
5333
    // There is *some* kind of drag-and-drop support in IE6-8, but I
5334
    // couldn't get it to work yet.
5335
    if (ie_lt9) return false;
5336
    var div = elt('div');
5337
    return "draggable" in div || "dragDrop" in div;
5338
  }();
5339
5340
  // For a reason I have yet to figure out, some browsers disallow
5341
  // word wrapping between certain characters *only* if a new inline
5342
  // element is started between them. This makes it hard to reliably
5343
  // measure the position of things, since that requires inserting an
5344
  // extra span. This terribly fragile set of tests matches the
5345
  // character combinations that suffer from this phenomenon on the
5346
  // various browsers.
5347
  function spanAffectsWrapping() { return false; }
5348
  if (gecko) // Only for "$'"
5349
    spanAffectsWrapping = function(str, i) {
5350
      return str.charCodeAt(i - 1) == 36 && str.charCodeAt(i) == 39;
5351
    };
5352
  else if (safari && !/Version\/([6-9]|\d\d)\b/.test(navigator.userAgent))
5353
    spanAffectsWrapping = function(str, i) {
5354
      return /\-[^ \-?]|\?[^ !\'\"\),.\-\/:;\?\]\}]/.test(str.slice(i - 1, i + 1));
5355
    };
5356
  else if (webkit)
5357
    spanAffectsWrapping = function(str, i) {
5358
      if (i > 1 && str.charCodeAt(i - 1) == 45 && /\w/.test(str.charAt(i - 2)) && /[^\-?\.]/.test(str.charAt(i)))
5359
        return true;
5360
      return /[~!#%&*)=+}\]|\"\.>,:;][({[<]|-[^\-?\.\u2010-\u201f\u2026]|\?[\w~`@#$%\^&*(_=+{[|><]|…[\w~`@#$%\^&*(_=+{[><]/.test(str.slice(i - 1, i + 1));
5361
    };
5362
5363
  var knownScrollbarWidth;
5364
  function scrollbarWidth(measure) {
5365
    if (knownScrollbarWidth != null) return knownScrollbarWidth;
5366
    var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll");
5367
    removeChildrenAndAdd(measure, test);
5368
    if (test.offsetWidth)
5369
      knownScrollbarWidth = test.offsetHeight - test.clientHeight;
5370
    return knownScrollbarWidth || 0;
5371
  }
5372
5373
  var zwspSupported;
5374
  function zeroWidthElement(measure) {
5375
    if (zwspSupported == null) {
5376
      var test = elt("span", "\u200b");
5377
      removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
5378
      if (measure.firstChild.offsetHeight != 0)
5379
        zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_lt8;
5380
    }
5381
    if (zwspSupported) return elt("span", "\u200b");
5382
    else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
5383
  }
5384
5385
  // See if "".split is the broken IE version, if so, provide an
5386
  // alternative way to split lines.
5387
  var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
5388
    var pos = 0, result = [], l = string.length;
5389
    while (pos <= l) {
5390
      var nl = string.indexOf("\n", pos);
5391
      if (nl == -1) nl = string.length;
5392
      var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
5393
      var rt = line.indexOf("\r");
5394
      if (rt != -1) {
5395
        result.push(line.slice(0, rt));
5396
        pos += rt + 1;
5397
      } else {
5398
        result.push(line);
5399
        pos = nl + 1;
5400
      }
5401
    }
5402
    return result;
5403
  } : function(string){return string.split(/\r\n?|\n/);};
5404
  CodeMirror.splitLines = splitLines;
5405
5406
  var hasSelection = window.getSelection ? function(te) {
5407
    try { return te.selectionStart != te.selectionEnd; }
5408
    catch(e) { return false; }
5409
  } : function(te) {
5410
    try {var range = te.ownerDocument.selection.createRange();}
5411
    catch(e) {}
5412
    if (!range || range.parentElement() != te) return false;
5413
    return range.compareEndPoints("StartToEnd", range) != 0;
5414
  };
5415
5416
  var hasCopyEvent = (function() {
5417
    var e = elt("div");
5418
    if ("oncopy" in e) return true;
5419
    e.setAttribute("oncopy", "return;");
5420
    return typeof e.oncopy == 'function';
5421
  })();
5422
5423
  // KEY NAMING
5424
5425
  var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
5426
                  19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
5427
                  36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
5428
                  46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete",
5429
                  186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
5430
                  221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home",
5431
                  63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"};
5432
  CodeMirror.keyNames = keyNames;
5433
  (function() {
5434
    // Number keys
5435
    for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i);
5436
    // Alphabetic keys
5437
    for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
5438
    // Function keys
5439
    for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
5440
  })();
5441
5442
  // BIDI HELPERS
5443
5444
  function iterateBidiSections(order, from, to, f) {
5445
    if (!order) return f(from, to, "ltr");
5446
    for (var i = 0; i < order.length; ++i) {
5447
      var part = order[i];
5448
      if (part.from < to && part.to > from || from == to && part.to == from)
5449
        f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
5450
    }
5451
  }
5452
5453
  function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
5454
  function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
5455
5456
  function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
5457
  function lineRight(line) {
5458
    var order = getOrder(line);
5459
    if (!order) return line.text.length;
5460
    return bidiRight(lst(order));
5461
  }
5462
5463
  function lineStart(cm, lineN) {
5464
    var line = getLine(cm.doc, lineN);
5465
    var visual = visualLine(cm.doc, line);
5466
    if (visual != line) lineN = lineNo(visual);
5467
    var order = getOrder(visual);
5468
    var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
5469
    return Pos(lineN, ch);
5470
  }
5471
  function lineEnd(cm, lineN) {
5472
    var merged, line;
5473
    while (merged = collapsedSpanAtEnd(line = getLine(cm.doc, lineN)))
5474
      lineN = merged.find().to.line;
5475
    var order = getOrder(line);
5476
    var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
5477
    return Pos(lineN, ch);
5478
  }
5479
5480
  function compareBidiLevel(order, a, b) {
5481
    var linedir = order[0].level;
5482
    if (a == linedir) return true;
5483
    if (b == linedir) return false;
5484
    return a < b;
5485
  }
5486
  var bidiOther;
5487
  function getBidiPartAt(order, pos) {
5488
    for (var i = 0, found; i < order.length; ++i) {
5489
      var cur = order[i];
5490
      if (cur.from < pos && cur.to > pos) { bidiOther = null; return i; }
5491
      if (cur.from == pos || cur.to == pos) {
5492
        if (found == null) {
5493
          found = i;
5494
        } else if (compareBidiLevel(order, cur.level, order[found].level)) {
5495
          bidiOther = found;
5496
          return i;
5497
        } else {
5498
          bidiOther = i;
5499
          return found;
5500
        }
5501
      }
5502
    }
5503
    bidiOther = null;
5504
    return found;
5505
  }
5506
5507
  function moveInLine(line, pos, dir, byUnit) {
5508
    if (!byUnit) return pos + dir;
5509
    do pos += dir;
5510
    while (pos > 0 && isExtendingChar.test(line.text.charAt(pos)));
5511
    return pos;
5512
  }
5513
5514
  // This is somewhat involved. It is needed in order to move
5515
  // 'visually' through bi-directional text -- i.e., pressing left
5516
  // should make the cursor go left, even when in RTL text. The
5517
  // tricky part is the 'jumps', where RTL and LTR text touch each
5518
  // other. This often requires the cursor offset to move more than
5519
  // one unit, in order to visually move one unit.
5520
  function moveVisually(line, start, dir, byUnit) {
5521
    var bidi = getOrder(line);
5522
    if (!bidi) return moveLogically(line, start, dir, byUnit);
5523
    var pos = getBidiPartAt(bidi, start), part = bidi[pos];
5524
    var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
5525
5526
    for (;;) {
5527
      if (target > part.from && target < part.to) return target;
5528
      if (target == part.from || target == part.to) {
5529
        if (getBidiPartAt(bidi, target) == pos) return target;
5530
        part = bidi[pos += dir];
5531
        return (dir > 0) == part.level % 2 ? part.to : part.from;
5532
      } else {
5533
        part = bidi[pos += dir];
5534
        if (!part) return null;
5535
        if ((dir > 0) == part.level % 2)
5536
          target = moveInLine(line, part.to, -1, byUnit);
5537
        else
5538
          target = moveInLine(line, part.from, 1, byUnit);
5539
      }
5540
    }
5541
  }
5542
5543
  function moveLogically(line, start, dir, byUnit) {
5544
    var target = start + dir;
5545
    if (byUnit) while (target > 0 && isExtendingChar.test(line.text.charAt(target))) target += dir;
5546
    return target < 0 || target > line.text.length ? null : target;
5547
  }
5548
5549
  // Bidirectional ordering algorithm
5550
  // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
5551
  // that this (partially) implements.
5552
5553
  // One-char codes used for character types:
5554
  // L (L):   Left-to-Right
5555
  // R (R):   Right-to-Left
5556
  // r (AL):  Right-to-Left Arabic
5557
  // 1 (EN):  European Number
5558
  // + (ES):  European Number Separator
5559
  // % (ET):  European Number Terminator
5560
  // n (AN):  Arabic Number
5561
  // , (CS):  Common Number Separator
5562
  // m (NSM): Non-Spacing Mark
5563
  // b (BN):  Boundary Neutral
5564
  // s (B):   Paragraph Separator
5565
  // t (S):   Segment Separator
5566
  // w (WS):  Whitespace
5567
  // N (ON):  Other Neutrals
5568
5569
  // Returns null if characters are ordered as they appear
5570
  // (left-to-right), or an array of sections ({from, to, level}
5571
  // objects) in the order in which they occur visually.
5572
  var bidiOrdering = (function() {
5573
    // Character types for codepoints 0 to 0xff
5574
    var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLL";
5575
    // Character types for codepoints 0x600 to 0x6ff
5576
    var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmmrrrrrrrrrrrrrrrrrr";
5577
    function charType(code) {
5578
      if (code <= 0xff) return lowTypes.charAt(code);
5579
      else if (0x590 <= code && code <= 0x5f4) return "R";
5580
      else if (0x600 <= code && code <= 0x6ff) return arabicTypes.charAt(code - 0x600);
5581
      else if (0x700 <= code && code <= 0x8ac) return "r";
5582
      else return "L";
5583
    }
5584
5585
    var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
5586
    var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
5587
    // Browsers seem to always treat the boundaries of block elements as being L.
5588
    var outerType = "L";
5589
5590
    return function(str) {
5591
      if (!bidiRE.test(str)) return false;
5592
      var len = str.length, types = [];
5593
      for (var i = 0, type; i < len; ++i)
5594
        types.push(type = charType(str.charCodeAt(i)));
5595
5596
      // W1. Examine each non-spacing mark (NSM) in the level run, and
5597
      // change the type of the NSM to the type of the previous
5598
      // character. If the NSM is at the start of the level run, it will
5599
      // get the type of sor.
5600
      for (var i = 0, prev = outerType; i < len; ++i) {
5601
        var type = types[i];
5602
        if (type == "m") types[i] = prev;
5603
        else prev = type;
5604
      }
5605
5606
      // W2. Search backwards from each instance of a European number
5607
      // until the first strong type (R, L, AL, or sor) is found. If an
5608
      // AL is found, change the type of the European number to Arabic
5609
      // number.
5610
      // W3. Change all ALs to R.
5611
      for (var i = 0, cur = outerType; i < len; ++i) {
5612
        var type = types[i];
5613
        if (type == "1" && cur == "r") types[i] = "n";
5614
        else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
5615
      }
5616
5617
      // W4. A single European separator between two European numbers
5618
      // changes to a European number. A single common separator between
5619
      // two numbers of the same type changes to that type.
5620
      for (var i = 1, prev = types[0]; i < len - 1; ++i) {
5621
        var type = types[i];
5622
        if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
5623
        else if (type == "," && prev == types[i+1] &&
5624
                 (prev == "1" || prev == "n")) types[i] = prev;
5625
        prev = type;
5626
      }
5627
5628
      // W5. A sequence of European terminators adjacent to European
5629
      // numbers changes to all European numbers.
5630
      // W6. Otherwise, separators and terminators change to Other
5631
      // Neutral.
5632
      for (var i = 0; i < len; ++i) {
5633
        var type = types[i];
5634
        if (type == ",") types[i] = "N";
5635
        else if (type == "%") {
5636
          for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
5637
          var replace = (i && types[i-1] == "!") || (end < len - 1 && types[end] == "1") ? "1" : "N";
5638
          for (var j = i; j < end; ++j) types[j] = replace;
5639
          i = end - 1;
5640
        }
5641
      }
5642
5643
      // W7. Search backwards from each instance of a European number
5644
      // until the first strong type (R, L, or sor) is found. If an L is
5645
      // found, then change the type of the European number to L.
5646
      for (var i = 0, cur = outerType; i < len; ++i) {
5647
        var type = types[i];
5648
        if (cur == "L" && type == "1") types[i] = "L";
5649
        else if (isStrong.test(type)) cur = type;
5650
      }
5651
5652
      // N1. A sequence of neutrals takes the direction of the
5653
      // surrounding strong text if the text on both sides has the same
5654
      // direction. European and Arabic numbers act as if they were R in
5655
      // terms of their influence on neutrals. Start-of-level-run (sor)
5656
      // and end-of-level-run (eor) are used at level run boundaries.
5657
      // N2. Any remaining neutrals take the embedding direction.
5658
      for (var i = 0; i < len; ++i) {
5659
        if (isNeutral.test(types[i])) {
5660
          for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
5661
          var before = (i ? types[i-1] : outerType) == "L";
5662
          var after = (end < len - 1 ? types[end] : outerType) == "L";
5663
          var replace = before || after ? "L" : "R";
5664
          for (var j = i; j < end; ++j) types[j] = replace;
5665
          i = end - 1;
5666
        }
5667
      }
5668
5669
      // Here we depart from the documented algorithm, in order to avoid
5670
      // building up an actual levels array. Since there are only three
5671
      // levels (0, 1, 2) in an implementation that doesn't take
5672
      // explicit embedding into account, we can build up the order on
5673
      // the fly, without following the level-based algorithm.
5674
      var order = [], m;
5675
      for (var i = 0; i < len;) {
5676
        if (countsAsLeft.test(types[i])) {
5677
          var start = i;
5678
          for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
5679
          order.push({from: start, to: i, level: 0});
5680
        } else {
5681
          var pos = i, at = order.length;
5682
          for (++i; i < len && types[i] != "L"; ++i) {}
5683
          for (var j = pos; j < i;) {
5684
            if (countsAsNum.test(types[j])) {
5685
              if (pos < j) order.splice(at, 0, {from: pos, to: j, level: 1});
5686
              var nstart = j;
5687
              for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
5688
              order.splice(at, 0, {from: nstart, to: j, level: 2});
5689
              pos = j;
5690
            } else ++j;
5691
          }
5692
          if (pos < i) order.splice(at, 0, {from: pos, to: i, level: 1});
5693
        }
5694
      }
5695
      if (order[0].level == 1 && (m = str.match(/^\s+/))) {
5696
        order[0].from = m[0].length;
5697
        order.unshift({from: 0, to: m[0].length, level: 0});
5698
      }
5699
      if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
5700
        lst(order).to -= m[0].length;
5701
        order.push({from: len - m[0].length, to: len, level: 0});
5702
      }
5703
      if (order[0].level != lst(order).level)
5704
        order.push({from: len, to: len, level: order[0].level});
5705
5706
      return order;
5707
    };
5708
  })();
5709
5710
  // THE END
5711
5712
  CodeMirror.version = "3.14.0";
5713
5714
  return CodeMirror;
5715
})();
(-)a/koha-tmpl/intranet-tmpl/lib/codemirror/lib/runmode.js (+56 lines)
Line 0 Link Here
1
CodeMirror.runMode = function(string, modespec, callback, options) {
2
  var mode = CodeMirror.getMode(CodeMirror.defaults, modespec);
3
  var ie = /MSIE \d/.test(navigator.userAgent);
4
  var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9);
5
6
  if (callback.nodeType == 1) {
7
    var tabSize = (options && options.tabSize) || CodeMirror.defaults.tabSize;
8
    var node = callback, col = 0;
9
    node.innerHTML = "";
10
    callback = function(text, style) {
11
      if (text == "\n") {
12
        // Emitting LF or CRLF on IE8 or earlier results in an incorrect display.
13
        // Emitting a carriage return makes everything ok.
14
        node.appendChild(document.createTextNode(ie_lt9 ? '\r' : text));
15
        col = 0;
16
        return;
17
      }
18
      var content = "";
19
      // replace tabs
20
      for (var pos = 0;;) {
21
        var idx = text.indexOf("\t", pos);
22
        if (idx == -1) {
23
          content += text.slice(pos);
24
          col += text.length - pos;
25
          break;
26
        } else {
27
          col += idx - pos;
28
          content += text.slice(pos, idx);
29
          var size = tabSize - col % tabSize;
30
          col += size;
31
          for (var i = 0; i < size; ++i) content += " ";
32
          pos = idx + 1;
33
        }
34
      }
35
36
      if (style) {
37
        var sp = node.appendChild(document.createElement("span"));
38
        sp.className = "cm-" + style.replace(/ +/g, " cm-");
39
        sp.appendChild(document.createTextNode(content));
40
      } else {
41
        node.appendChild(document.createTextNode(content));
42
      }
43
    };
44
  }
45
46
  var lines = CodeMirror.splitLines(string), state = CodeMirror.startState(mode);
47
  for (var i = 0, e = lines.length; i < e; ++i) {
48
    if (i) callback("\n");
49
    var stream = new CodeMirror.StringStream(lines[i]);
50
    while (!stream.eol()) {
51
      var style = mode.token(stream, state);
52
      callback(stream.current(), style, i, stream.start);
53
      stream.start = stream.pos;
54
    }
55
  }
56
};
(-)a/koha-tmpl/intranet-tmpl/lib/filesaver.js (+232 lines)
Line 0 Link Here
1
/* FileSaver.js
2
 * A saveAs() FileSaver implementation.
3
 * 2013-10-21
4
 *
5
 * By Eli Grey, http://eligrey.com
6
 * License: X11/MIT
7
 *   See LICENSE.md
8
 */
9
10
/*global self */
11
/*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
12
  plusplus: true */
13
14
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
15
16
var saveAs = saveAs
17
  || (typeof navigator !== 'undefined' && navigator.msSaveOrOpenBlob && navigator.msSaveOrOpenBlob.bind(navigator))
18
  || (function(view) {
19
	"use strict";
20
	var
21
		  doc = view.document
22
		  // only get URL when necessary in case BlobBuilder.js hasn't overridden it yet
23
		, get_URL = function() {
24
			return view.URL || view.webkitURL || view;
25
		}
26
		, URL = view.URL || view.webkitURL || view
27
		, save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
28
		, can_use_save_link =  !view.externalHost && "download" in save_link
29
		, click = function(node) {
30
			var event = doc.createEvent("MouseEvents");
31
			event.initMouseEvent(
32
				"click", true, false, view, 0, 0, 0, 0, 0
33
				, false, false, false, false, 0, null
34
			);
35
			node.dispatchEvent(event);
36
		}
37
		, webkit_req_fs = view.webkitRequestFileSystem
38
		, req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
39
		, throw_outside = function (ex) {
40
			(view.setImmediate || view.setTimeout)(function() {
41
				throw ex;
42
			}, 0);
43
		}
44
		, force_saveable_type = "application/octet-stream"
45
		, fs_min_size = 0
46
		, deletion_queue = []
47
		, process_deletion_queue = function() {
48
			var i = deletion_queue.length;
49
			while (i--) {
50
				var file = deletion_queue[i];
51
				if (typeof file === "string") { // file is an object URL
52
					URL.revokeObjectURL(file);
53
				} else { // file is a File
54
					file.remove();
55
				}
56
			}
57
			deletion_queue.length = 0; // clear queue
58
		}
59
		, dispatch = function(filesaver, event_types, event) {
60
			event_types = [].concat(event_types);
61
			var i = event_types.length;
62
			while (i--) {
63
				var listener = filesaver["on" + event_types[i]];
64
				if (typeof listener === "function") {
65
					try {
66
						listener.call(filesaver, event || filesaver);
67
					} catch (ex) {
68
						throw_outside(ex);
69
					}
70
				}
71
			}
72
		}
73
		, FileSaver = function(blob, name) {
74
			// First try a.download, then web filesystem, then object URLs
75
			var
76
				  filesaver = this
77
				, type = blob.type
78
				, blob_changed = false
79
				, object_url
80
				, target_view
81
				, get_object_url = function() {
82
					var object_url = get_URL().createObjectURL(blob);
83
					deletion_queue.push(object_url);
84
					return object_url;
85
				}
86
				, dispatch_all = function() {
87
					dispatch(filesaver, "writestart progress write writeend".split(" "));
88
				}
89
				// on any filesys errors revert to saving with object URLs
90
				, fs_error = function() {
91
					// don't create more object URLs than needed
92
					if (blob_changed || !object_url) {
93
						object_url = get_object_url(blob);
94
					}
95
					if (target_view) {
96
						target_view.location.href = object_url;
97
					} else {
98
                        window.open(object_url, "_blank");
99
                    }
100
					filesaver.readyState = filesaver.DONE;
101
					dispatch_all();
102
				}
103
				, abortable = function(func) {
104
					return function() {
105
						if (filesaver.readyState !== filesaver.DONE) {
106
							return func.apply(this, arguments);
107
						}
108
					};
109
				}
110
				, create_if_not_found = {create: true, exclusive: false}
111
				, slice
112
			;
113
			filesaver.readyState = filesaver.INIT;
114
			if (!name) {
115
				name = "download";
116
			}
117
			if (can_use_save_link) {
118
				object_url = get_object_url(blob);
119
				// FF for Android has a nasty garbage collection mechanism
120
				// that turns all objects that are not pure javascript into 'deadObject'
121
				// this means `doc` and `save_link` are unusable and need to be recreated
122
				// `view` is usable though:
123
				doc = view.document;
124
				save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a");
125
				save_link.href = object_url;
126
				save_link.download = name;
127
				var event = doc.createEvent("MouseEvents");
128
				event.initMouseEvent(
129
					"click", true, false, view, 0, 0, 0, 0, 0
130
					, false, false, false, false, 0, null
131
				);
132
				save_link.dispatchEvent(event);
133
				filesaver.readyState = filesaver.DONE;
134
				dispatch_all();
135
				return;
136
			}
137
			// Object and web filesystem URLs have a problem saving in Google Chrome when
138
			// viewed in a tab, so I force save with application/octet-stream
139
			// http://code.google.com/p/chromium/issues/detail?id=91158
140
			if (view.chrome && type && type !== force_saveable_type) {
141
				slice = blob.slice || blob.webkitSlice;
142
				blob = slice.call(blob, 0, blob.size, force_saveable_type);
143
				blob_changed = true;
144
			}
145
			// Since I can't be sure that the guessed media type will trigger a download
146
			// in WebKit, I append .download to the filename.
147
			// https://bugs.webkit.org/show_bug.cgi?id=65440
148
			if (webkit_req_fs && name !== "download") {
149
				name += ".download";
150
			}
151
			if (type === force_saveable_type || webkit_req_fs) {
152
				target_view = view;
153
			}
154
			if (!req_fs) {
155
				fs_error();
156
				return;
157
			}
158
			fs_min_size += blob.size;
159
			req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) {
160
				fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) {
161
					var save = function() {
162
						dir.getFile(name, create_if_not_found, abortable(function(file) {
163
							file.createWriter(abortable(function(writer) {
164
								writer.onwriteend = function(event) {
165
									target_view.location.href = file.toURL();
166
									deletion_queue.push(file);
167
									filesaver.readyState = filesaver.DONE;
168
									dispatch(filesaver, "writeend", event);
169
								};
170
								writer.onerror = function() {
171
									var error = writer.error;
172
									if (error.code !== error.ABORT_ERR) {
173
										fs_error();
174
									}
175
								};
176
								"writestart progress write abort".split(" ").forEach(function(event) {
177
									writer["on" + event] = filesaver["on" + event];
178
								});
179
								writer.write(blob);
180
								filesaver.abort = function() {
181
									writer.abort();
182
									filesaver.readyState = filesaver.DONE;
183
								};
184
								filesaver.readyState = filesaver.WRITING;
185
							}), fs_error);
186
						}), fs_error);
187
					};
188
					dir.getFile(name, {create: false}, abortable(function(file) {
189
						// delete file if it already exists
190
						file.remove();
191
						save();
192
					}), abortable(function(ex) {
193
						if (ex.code === ex.NOT_FOUND_ERR) {
194
							save();
195
						} else {
196
							fs_error();
197
						}
198
					}));
199
				}), fs_error);
200
			}), fs_error);
201
		}
202
		, FS_proto = FileSaver.prototype
203
		, saveAs = function(blob, name) {
204
			return new FileSaver(blob, name);
205
		}
206
	;
207
	FS_proto.abort = function() {
208
		var filesaver = this;
209
		filesaver.readyState = filesaver.DONE;
210
		dispatch(filesaver, "abort");
211
	};
212
	FS_proto.readyState = FS_proto.INIT = 0;
213
	FS_proto.WRITING = 1;
214
	FS_proto.DONE = 2;
215
216
	FS_proto.error =
217
	FS_proto.onwritestart =
218
	FS_proto.onprogress =
219
	FS_proto.onwrite =
220
	FS_proto.onabort =
221
	FS_proto.onerror =
222
	FS_proto.onwriteend =
223
		null;
224
225
	view.addEventListener("unload", process_deletion_queue, false);
226
	return saveAs;
227
}(this.self || this.window || this.content));
228
// `self` is undefined in Firefox for Android content script context
229
// while `this` is nsIContentFrameMessageManager
230
// with an attribute `content` that corresponds to the window
231
232
if (typeof module !== 'undefined') module.exports = saveAs;
(-)a/koha-tmpl/intranet-tmpl/lib/pz2.js (+1116 lines)
Line 0 Link Here
1
/*
2
 * $Id: 3a9980787bb5d0fe966140b243a4a5eb6768913e $
3
** pz2.js - pazpar2's javascript client library.
4
*/
5
6
/**
7
 * Additions to support custom settings for Koha
8
 * Modified by Jesse Weaver
9
 */
10
11
//since explorer is flawed
12
if (!window['Node']) {
13
    window.Node = new Object();
14
    Node.ELEMENT_NODE = 1;
15
    Node.ATTRIBUTE_NODE = 2;
16
    Node.TEXT_NODE = 3;
17
    Node.CDATA_SECTION_NODE = 4;
18
    Node.ENTITY_REFERENCE_NODE = 5;
19
    Node.ENTITY_NODE = 6;
20
    Node.PROCESSING_INSTRUCTION_NODE = 7;
21
    Node.COMMENT_NODE = 8;
22
    Node.DOCUMENT_NODE = 9;
23
    Node.DOCUMENT_TYPE_NODE = 10;
24
    Node.DOCUMENT_FRAGMENT_NODE = 11;
25
    Node.NOTATION_NODE = 12;
26
}
27
28
// prevent execution of more than once
29
if(typeof window.pz2 == "undefined") {
30
window.undefined = window.undefined;
31
32
var pz2 = function ( paramArray )
33
{
34
35
    // at least one callback required
36
    if ( !paramArray )
37
        throw new Error("Pz2.js: Array with parameters has to be supplied.");
38
39
    //supported pazpar2's protocol version
40
    this.suppProtoVer = '1';
41
    if (typeof paramArray.pazpar2path != "undefined")
42
        this.pz2String = paramArray.pazpar2path;
43
    else
44
        this.pz2String = "/pazpar2/search.pz2";
45
    this.useSessions = true;
46
47
    this.stylesheet = paramArray.detailstylesheet || null;
48
    //load stylesheet if required in async mode
49
    if( this.stylesheet ) {
50
        var context = this;
51
        var request = new pzHttpRequest( this.stylesheet );
52
        request.get( {}, function ( doc ) { context.xslDoc = doc; } );
53
    }
54
55
    this.errorHandler = paramArray.errorhandler || null;
56
    this.showResponseType = paramArray.showResponseType || "xml";
57
58
    // function callbacks
59
    this.initCallback = paramArray.oninit || null;
60
    this.statCallback = paramArray.onstat || null;
61
    this.showCallback = paramArray.onshow || null;
62
    this.termlistCallback = paramArray.onterm || null;
63
    this.recordCallback = paramArray.onrecord || null;
64
    this.bytargetCallback = paramArray.onbytarget || null;
65
    this.resetCallback = paramArray.onreset || null;
66
67
    // termlist keys
68
    this.termKeys = paramArray.termlist || "subject";
69
70
    // some configurational stuff
71
    this.keepAlive = 50000;
72
73
    if ( paramArray.keepAlive < this.keepAlive )
74
        this.keepAlive = paramArray.keepAlive;
75
76
    this.sessionID = null;
77
    this.serviceId = paramArray.serviceId || null;
78
    this.initStatusOK = false;
79
    this.pingStatusOK = false;
80
    this.searchStatusOK = false;
81
82
    // for sorting
83
    this.currentSort = "relevance";
84
85
    // where are we?
86
    this.currentStart = 0;
87
    // currentNum can be overwritten in show
88
    this.currentNum = 20;
89
90
    // last full record retrieved
91
    this.currRecID = null;
92
93
    // current query
94
    this.currQuery = null;
95
96
    //current raw record offset
97
    this.currRecOffset = null;
98
99
    //timers
100
    this.pingTimer = null;
101
    this.statTime = paramArray.stattime || 1000;
102
    this.statTimer = null;
103
    this.termTime = paramArray.termtime || 1000;
104
    this.termTimer = null;
105
    this.showTime = paramArray.showtime || 1000;
106
    this.showTimer = null;
107
    this.showFastCount = 4;
108
    this.bytargetTime = paramArray.bytargettime || 1000;
109
    this.bytargetTimer = null;
110
    this.recordTime = paramArray.recordtime || 500;
111
    this.recordTimer = null;
112
113
    // counters for each command and applied delay
114
    this.dumpFactor = 500;
115
    this.showCounter = 0;
116
    this.termCounter = 0;
117
    this.statCounter = 0;
118
    this.bytargetCounter = 0;
119
    this.recordCounter = 0;
120
121
    // active clients, updated by stat and show
122
    // might be an issue since bytarget will poll accordingly
123
    this.activeClients = 1;
124
125
    // if in proxy mode no need to init
126
    if (paramArray.usesessions != undefined) {
127
         this.useSessions = paramArray.usesessions;
128
        this.initStatusOK = true;
129
    }
130
    // else, auto init session or wait for a user init?
131
    if (this.useSessions && paramArray.autoInit !== false) {
132
        this.init(this.sessionID, paramArray.initopts);
133
    }
134
    // Version parameter
135
    this.version = paramArray.version || null;
136
};
137
138
pz2.prototype =
139
{
140
    //error handler for async error throws
141
   throwError: function (errMsg, errCode)
142
   {
143
        var err = new Error(errMsg);
144
        if (errCode) err.code = errCode;
145
146
        if (this.errorHandler) {
147
            this.errorHandler(err);
148
        }
149
        else {
150
            throw err;
151
        }
152
   },
153
154
    // stop activity by clearing tiemouts
155
   stop: function ()
156
   {
157
       clearTimeout(this.statTimer);
158
       clearTimeout(this.showTimer);
159
       clearTimeout(this.termTimer);
160
       clearTimeout(this.bytargetTimer);
161
    },
162
163
    // reset status variables
164
    reset: function ()
165
    {
166
        if ( this.useSessions ) {
167
            this.sessionID = null;
168
            this.initStatusOK = false;
169
            this.pingStatusOK = false;
170
            clearTimeout(this.pingTimer);
171
        }
172
        this.searchStatusOK = false;
173
        this.stop();
174
175
        if ( this.resetCallback )
176
                this.resetCallback();
177
    },
178
179
    init: function (sessionId, initOpts)
180
    {
181
        this.reset();
182
183
        // session id as a param
184
        if (sessionId && this.useSessions ) {
185
            this.initStatusOK = true;
186
            this.sessionID = sessionId;
187
            this.ping();
188
        // old school direct pazpar2 init
189
        } else if (this.useSessions) {
190
            var context = this;
191
            var request = new pzHttpRequest(this.pz2String, this.errorHandler);
192
            initOpts = initOpts || {};
193
            initOpts.command = 'init';
194
            request.safeGet(
195
                initOpts,
196
                function(data) {
197
                    if ( data.getElementsByTagName("status")[0]
198
                            .childNodes[0].nodeValue == "OK" ) {
199
                        if ( data.getElementsByTagName("protocol")[0]
200
                                .childNodes[0].nodeValue
201
                            != context.suppProtoVer )
202
                            throw new Error(
203
                                "Server's protocol not supported by the client"
204
                            );
205
                        context.initStatusOK = true;
206
                        context.sessionID =
207
                            data.getElementsByTagName("session")[0]
208
                                .childNodes[0].nodeValue;
209
                        if (data.getElementsByTagName("keepAlive").length > 0) {
210
                            context.keepAlive = data.getElementsByTagName("keepAlive")[0].childNodes[0].nodeValue;
211
                        }
212
                        context.pingTimer =
213
                            setTimeout(
214
                                function () {
215
                                    context.ping();
216
                                },
217
                                context.keepAlive
218
                            );
219
                        if ( context.initCallback )
220
                            context.initCallback();
221
                    }
222
                    else
223
                        context.throwError('Init failed. Malformed WS resonse.',
224
                                            110);
225
                }
226
            );
227
        // when through proxy no need to init
228
        } else {
229
            this.initStatusOK = true;
230
	}
231
    },
232
    // no need to ping explicitly
233
    ping: function ()
234
    {
235
        // pinging only makes sense when using pazpar2 directly
236
        if( !this.initStatusOK || !this.useSessions )
237
            throw new Error(
238
            'Pz2.js: Ping not allowed (proxy mode) or session not initialized.'
239
            );
240
        var context = this;
241
242
        clearTimeout(context.pingTimer);
243
244
        var request = new pzHttpRequest(this.pz2String, this.errorHandler);
245
        request.safeGet(
246
            { "command": "ping", "session": this.sessionID, "windowid" : window.name },
247
            function(data) {
248
                if ( data.getElementsByTagName("status")[0]
249
                        .childNodes[0].nodeValue == "OK" ) {
250
                    context.pingStatusOK = true;
251
                    context.pingTimer =
252
                        setTimeout(
253
                            function () {
254
                                context.ping();
255
                            },
256
                            context.keepAlive
257
                        );
258
                }
259
                else
260
                    context.throwError('Ping failed. Malformed WS resonse.',
261
                                        111);
262
            }
263
        );
264
    },
265
    search: function (query, num, sort, filter, showfrom, addParamsArr)
266
    {
267
        clearTimeout(this.statTimer);
268
        clearTimeout(this.showTimer);
269
        clearTimeout(this.termTimer);
270
        clearTimeout(this.bytargetTimer);
271
272
        this.showCounter = 0;
273
        this.termCounter = 0;
274
        this.bytargetCounter = 0;
275
        this.statCounter = 0;
276
        this.activeClients = 1;
277
278
        // no proxy mode
279
        if( !this.initStatusOK )
280
            throw new Error('Pz2.js: session not initialized.');
281
282
        if( query !== undefined )
283
            this.currQuery = query;
284
        else
285
            throw new Error("Pz2.js: no query supplied to the search command.");
286
287
        if ( showfrom !== undefined )
288
            var start = showfrom;
289
        else
290
            var start = 0;
291
292
	var searchParams = {
293
          "command": "search",
294
          "query": this.currQuery,
295
          "session": this.sessionID,
296
          "windowid" : window.name
297
        };
298
299
        if( sort !== undefined ) {
300
            this.currentSort = sort;
301
	    searchParams["sort"] = sort;
302
	}
303
        if (filter !== undefined)
304
	        searchParams["filter"] = filter;
305
306
        // copy additional parmeters, do not overwrite
307
        if (addParamsArr != undefined) {
308
            for (var prop in addParamsArr) {
309
                if (!searchParams.hasOwnProperty(prop))
310
                    searchParams[prop] = addParamsArr[prop];
311
            }
312
        }
313
314
        var context = this;
315
        var request = new pzHttpRequest(this.pz2String, this.errorHandler);
316
        request.safeGet(
317
            searchParams,
318
            function(data) {
319
                if ( data.getElementsByTagName("status")[0]
320
                        .childNodes[0].nodeValue == "OK" ) {
321
                    context.searchStatusOK = true;
322
                    //piggyback search
323
                    if (context.showCallback)
324
                        context.show(start, num, sort);
325
                    if (context.statCallback)
326
                        context.stat();
327
                    if (context.termlistCallback)
328
                        context.termlist();
329
                    if (context.bytargetCallback)
330
                        context.bytarget();
331
                }
332
                else
333
                    context.throwError('Search failed. Malformed WS resonse.',
334
                                        112);
335
            }
336
        );
337
    },
338
    stat: function()
339
    {
340
        if( !this.initStatusOK )
341
            throw new Error('Pz2.js: session not initialized.');
342
343
        // if called explicitly takes precedence
344
        clearTimeout(this.statTimer);
345
346
        var context = this;
347
        var request = new pzHttpRequest(this.pz2String, this.errorHandler);
348
        request.safeGet(
349
            { "command": "stat", "session": this.sessionID, "windowid" : window.name },
350
            function(data) {
351
                if ( data.getElementsByTagName("stat") ) {
352
                    var activeClients =
353
                        Number( data.getElementsByTagName("activeclients")[0]
354
                                    .childNodes[0].nodeValue );
355
                    context.activeClients = activeClients;
356
357
		    var stat = Element_parseChildNodes(data.documentElement);
358
359
                    context.statCounter++;
360
		    var delay = context.statTime
361
                        + context.statCounter * context.dumpFactor;
362
363
                    if ( activeClients > 0 )
364
                        context.statTimer =
365
                            setTimeout(
366
                                function () {
367
                                    context.stat();
368
                                },
369
                                delay
370
                            );
371
                    context.statCallback(stat);
372
                }
373
                else
374
                    context.throwError('Stat failed. Malformed WS resonse.',
375
                                        113);
376
            }
377
        );
378
    },
379
    show: function(start, num, sort, query_state)
380
    {
381
        if( !this.searchStatusOK && this.useSessions )
382
            throw new Error(
383
                'Pz2.js: show command has to be preceded with a search command.'
384
            );
385
386
        // if called explicitly takes precedence
387
        clearTimeout(this.showTimer);
388
389
        if( sort !== undefined )
390
            this.currentSort = sort;
391
        if( start !== undefined )
392
            this.currentStart = Number( start );
393
        if( num !== undefined )
394
            this.currentNum = Number( num );
395
396
        var context = this;
397
        var request = new pzHttpRequest(this.pz2String, this.errorHandler);
398
	var requestParameters =
399
          {
400
              "command": "show",
401
              "session": this.sessionID,
402
              "start": this.currentStart,
403
              "num": this.currentNum,
404
              "sort": this.currentSort,
405
              "block": 1,
406
              "type": this.showResponseType,
407
              "windowid" : window.name
408
          };
409
        if (query_state)
410
          requestParameters["query-state"] = query_state;
411
	if (this.version && this.version > 0)
412
	    requestParameters["version"] = this.version;
413
        request.safeGet(
414
	  requestParameters,
415
          function(data, type) {
416
            var show = null;
417
            var activeClients = 0;
418
            if (type === "json") {
419
              show = {};
420
              activeClients = Number(data.activeclients[0]);
421
              show.activeclients = activeClients;
422
              show.merged = Number(data.merged[0]);
423
              show.total = Number(data.total[0]);
424
              show.start = Number(data.start[0]);
425
              show.num = Number(data.num[0]);
426
              show.hits = data.hit;
427
            } else if (data.getElementsByTagName("status")[0]
428
                  .childNodes[0].nodeValue == "OK") {
429
                // first parse the status data send along with records
430
                // this is strictly bound to the format
431
                activeClients =
432
                  Number(data.getElementsByTagName("activeclients")[0]
433
                      .childNodes[0].nodeValue);
434
                show = {
435
                  "activeclients": activeClients,
436
                  "merged":
437
                    Number( data.getElementsByTagName("merged")[0]
438
                        .childNodes[0].nodeValue ),
439
                  "total":
440
                    Number( data.getElementsByTagName("total")[0]
441
                        .childNodes[0].nodeValue ),
442
                  "start":
443
                    Number( data.getElementsByTagName("start")[0]
444
                        .childNodes[0].nodeValue ),
445
                  "num":
446
                    Number( data.getElementsByTagName("num")[0]
447
                        .childNodes[0].nodeValue ),
448
                  "hits": []
449
                };
450
                // parse all the first-level nodes for all <hit> tags
451
                var hits = data.getElementsByTagName("hit");
452
                for (i = 0; i < hits.length; i++)
453
                  show.hits[i] = Element_parseChildNodes(hits[i]);
454
            } else {
455
              context.throwError('Show failed. Malformed WS resonse.',
456
                  114);
457
            };
458
459
	    var approxNode = data.getElementsByTagName("approximation");
460
	    if (approxNode && approxNode[0] && approxNode[0].childNodes[0] && approxNode[0].childNodes[0].nodeValue)
461
		show['approximation'] =
462
		  Number( approxNode[0].childNodes[0].nodeValue);
463
464
465
	      data.getElementsByTagName("")
466
            context.activeClients = activeClients;
467
            context.showCounter++;
468
            var delay = context.showTime;
469
            if (context.showCounter > context.showFastCount)
470
              delay += context.showCounter * context.dumpFactor;
471
            if ( activeClients > 0 )
472
              context.showTimer = setTimeout(
473
                function () {
474
                  context.show();
475
                },
476
                delay);
477
            context.showCallback(show);
478
          }
479
        );
480
    },
481
    record: function(id, offset, syntax, handler)
482
    {
483
        // we may call record with no previous search if in proxy mode
484
        if(!this.searchStatusOK && this.useSessions)
485
           throw new Error(
486
            'Pz2.js: record command has to be preceded with a search command.'
487
            );
488
489
        if( id !== undefined )
490
            this.currRecID = id;
491
492
	var recordParams = {
493
            "command": "record",
494
            "session": this.sessionID,
495
            "id": this.currRecID,
496
            "windowid" : window.name
497
        };
498
499
	this.currRecOffset = null;
500
        if (offset != undefined) {
501
	    recordParams["offset"] = offset;
502
            this.currRecOffset = offset;
503
        }
504
505
        if (syntax != undefined)
506
            recordParams['syntax'] = syntax;
507
508
        //overwrite default callback id needed
509
        var callback = this.recordCallback;
510
        var args = undefined;
511
        if (handler != undefined) {
512
            callback = handler['callback'];
513
            args = handler['args'];
514
        }
515
516
        var context = this;
517
        var request = new pzHttpRequest(this.pz2String, this.errorHandler);
518
519
        request.safeGet(
520
	    recordParams,
521
            function(data) {
522
                var recordNode;
523
                var record;
524
                //raw record
525
                if (context.currRecOffset !== null) {
526
                    record = new Array();
527
                    record['xmlDoc'] = data;
528
                    record['offset'] = context.currRecOffset;
529
                    callback(record, args);
530
                //pz2 record
531
                } else if ( recordNode =
532
                    data.getElementsByTagName("record")[0] ) {
533
                    // if stylesheet was fetched do not parse the response
534
                    if ( context.xslDoc ) {
535
                        record = new Array();
536
                        record['xmlDoc'] = data;
537
                        record['xslDoc'] = context.xslDoc;
538
                        record['recid'] =
539
                            recordNode.getElementsByTagName("recid")[0]
540
                                .firstChild.nodeValue;
541
                    //parse record
542
                    } else {
543
                        record = Element_parseChildNodes(recordNode);
544
                    }
545
		    var activeClients =
546
		       Number( data.getElementsByTagName("activeclients")[0]
547
				.childNodes[0].nodeValue );
548
		    context.activeClients = activeClients;
549
                    context.recordCounter++;
550
                    var delay = context.recordTime + context.recordCounter * context.dumpFactor;
551
                    if ( activeClients > 0 )
552
                        context.recordTimer =
553
                           setTimeout (
554
                               function() {
555
                                  context.record(id, offset, syntax, handler);
556
                                  },
557
                                  delay
558
                               );
559
                    callback(record, args);
560
                }
561
                else
562
                    context.throwError('Record failed. Malformed WS resonse.',
563
                                        115);
564
            }
565
        );
566
    },
567
568
    termlist: function()
569
    {
570
        if( !this.searchStatusOK && this.useSessions )
571
            throw new Error(
572
            'Pz2.js: termlist command has to be preceded with a search command.'
573
            );
574
575
        // if called explicitly takes precedence
576
        clearTimeout(this.termTimer);
577
578
        var context = this;
579
        var request = new pzHttpRequest(this.pz2String, this.errorHandler);
580
        request.safeGet(
581
            {
582
                "command": "termlist",
583
                "session": this.sessionID,
584
                "name": this.termKeys,
585
                "windowid" : window.name,
586
		"version" : this.version
587
588
            },
589
            function(data) {
590
                if ( data.getElementsByTagName("termlist") ) {
591
                    var activeClients =
592
                        Number( data.getElementsByTagName("activeclients")[0]
593
                                    .childNodes[0].nodeValue );
594
                    context.activeClients = activeClients;
595
                    var termList = { "activeclients":  activeClients };
596
                    var termLists = data.getElementsByTagName("list");
597
                    //for each termlist
598
                    for (i = 0; i < termLists.length; i++) {
599
			var listName = termLists[i].getAttribute('name');
600
                        termList[listName] = new Array();
601
                        var terms = termLists[i].getElementsByTagName('term');
602
                        //for each term in the list
603
                        for (j = 0; j < terms.length; j++) {
604
                            var term = {
605
                                "name":
606
                                    (terms[j].getElementsByTagName("name")[0]
607
                                        .childNodes.length
608
                                    ? terms[j].getElementsByTagName("name")[0]
609
                                        .childNodes[0].nodeValue
610
                                    : 'ERROR'),
611
                                "freq":
612
                                    terms[j]
613
                                    .getElementsByTagName("frequency")[0]
614
                                    .childNodes[0].nodeValue || 'ERROR'
615
                            };
616
617
			    // Only for xtargets: id, records, filtered
618
                            var termIdNode =
619
                                terms[j].getElementsByTagName("id");
620
                            if(terms[j].getElementsByTagName("id").length)
621
                                term["id"] =
622
                                    termIdNode[0].childNodes[0].nodeValue;
623
                            termList[listName][j] = term;
624
625
			    var recordsNode  = terms[j].getElementsByTagName("records");
626
			    if (recordsNode && recordsNode.length)
627
				term["records"] = recordsNode[0].childNodes[0].nodeValue;
628
629
			    var filteredNode  = terms[j].getElementsByTagName("filtered");
630
			    if (filteredNode && filteredNode.length)
631
				term["filtered"] = filteredNode[0].childNodes[0].nodeValue;
632
633
                        }
634
                    }
635
636
                    context.termCounter++;
637
                    var delay = context.termTime
638
                        + context.termCounter * context.dumpFactor;
639
                    if ( activeClients > 0 )
640
                        context.termTimer =
641
                            setTimeout(
642
                                function () {
643
                                    context.termlist();
644
                                },
645
                                delay
646
                            );
647
648
                   context.termlistCallback(termList);
649
                }
650
                else
651
                    context.throwError('Termlist failed. Malformed WS resonse.',
652
                                        116);
653
            }
654
        );
655
656
    },
657
    bytarget: function()
658
    {
659
        if( !this.initStatusOK && this.useSessions )
660
            throw new Error(
661
            'Pz2.js: bytarget command has to be preceded with a search command.'
662
            );
663
664
        // no need to continue
665
        if( !this.searchStatusOK )
666
            return;
667
668
        // if called explicitly takes precedence
669
        clearTimeout(this.bytargetTimer);
670
671
        var context = this;
672
        var request = new pzHttpRequest(this.pz2String, this.errorHandler);
673
        request.safeGet(
674
            {
675
		"command": "bytarget",
676
		"session": this.sessionID,
677
		"block": 1,
678
		"windowid" : window.name,
679
		"version" : this.version
680
	    },
681
            function(data) {
682
                if ( data.getElementsByTagName("status")[0]
683
                        .childNodes[0].nodeValue == "OK" ) {
684
                    var targetNodes = data.getElementsByTagName("target");
685
                    var bytarget = new Array();
686
                    for ( i = 0; i < targetNodes.length; i++) {
687
                        bytarget[i] = new Array();
688
                        for( j = 0; j < targetNodes[i].childNodes.length; j++ ) {
689
                            if ( targetNodes[i].childNodes[j].nodeType
690
                                == Node.ELEMENT_NODE ) {
691
                                var nodeName =
692
                                    targetNodes[i].childNodes[j].nodeName;
693
				if (targetNodes[i].childNodes[j].firstChild != null)
694
				{
695
                                    var nodeText = targetNodes[i].childNodes[j]
696
					.firstChild.nodeValue;
697
                                    bytarget[i][nodeName] = nodeText;
698
				}
699
				else {
700
				    bytarget[i][nodeName] = "";
701
				}
702
703
704
                            }
705
                        }
706
                        if (bytarget[i]["state"]=="Client_Disconnected") {
707
                          bytarget[i]["hits"] = "Error";
708
                        } else if (bytarget[i]["state"]=="Client_Error") {
709
                          bytarget[i]["hits"] = "Error";
710
                        } else if (bytarget[i]["state"]=="Client_Working") {
711
                          bytarget[i]["hits"] = "...";
712
                        }
713
                        if (bytarget[i].diagnostic == "1") {
714
                          bytarget[i].diagnostic = "Permanent system error";
715
                        } else if (bytarget[i].diagnostic == "2") {
716
                          bytarget[i].diagnostic = "Temporary system error";
717
                        }
718
                        var targetsSuggestions = targetNodes[i].getElementsByTagName("suggestions");
719
                        if (targetsSuggestions != undefined && targetsSuggestions.length>0) {
720
                          var suggestions = targetsSuggestions[0];
721
                          bytarget[i]["suggestions"] = Element_parseChildNodes(suggestions);
722
                        }
723
                    }
724
725
                    context.bytargetCounter++;
726
                    var delay = context.bytargetTime
727
                        + context.bytargetCounter * context.dumpFactor;
728
                    if ( context.activeClients > 0 )
729
                        context.bytargetTimer =
730
                            setTimeout(
731
                                function () {
732
                                    context.bytarget();
733
                                },
734
                                delay
735
                            );
736
737
                    context.bytargetCallback(bytarget);
738
                }
739
                else
740
                    context.throwError('Bytarget failed. Malformed WS resonse.',
741
                                        117);
742
            }
743
        );
744
    },
745
746
    // just for testing, probably shouldn't be here
747
    showNext: function(page)
748
    {
749
        var step = page || 1;
750
        this.show( ( step * this.currentNum ) + this.currentStart );
751
    },
752
753
    showPrev: function(page)
754
    {
755
        if (this.currentStart == 0 )
756
            return false;
757
        var step = page || 1;
758
        var newStart = this.currentStart - (step * this.currentNum );
759
        this.show( newStart > 0 ? newStart : 0 );
760
    },
761
762
    showPage: function(pageNum)
763
    {
764
        //var page = pageNum || 1;
765
        this.show(pageNum * this.currentNum);
766
    }
767
};
768
769
/*
770
********************************************************************************
771
** AJAX HELPER CLASS ***********************************************************
772
********************************************************************************
773
*/
774
var pzHttpRequest = function ( url, errorHandler ) {
775
        this.maxUrlLength = 2048;
776
        this.request = null;
777
        this.url = url;
778
        this.errorHandler = errorHandler || null;
779
        this.async = true;
780
        this.requestHeaders = {};
781
782
        if ( window.XMLHttpRequest ) {
783
            this.request = new XMLHttpRequest();
784
        } else if ( window.ActiveXObject ) {
785
            try {
786
                this.request = new ActiveXObject( 'Msxml2.XMLHTTP' );
787
            } catch (err) {
788
                this.request = new ActiveXObject( 'Microsoft.XMLHTTP' );
789
            }
790
        }
791
};
792
793
794
pzHttpRequest.prototype =
795
{
796
    safeGet: function ( params, callback )
797
    {
798
        var encodedParams =  this.encodeParams(params);
799
        var url = this._urlAppendParams(encodedParams);
800
        if (url.length >= this.maxUrlLength) {
801
            this.requestHeaders["Content-Type"]
802
                = "application/x-www-form-urlencoded";
803
            this._send( 'POST', this.url, encodedParams, callback );
804
        } else {
805
            this._send( 'GET', url, '', callback );
806
        }
807
    },
808
809
    get: function ( params, callback )
810
    {
811
        this._send( 'GET', this._urlAppendParams(this.encodeParams(params)),
812
            '', callback );
813
    },
814
815
    post: function ( params, data, callback )
816
    {
817
        this._send( 'POST', this._urlAppendParams(this.encodeParams(params)),
818
            data, callback );
819
    },
820
821
    load: function ()
822
    {
823
        this.async = false;
824
        this.request.open( 'GET', this.url, this.async );
825
        this.request.send('');
826
        if ( this.request.status == 200 )
827
            return this.request.responseXML;
828
    },
829
830
    encodeParams: function (params)
831
    {
832
        var sep = "";
833
        var encoded = "";
834
        for (var key in params) {
835
            if (params[key] != null) {
836
                encoded += sep + key + '=' + encodeURIComponent(params[key]);
837
                sep = '&';
838
            }
839
        }
840
        return encoded;
841
    },
842
843
    _send: function ( type, url, data, callback)
844
    {
845
        var context = this;
846
        this.callback = callback;
847
        this.async = true;
848
        this.request.open( type, url, this.async );
849
        for (var key in this.requestHeaders)
850
            this.request.setRequestHeader(key, this.requestHeaders[key]);
851
        this.request.onreadystatechange = function () {
852
            context._handleResponse(url); /// url used ONLY for error reporting
853
        }
854
        this.request.send(data);
855
    },
856
857
    _urlAppendParams: function (encodedParams)
858
    {
859
        if (encodedParams)
860
            return this.url + "?" + encodedParams;
861
        else
862
            return this.url;
863
    },
864
865
    _handleResponse: function (savedUrlForErrorReporting)
866
    {
867
        if ( this.request.readyState == 4 ) {
868
            // pick up appplication errors first
869
            var errNode = null;
870
            if (this.request.responseXML &&
871
                (errNode = this.request.responseXML.documentElement)
872
                && errNode.nodeName == 'error') {
873
                var errMsg = errNode.getAttribute("msg");
874
                var errCode = errNode.getAttribute("code");
875
                var errAddInfo = '';
876
                if (errNode.childNodes.length)
877
                    errAddInfo = ': ' + errNode.childNodes[0].nodeValue;
878
879
                var err = new Error(errMsg + errAddInfo);
880
                err.code = errCode;
881
882
                if (this.errorHandler) {
883
                    this.errorHandler(err);
884
                }
885
                else {
886
                    throw err;
887
                }
888
            } else if (this.request.status == 200 &&
889
                       this.request.responseXML == null) {
890
              if (this.request.responseText != null) {
891
                //assume JSON
892
893
		var json = null;
894
		var text = this.request.responseText;
895
		if (typeof window.JSON == "undefined")
896
		    json = eval("(" + text + ")");
897
		else {
898
		    try	{
899
			json = JSON.parse(text);
900
		    }
901
		    catch (e) {
902
			// Safari: eval will fail as well. Considering trying JSON2 (non-native implementation) instead
903
			/* DEBUG only works in mk2-mobile
904
			if (document.getElementById("log"))
905
			    document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
906
			*/
907
			try {
908
			    json = eval("(" + text + ")");
909
			}
910
			catch (e) {
911
			    /* DEBUG only works in mk2-mobile
912
			    if (document.getElementById("log"))
913
				document.getElementById("log").innerHTML = "" + e + " " + length + ": " + text;
914
			    */
915
			}
916
		    }
917
		}
918
		this.callback(json, "json");
919
              } else {
920
                var err = new Error("XML response is empty but no error " +
921
                                    "for " + savedUrlForErrorReporting);
922
                err.code = -1;
923
                if (this.errorHandler) {
924
                    this.errorHandler(err);
925
                } else {
926
                    throw err;
927
                }
928
              }
929
            } else if (this.request.status == 200) {
930
                this.callback(this.request.responseXML);
931
            } else {
932
                var err = new Error("HTTP response not OK: "
933
                            + this.request.status + " - "
934
                            + this.request.statusText );
935
                err.code = '00' + this.request.status;
936
                if (this.errorHandler) {
937
                    this.errorHandler(err);
938
                }
939
                else {
940
                    throw err;
941
                }
942
            }
943
        }
944
    }
945
};
946
947
/*
948
********************************************************************************
949
** XML HELPER FUNCTIONS ********************************************************
950
********************************************************************************
951
*/
952
953
// DOMDocument
954
955
if ( window.ActiveXObject) {
956
    var DOMDoc = document;
957
} else {
958
    var DOMDoc = Document.prototype;
959
}
960
961
DOMDoc.newXmlDoc = function ( root )
962
{
963
    var doc;
964
965
    if (document.implementation && document.implementation.createDocument) {
966
        doc = document.implementation.createDocument('', root, null);
967
    } else if ( window.ActiveXObject ) {
968
        doc = new ActiveXObject("MSXML2.DOMDocument");
969
        doc.loadXML('<' + root + '/>');
970
    } else {
971
        throw new Error ('No XML support in this browser');
972
    }
973
974
    return doc;
975
}
976
977
978
DOMDoc.parseXmlFromString = function ( xmlString )
979
{
980
    var doc;
981
982
    if ( window.DOMParser ) {
983
        var parser = new DOMParser();
984
        doc = parser.parseFromString( xmlString, "text/xml");
985
    } else if ( window.ActiveXObject ) {
986
        doc = new ActiveXObject("MSXML2.DOMDocument");
987
        doc.loadXML( xmlString );
988
    } else {
989
        throw new Error ("No XML parsing support in this browser.");
990
    }
991
992
    return doc;
993
}
994
995
DOMDoc.transformToDoc = function (xmlDoc, xslDoc)
996
{
997
    if ( window.XSLTProcessor ) {
998
        var proc = new XSLTProcessor();
999
        proc.importStylesheet( xslDoc );
1000
        return proc.transformToDocument(xmlDoc);
1001
    } else if ( window.ActiveXObject ) {
1002
        return document.parseXmlFromString(xmlDoc.transformNode(xslDoc));
1003
    } else {
1004
        alert( 'Unable to perform XSLT transformation in this browser' );
1005
    }
1006
}
1007
1008
// DOMElement
1009
1010
Element_removeFromDoc = function (DOM_Element)
1011
{
1012
    DOM_Element.parentNode.removeChild(DOM_Element);
1013
}
1014
1015
Element_emptyChildren = function (DOM_Element)
1016
{
1017
    while( DOM_Element.firstChild ) {
1018
        DOM_Element.removeChild( DOM_Element.firstChild )
1019
    }
1020
}
1021
1022
Element_appendTransformResult = function ( DOM_Element, xmlDoc, xslDoc )
1023
{
1024
    if ( window.XSLTProcessor ) {
1025
        var proc = new XSLTProcessor();
1026
        proc.importStylesheet( xslDoc );
1027
        var docFrag = false;
1028
        docFrag = proc.transformToFragment( xmlDoc, DOM_Element.ownerDocument );
1029
        DOM_Element.appendChild(docFrag);
1030
    } else if ( window.ActiveXObject ) {
1031
        DOM_Element.innerHTML = xmlDoc.transformNode( xslDoc );
1032
    } else {
1033
        alert( 'Unable to perform XSLT transformation in this browser' );
1034
    }
1035
}
1036
1037
Element_appendTextNode = function (DOM_Element, tagName, textContent )
1038
{
1039
    var node = DOM_Element.ownerDocument.createElement(tagName);
1040
    var text = DOM_Element.ownerDocument.createTextNode(textContent);
1041
1042
    DOM_Element.appendChild(node);
1043
    node.appendChild(text);
1044
1045
    return node;
1046
}
1047
1048
Element_setTextContent = function ( DOM_Element, textContent )
1049
{
1050
    if (typeof DOM_Element.textContent !== "undefined") {
1051
        DOM_Element.textContent = textContent;
1052
    } else if (typeof DOM_Element.innerText !== "undefined" ) {
1053
        DOM_Element.innerText = textContent;
1054
    } else {
1055
        throw new Error("Cannot set text content of the node, no such method.");
1056
    }
1057
}
1058
1059
Element_getTextContent = function (DOM_Element)
1060
{
1061
    if ( typeof DOM_Element.textContent != 'undefined' ) {
1062
        return DOM_Element.textContent;
1063
    } else if (typeof DOM_Element.text != 'undefined') {
1064
        return DOM_Element.text;
1065
    } else {
1066
        throw new Error("Cannot get text content of the node, no such method.");
1067
    }
1068
}
1069
1070
Element_parseChildNodes = function (node)
1071
{
1072
    var parsed = {};
1073
    var hasChildElems = false;
1074
    var textContent = '';
1075
1076
    if (node.hasChildNodes()) {
1077
        var children = node.childNodes;
1078
        for (var i = 0; i < children.length; i++) {
1079
            var child = children[i];
1080
            switch (child.nodeType) {
1081
              case Node.ELEMENT_NODE:
1082
                hasChildElems = true;
1083
                var nodeName = child.nodeName;
1084
                if (!(nodeName in parsed))
1085
                    parsed[nodeName] = [];
1086
                parsed[nodeName].push(Element_parseChildNodes(child));
1087
                break;
1088
              case Node.TEXT_NODE:
1089
                textContent += child.nodeValue;
1090
                break;
1091
              case Node.CDATA_SECTION_NODE:
1092
                textContent += child.nodeValue;
1093
                break;
1094
            }
1095
        }
1096
    }
1097
1098
    var attrs = node.attributes;
1099
    for (var i = 0; i < attrs.length; i++) {
1100
        hasChildElems = true;
1101
        var attrName = '@' + attrs[i].nodeName;
1102
        var attrValue = attrs[i].nodeValue;
1103
        parsed[attrName] = attrValue;
1104
    }
1105
1106
    // if no nested elements/attrs set value to text
1107
    if (hasChildElems)
1108
      parsed['#text'] = textContent;
1109
    else
1110
      parsed = textContent;
1111
1112
    return parsed;
1113
}
1114
1115
/* do not remove trailing bracket */
1116
}
(-)a/koha-tmpl/intranet-tmpl/lib/require.js (-1 / +36 lines)
Line 0 Link Here
0
- 
1
/*
2
 RequireJS 2.1.8 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
3
 Available via the MIT or new BSD license.
4
 see: http://github.com/jrburke/requirejs for details
5
*/
6
var requirejs,require,define;
7
(function(Z){function H(b){return"[object Function]"===L.call(b)}function I(b){return"[object Array]"===L.call(b)}function y(b,c){if(b){var d;for(d=0;d<b.length&&(!b[d]||!c(b[d],d,b));d+=1);}}function M(b,c){if(b){var d;for(d=b.length-1;-1<d&&(!b[d]||!c(b[d],d,b));d-=1);}}function s(b,c){return ga.call(b,c)}function l(b,c){return s(b,c)&&b[c]}function F(b,c){for(var d in b)if(s(b,d)&&c(b[d],d))break}function Q(b,c,d,h){c&&F(c,function(c,j){if(d||!s(b,j))h&&"string"!==typeof c?(b[j]||(b[j]={}),Q(b[j],
8
c,d,h)):b[j]=c});return b}function u(b,c){return function(){return c.apply(b,arguments)}}function aa(b){throw b;}function ba(b){if(!b)return b;var c=Z;y(b.split("."),function(b){c=c[b]});return c}function A(b,c,d,h){c=Error(c+"\nhttp://requirejs.org/docs/errors.html#"+b);c.requireType=b;c.requireModules=h;d&&(c.originalError=d);return c}function ha(b){function c(a,f,b){var e,m,c,g,d,h,j,i=f&&f.split("/");e=i;var n=k.map,p=n&&n["*"];if(a&&"."===a.charAt(0))if(f){e=l(k.pkgs,f)?i=[f]:i.slice(0,i.length-
9
1);f=a=e.concat(a.split("/"));for(e=0;f[e];e+=1)if(m=f[e],"."===m)f.splice(e,1),e-=1;else if(".."===m)if(1===e&&(".."===f[2]||".."===f[0]))break;else 0<e&&(f.splice(e-1,2),e-=2);e=l(k.pkgs,f=a[0]);a=a.join("/");e&&a===f+"/"+e.main&&(a=f)}else 0===a.indexOf("./")&&(a=a.substring(2));if(b&&n&&(i||p)){f=a.split("/");for(e=f.length;0<e;e-=1){c=f.slice(0,e).join("/");if(i)for(m=i.length;0<m;m-=1)if(b=l(n,i.slice(0,m).join("/")))if(b=l(b,c)){g=b;d=e;break}if(g)break;!h&&(p&&l(p,c))&&(h=l(p,c),j=e)}!g&&
10
h&&(g=h,d=j);g&&(f.splice(0,d,g),a=f.join("/"))}return a}function d(a){z&&y(document.getElementsByTagName("script"),function(f){if(f.getAttribute("data-requiremodule")===a&&f.getAttribute("data-requirecontext")===i.contextName)return f.parentNode.removeChild(f),!0})}function h(a){var f=l(k.paths,a);if(f&&I(f)&&1<f.length)return d(a),f.shift(),i.require.undef(a),i.require([a]),!0}function $(a){var f,b=a?a.indexOf("!"):-1;-1<b&&(f=a.substring(0,b),a=a.substring(b+1,a.length));return[f,a]}function n(a,
11
f,b,e){var m,B,g=null,d=f?f.name:null,h=a,j=!0,k="";a||(j=!1,a="_@r"+(L+=1));a=$(a);g=a[0];a=a[1];g&&(g=c(g,d,e),B=l(r,g));a&&(g?k=B&&B.normalize?B.normalize(a,function(a){return c(a,d,e)}):c(a,d,e):(k=c(a,d,e),a=$(k),g=a[0],k=a[1],b=!0,m=i.nameToUrl(k)));b=g&&!B&&!b?"_unnormalized"+(M+=1):"";return{prefix:g,name:k,parentMap:f,unnormalized:!!b,url:m,originalName:h,isDefine:j,id:(g?g+"!"+k:k)+b}}function q(a){var f=a.id,b=l(p,f);b||(b=p[f]=new i.Module(a));return b}function t(a,f,b){var e=a.id,m=l(p,
12
e);if(s(r,e)&&(!m||m.defineEmitComplete))"defined"===f&&b(r[e]);else if(m=q(a),m.error&&"error"===f)b(m.error);else m.on(f,b)}function v(a,f){var b=a.requireModules,e=!1;if(f)f(a);else if(y(b,function(f){if(f=l(p,f))f.error=a,f.events.error&&(e=!0,f.emit("error",a))}),!e)j.onError(a)}function w(){R.length&&(ia.apply(G,[G.length-1,0].concat(R)),R=[])}function x(a){delete p[a];delete T[a]}function E(a,f,b){var e=a.map.id;a.error?a.emit("error",a.error):(f[e]=!0,y(a.depMaps,function(e,c){var g=e.id,
13
d=l(p,g);d&&(!a.depMatched[c]&&!b[g])&&(l(f,g)?(a.defineDep(c,r[g]),a.check()):E(d,f,b))}),b[e]=!0)}function C(){var a,f,b,e,m=(b=1E3*k.waitSeconds)&&i.startTime+b<(new Date).getTime(),c=[],g=[],j=!1,l=!0;if(!U){U=!0;F(T,function(b){a=b.map;f=a.id;if(b.enabled&&(a.isDefine||g.push(b),!b.error))if(!b.inited&&m)h(f)?j=e=!0:(c.push(f),d(f));else if(!b.inited&&(b.fetched&&a.isDefine)&&(j=!0,!a.prefix))return l=!1});if(m&&c.length)return b=A("timeout","Load timeout for modules: "+c,null,c),b.contextName=
14
i.contextName,v(b);l&&y(g,function(a){E(a,{},{})});if((!m||e)&&j)if((z||da)&&!V)V=setTimeout(function(){V=0;C()},50);U=!1}}function D(a){s(r,a[0])||q(n(a[0],null,!0)).init(a[1],a[2])}function J(a){var a=a.currentTarget||a.srcElement,b=i.onScriptLoad;a.detachEvent&&!W?a.detachEvent("onreadystatechange",b):a.removeEventListener("load",b,!1);b=i.onScriptError;(!a.detachEvent||W)&&a.removeEventListener("error",b,!1);return{node:a,id:a&&a.getAttribute("data-requiremodule")}}function K(){var a;for(w();G.length;){a=
15
G.shift();if(null===a[0])return v(A("mismatch","Mismatched anonymous define() module: "+a[a.length-1]));D(a)}}var U,X,i,N,V,k={waitSeconds:7,baseUrl:"./",paths:{},pkgs:{},shim:{},config:{}},p={},T={},Y={},G=[],r={},S={},L=1,M=1;N={require:function(a){return a.require?a.require:a.require=i.makeRequire(a.map)},exports:function(a){a.usingExports=!0;if(a.map.isDefine)return a.exports?a.exports:a.exports=r[a.map.id]={}},module:function(a){return a.module?a.module:a.module={id:a.map.id,uri:a.map.url,config:function(){var b=
16
l(k.pkgs,a.map.id);return(b?l(k.config,a.map.id+"/"+b.main):l(k.config,a.map.id))||{}},exports:r[a.map.id]}}};X=function(a){this.events=l(Y,a.id)||{};this.map=a;this.shim=l(k.shim,a.id);this.depExports=[];this.depMaps=[];this.depMatched=[];this.pluginMaps={};this.depCount=0};X.prototype={init:function(a,b,c,e){e=e||{};if(!this.inited){this.factory=b;if(c)this.on("error",c);else this.events.error&&(c=u(this,function(a){this.emit("error",a)}));this.depMaps=a&&a.slice(0);this.errback=c;this.inited=!0;
17
this.ignore=e.ignore;e.enabled||this.enabled?this.enable():this.check()}},defineDep:function(a,b){this.depMatched[a]||(this.depMatched[a]=!0,this.depCount-=1,this.depExports[a]=b)},fetch:function(){if(!this.fetched){this.fetched=!0;i.startTime=(new Date).getTime();var a=this.map;if(this.shim)i.makeRequire(this.map,{enableBuildCallback:!0})(this.shim.deps||[],u(this,function(){return a.prefix?this.callPlugin():this.load()}));else return a.prefix?this.callPlugin():this.load()}},load:function(){var a=
18
this.map.url;S[a]||(S[a]=!0,i.load(this.map.id,a))},check:function(){if(this.enabled&&!this.enabling){var a,b,c=this.map.id;b=this.depExports;var e=this.exports,m=this.factory;if(this.inited)if(this.error)this.emit("error",this.error);else{if(!this.defining){this.defining=!0;if(1>this.depCount&&!this.defined){if(H(m)){if(this.events.error&&this.map.isDefine||j.onError!==aa)try{e=i.execCb(c,m,b,e)}catch(d){a=d}else e=i.execCb(c,m,b,e);this.map.isDefine&&((b=this.module)&&void 0!==b.exports&&b.exports!==
19
this.exports?e=b.exports:void 0===e&&this.usingExports&&(e=this.exports));if(a)return a.requireMap=this.map,a.requireModules=this.map.isDefine?[this.map.id]:null,a.requireType=this.map.isDefine?"define":"require",v(this.error=a)}else e=m;this.exports=e;if(this.map.isDefine&&!this.ignore&&(r[c]=e,j.onResourceLoad))j.onResourceLoad(i,this.map,this.depMaps);x(c);this.defined=!0}this.defining=!1;this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=
20
!0)}}else this.fetch()}},callPlugin:function(){var a=this.map,b=a.id,d=n(a.prefix);this.depMaps.push(d);t(d,"defined",u(this,function(e){var m,d;d=this.map.name;var g=this.map.parentMap?this.map.parentMap.name:null,h=i.makeRequire(a.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){if(e.normalize&&(d=e.normalize(d,function(a){return c(a,g,!0)})||""),e=n(a.prefix+"!"+d,this.map.parentMap),t(e,"defined",u(this,function(a){this.init([],function(){return a},null,{enabled:!0,ignore:!0})})),
21
d=l(p,e.id)){this.depMaps.push(e);if(this.events.error)d.on("error",u(this,function(a){this.emit("error",a)}));d.enable()}}else m=u(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),m.error=u(this,function(a){this.inited=!0;this.error=a;a.requireModules=[b];F(p,function(a){0===a.map.id.indexOf(b+"_unnormalized")&&x(a.map.id)});v(a)}),m.fromText=u(this,function(e,c){var d=a.name,g=n(d),B=O;c&&(e=c);B&&(O=!1);q(g);s(k.config,b)&&(k.config[d]=k.config[b]);try{j.exec(e)}catch(ca){return v(A("fromtexteval",
22
"fromText eval for "+b+" failed: "+ca,ca,[b]))}B&&(O=!0);this.depMaps.push(g);i.completeLoad(d);h([d],m)}),e.load(a.name,h,m,k)}));i.enable(d,this);this.pluginMaps[d.id]=d},enable:function(){T[this.map.id]=this;this.enabling=this.enabled=!0;y(this.depMaps,u(this,function(a,b){var c,e;if("string"===typeof a){a=n(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap);this.depMaps[b]=a;if(c=l(N,a.id)){this.depExports[b]=c(this);return}this.depCount+=1;t(a,"defined",u(this,function(a){this.defineDep(b,
23
a);this.check()}));this.errback&&t(a,"error",u(this,this.errback))}c=a.id;e=p[c];!s(N,c)&&(e&&!e.enabled)&&i.enable(a,this)}));F(this.pluginMaps,u(this,function(a){var b=l(p,a.id);b&&!b.enabled&&i.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){y(this.events[a],function(a){a(b)});"error"===a&&delete this.events[a]}};i={config:k,contextName:b,registry:p,defined:r,urlFetched:S,defQueue:G,Module:X,makeModuleMap:n,
24
nextTick:j.nextTick,onError:v,configure:function(a){a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/");var b=k.pkgs,c=k.shim,e={paths:!0,config:!0,map:!0};F(a,function(a,b){e[b]?"map"===b?(k.map||(k.map={}),Q(k[b],a,!0,!0)):Q(k[b],a,!0):k[b]=a});a.shim&&(F(a.shim,function(a,b){I(a)&&(a={deps:a});if((a.exports||a.init)&&!a.exportsFn)a.exportsFn=i.makeShimExports(a);c[b]=a}),k.shim=c);a.packages&&(y(a.packages,function(a){a="string"===typeof a?{name:a}:a;b[a.name]={name:a.name,
25
location:a.location||a.name,main:(a.main||"main").replace(ja,"").replace(ea,"")}}),k.pkgs=b);F(p,function(a,b){!a.inited&&!a.map.unnormalized&&(a.map=n(b))});if(a.deps||a.callback)i.require(a.deps||[],a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(Z,arguments));return b||a.exports&&ba(a.exports)}},makeRequire:function(a,f){function d(e,c,h){var g,k;f.enableBuildCallback&&(c&&H(c))&&(c.__requireJsBuild=!0);if("string"===typeof e){if(H(c))return v(A("requireargs",
26
"Invalid require call"),h);if(a&&s(N,e))return N[e](p[a.id]);if(j.get)return j.get(i,e,a,d);g=n(e,a,!1,!0);g=g.id;return!s(r,g)?v(A("notloaded",'Module name "'+g+'" has not been loaded yet for context: '+b+(a?"":". Use require([])"))):r[g]}K();i.nextTick(function(){K();k=q(n(null,a));k.skipMap=f.skipMap;k.init(e,c,h,{enabled:!0});C()});return d}f=f||{};Q(d,{isBrowser:z,toUrl:function(b){var d,f=b.lastIndexOf("."),g=b.split("/")[0];if(-1!==f&&(!("."===g||".."===g)||1<f))d=b.substring(f,b.length),b=
27
b.substring(0,f);return i.nameToUrl(c(b,a&&a.id,!0),d,!0)},defined:function(b){return s(r,n(b,a,!1,!0).id)},specified:function(b){b=n(b,a,!1,!0).id;return s(r,b)||s(p,b)}});a||(d.undef=function(b){w();var c=n(b,a,!0),f=l(p,b);delete r[b];delete S[c.url];delete Y[b];f&&(f.events.defined&&(Y[b]=f.events),x(b))});return d},enable:function(a){l(p,a.id)&&q(a).enable()},completeLoad:function(a){var b,c,e=l(k.shim,a)||{},d=e.exports;for(w();G.length;){c=G.shift();if(null===c[0]){c[0]=a;if(b)break;b=!0}else c[0]===
28
a&&(b=!0);D(c)}c=l(p,a);if(!b&&!s(r,a)&&c&&!c.inited){if(k.enforceDefine&&(!d||!ba(d)))return h(a)?void 0:v(A("nodefine","No define call for "+a,null,[a]));D([a,e.deps||[],e.exportsFn])}C()},nameToUrl:function(a,b,c){var e,d,h,g,i,n;if(j.jsExtRegExp.test(a))g=a+(b||"");else{e=k.paths;d=k.pkgs;g=a.split("/");for(i=g.length;0<i;i-=1)if(n=g.slice(0,i).join("/"),h=l(d,n),n=l(e,n)){I(n)&&(n=n[0]);g.splice(0,i,n);break}else if(h){a=a===h.name?h.location+"/"+h.main:h.location;g.splice(0,i,a);break}g=g.join("/");
29
g+=b||(/\?/.test(g)||c?"":".js");g=("/"===g.charAt(0)||g.match(/^[\w\+\.\-]+:/)?"":k.baseUrl)+g}return k.urlArgs?g+((-1===g.indexOf("?")?"?":"&")+k.urlArgs):g},load:function(a,b){j.load(i,a,b)},execCb:function(a,b,c,e){return b.apply(e,c)},onScriptLoad:function(a){if("load"===a.type||ka.test((a.currentTarget||a.srcElement).readyState))P=null,a=J(a),i.completeLoad(a.id)},onScriptError:function(a){var b=J(a);if(!h(b.id))return v(A("scripterror","Script error for: "+b.id,a,[b.id]))}};i.require=i.makeRequire();
30
return i}var j,w,x,C,J,D,P,K,q,fa,la=/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,ma=/[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,ea=/\.js$/,ja=/^\.\//;w=Object.prototype;var L=w.toString,ga=w.hasOwnProperty,ia=Array.prototype.splice,z=!!("undefined"!==typeof window&&navigator&&window.document),da=!z&&"undefined"!==typeof importScripts,ka=z&&"PLAYSTATION 3"===navigator.platform?/^complete$/:/^(complete|loaded)$/,W="undefined"!==typeof opera&&"[object Opera]"===opera.toString(),E={},t={},R=[],O=
31
!1;if("undefined"===typeof define){if("undefined"!==typeof requirejs){if(H(requirejs))return;t=requirejs;requirejs=void 0}"undefined"!==typeof require&&!H(require)&&(t=require,require=void 0);j=requirejs=function(b,c,d,h){var q,n="_";!I(b)&&"string"!==typeof b&&(q=b,I(c)?(b=c,c=d,d=h):b=[]);q&&q.context&&(n=q.context);(h=l(E,n))||(h=E[n]=j.s.newContext(n));q&&h.configure(q);return h.require(b,c,d)};j.config=function(b){return j(b)};j.nextTick="undefined"!==typeof setTimeout?function(b){setTimeout(b,
32
4)}:function(b){b()};require||(require=j);j.version="2.1.8";j.jsExtRegExp=/^\/|:|\?|\.js$/;j.isBrowser=z;w=j.s={contexts:E,newContext:ha};j({});y(["toUrl","undef","defined","specified"],function(b){j[b]=function(){var c=E._;return c.require[b].apply(c,arguments)}});if(z&&(x=w.head=document.getElementsByTagName("head")[0],C=document.getElementsByTagName("base")[0]))x=w.head=C.parentNode;j.onError=aa;j.createNode=function(b){var c=b.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml","html:script"):
33
document.createElement("script");c.type=b.scriptType||"text/javascript";c.charset="utf-8";c.async=!0;return c};j.load=function(b,c,d){var h=b&&b.config||{};if(z)return h=j.createNode(h,c,d),h.setAttribute("data-requirecontext",b.contextName),h.setAttribute("data-requiremodule",c),h.attachEvent&&!(h.attachEvent.toString&&0>h.attachEvent.toString().indexOf("[native code"))&&!W?(O=!0,h.attachEvent("onreadystatechange",b.onScriptLoad)):(h.addEventListener("load",b.onScriptLoad,!1),h.addEventListener("error",
34
b.onScriptError,!1)),h.src=d,K=h,C?x.insertBefore(h,C):x.appendChild(h),K=null,h;if(da)try{importScripts(d),b.completeLoad(c)}catch(l){b.onError(A("importscripts","importScripts failed for "+c+" at "+d,l,[c]))}};z&&M(document.getElementsByTagName("script"),function(b){x||(x=b.parentNode);if(J=b.getAttribute("data-main"))return q=J,t.baseUrl||(D=q.split("/"),q=D.pop(),fa=D.length?D.join("/")+"/":"./",t.baseUrl=fa),q=q.replace(ea,""),j.jsExtRegExp.test(q)&&(q=J),t.deps=t.deps?t.deps.concat(q):[q],!0});
35
define=function(b,c,d){var h,j;"string"!==typeof b&&(d=c,c=b,b=null);I(c)||(d=c,c=null);!c&&H(d)&&(c=[],d.length&&(d.toString().replace(la,"").replace(ma,function(b,d){c.push(d)}),c=(1===d.length?["require"]:["require","exports","module"]).concat(c)));if(O){if(!(h=K))P&&"interactive"===P.readyState||M(document.getElementsByTagName("script"),function(b){if("interactive"===b.readyState)return P=b}),h=P;h&&(b||(b=h.getAttribute("data-requiremodule")),j=E[h.getAttribute("data-requirecontext")])}(j?j.defQueue:
36
R).push([b,c,d])};define.amd={jQuery:!0};j.exec=function(b){return eval(b)};j(t)}})(this);

Return to bug 11559