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