browser/devtools/sourceeditor/codemirror/codemirror.js

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

michael@0 1 // This is CodeMirror (http://codemirror.net), a code editor
michael@0 2 // implemented in JavaScript on top of the browser's DOM.
michael@0 3 //
michael@0 4 // You can find some technical background for some of the code below
michael@0 5 // at http://marijnhaverbeke.nl/blog/#cm-internals .
michael@0 6
michael@0 7 (function(mod) {
michael@0 8 if (typeof exports == "object" && typeof module == "object") // CommonJS
michael@0 9 module.exports = mod();
michael@0 10 else if (typeof define == "function" && define.amd) // AMD
michael@0 11 return define([], mod);
michael@0 12 else // Plain browser env
michael@0 13 this.CodeMirror = mod();
michael@0 14 })(function() {
michael@0 15 "use strict";
michael@0 16
michael@0 17 // BROWSER SNIFFING
michael@0 18
michael@0 19 // Kludges for bugs and behavior differences that can't be feature
michael@0 20 // detected are enabled based on userAgent etc sniffing.
michael@0 21
michael@0 22 var gecko = /gecko\/\d/i.test(navigator.userAgent);
michael@0 23 // ie_uptoN means Internet Explorer version N or lower
michael@0 24 var ie_upto10 = /MSIE \d/.test(navigator.userAgent);
michael@0 25 var ie_upto7 = ie_upto10 && (document.documentMode == null || document.documentMode < 8);
michael@0 26 var ie_upto8 = ie_upto10 && (document.documentMode == null || document.documentMode < 9);
michael@0 27 var ie_upto9 = ie_upto10 && (document.documentMode == null || document.documentMode < 10);
michael@0 28 var ie_11up = /Trident\/([7-9]|\d{2,})\./.test(navigator.userAgent);
michael@0 29 var ie = ie_upto10 || ie_11up;
michael@0 30 var webkit = /WebKit\//.test(navigator.userAgent);
michael@0 31 var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
michael@0 32 var chrome = /Chrome\//.test(navigator.userAgent);
michael@0 33 var presto = /Opera\//.test(navigator.userAgent);
michael@0 34 var safari = /Apple Computer/.test(navigator.vendor);
michael@0 35 var khtml = /KHTML\//.test(navigator.userAgent);
michael@0 36 var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent);
michael@0 37 var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
michael@0 38 var phantom = /PhantomJS/.test(navigator.userAgent);
michael@0 39
michael@0 40 var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
michael@0 41 // This is woefully incomplete. Suggestions for alternative methods welcome.
michael@0 42 var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
michael@0 43 var mac = ios || /Mac/.test(navigator.platform);
michael@0 44 var windows = /win/i.test(navigator.platform);
michael@0 45
michael@0 46 var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
michael@0 47 if (presto_version) presto_version = Number(presto_version[1]);
michael@0 48 if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
michael@0 49 // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
michael@0 50 var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
michael@0 51 var captureRightClick = gecko || (ie && !ie_upto8);
michael@0 52
michael@0 53 // Optimize some code when these features are not used.
michael@0 54 var sawReadOnlySpans = false, sawCollapsedSpans = false;
michael@0 55
michael@0 56 // EDITOR CONSTRUCTOR
michael@0 57
michael@0 58 // A CodeMirror instance represents an editor. This is the object
michael@0 59 // that user code is usually dealing with.
michael@0 60
michael@0 61 function CodeMirror(place, options) {
michael@0 62 if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
michael@0 63
michael@0 64 this.options = options = options || {};
michael@0 65 // Determine effective options based on given values and defaults.
michael@0 66 for (var opt in defaults) if (!options.hasOwnProperty(opt))
michael@0 67 options[opt] = defaults[opt];
michael@0 68 setGuttersForLineNumbers(options);
michael@0 69
michael@0 70 var doc = options.value;
michael@0 71 if (typeof doc == "string") doc = new Doc(doc, options.mode);
michael@0 72 this.doc = doc;
michael@0 73
michael@0 74 var display = this.display = new Display(place, doc);
michael@0 75 display.wrapper.CodeMirror = this;
michael@0 76 updateGutters(this);
michael@0 77 themeChanged(this);
michael@0 78 if (options.lineWrapping)
michael@0 79 this.display.wrapper.className += " CodeMirror-wrap";
michael@0 80 if (options.autofocus && !mobile) focusInput(this);
michael@0 81
michael@0 82 this.state = {
michael@0 83 keyMaps: [], // stores maps added by addKeyMap
michael@0 84 overlays: [], // highlighting overlays, as added by addOverlay
michael@0 85 modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
michael@0 86 overwrite: false, focused: false,
michael@0 87 suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
michael@0 88 pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in readInput
michael@0 89 draggingText: false,
michael@0 90 highlight: new Delayed() // stores highlight worker timeout
michael@0 91 };
michael@0 92
michael@0 93 // Override magic textarea content restore that IE sometimes does
michael@0 94 // on our hidden textarea on reload
michael@0 95 if (ie_upto10) setTimeout(bind(resetInput, this, true), 20);
michael@0 96
michael@0 97 registerEventHandlers(this);
michael@0 98
michael@0 99 var cm = this;
michael@0 100 runInOp(this, function() {
michael@0 101 cm.curOp.forceUpdate = true;
michael@0 102 attachDoc(cm, doc);
michael@0 103
michael@0 104 if ((options.autofocus && !mobile) || activeElt() == display.input)
michael@0 105 setTimeout(bind(onFocus, cm), 20);
michael@0 106 else
michael@0 107 onBlur(cm);
michael@0 108
michael@0 109 for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
michael@0 110 optionHandlers[opt](cm, options[opt], Init);
michael@0 111 for (var i = 0; i < initHooks.length; ++i) initHooks[i](cm);
michael@0 112 });
michael@0 113 }
michael@0 114
michael@0 115 // DISPLAY CONSTRUCTOR
michael@0 116
michael@0 117 // The display handles the DOM integration, both for input reading
michael@0 118 // and content drawing. It holds references to DOM nodes and
michael@0 119 // display-related state.
michael@0 120
michael@0 121 function Display(place, doc) {
michael@0 122 var d = this;
michael@0 123
michael@0 124 // The semihidden textarea that is focused when the editor is
michael@0 125 // focused, and receives input.
michael@0 126 var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
michael@0 127 // The textarea is kept positioned near the cursor to prevent the
michael@0 128 // fact that it'll be scrolled into view on input from scrolling
michael@0 129 // our fake cursor out of view. On webkit, when wrap=off, paste is
michael@0 130 // very slow. So make the area wide instead.
michael@0 131 if (webkit) input.style.width = "1000px";
michael@0 132 else input.setAttribute("wrap", "off");
michael@0 133 // If border: 0; -- iOS fails to open keyboard (issue #1287)
michael@0 134 if (ios) input.style.border = "1px solid black";
michael@0 135 input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); input.setAttribute("spellcheck", "false");
michael@0 136
michael@0 137 // Wraps and hides input textarea
michael@0 138 d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
michael@0 139 // The fake scrollbar elements.
michael@0 140 d.scrollbarH = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
michael@0 141 d.scrollbarV = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
michael@0 142 // Covers bottom-right square when both scrollbars are present.
michael@0 143 d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
michael@0 144 // Covers bottom of gutter when coverGutterNextToScrollbar is on
michael@0 145 // and h scrollbar is present.
michael@0 146 d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
michael@0 147 // Will contain the actual code, positioned to cover the viewport.
michael@0 148 d.lineDiv = elt("div", null, "CodeMirror-code");
michael@0 149 // Elements are added to these to represent selection and cursors.
michael@0 150 d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
michael@0 151 d.cursorDiv = elt("div", null, "CodeMirror-cursors");
michael@0 152 // A visibility: hidden element used to find the size of things.
michael@0 153 d.measure = elt("div", null, "CodeMirror-measure");
michael@0 154 // When lines outside of the viewport are measured, they are drawn in this.
michael@0 155 d.lineMeasure = elt("div", null, "CodeMirror-measure");
michael@0 156 // Wraps everything that needs to exist inside the vertically-padded coordinate system
michael@0 157 d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
michael@0 158 null, "position: relative; outline: none");
michael@0 159 // Moved around its parent to cover visible view.
michael@0 160 d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
michael@0 161 // Set to the height of the document, allowing scrolling.
michael@0 162 d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
michael@0 163 // Behavior of elts with overflow: auto and padding is
michael@0 164 // inconsistent across browsers. This is used to ensure the
michael@0 165 // scrollable area is big enough.
michael@0 166 d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerCutOff + "px; width: 1px;");
michael@0 167 // Will contain the gutters, if any.
michael@0 168 d.gutters = elt("div", null, "CodeMirror-gutters");
michael@0 169 d.lineGutter = null;
michael@0 170 // Actual scrollable element.
michael@0 171 d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
michael@0 172 d.scroller.setAttribute("tabIndex", "-1");
michael@0 173 // The element in which the editor lives.
michael@0 174 d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV,
michael@0 175 d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
michael@0 176
michael@0 177 // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
michael@0 178 if (ie_upto7) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
michael@0 179 // Needed to hide big blue blinking cursor on Mobile Safari
michael@0 180 if (ios) input.style.width = "0px";
michael@0 181 if (!webkit) d.scroller.draggable = true;
michael@0 182 // Needed to handle Tab key in KHTML
michael@0 183 if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; }
michael@0 184 // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
michael@0 185 if (ie_upto7) d.scrollbarH.style.minHeight = d.scrollbarV.style.minWidth = "18px";
michael@0 186
michael@0 187 if (place.appendChild) place.appendChild(d.wrapper);
michael@0 188 else place(d.wrapper);
michael@0 189
michael@0 190 // Current rendered range (may be bigger than the view window).
michael@0 191 d.viewFrom = d.viewTo = doc.first;
michael@0 192 // Information about the rendered lines.
michael@0 193 d.view = [];
michael@0 194 // Holds info about a single rendered line when it was rendered
michael@0 195 // for measurement, while not in view.
michael@0 196 d.externalMeasured = null;
michael@0 197 // Empty space (in pixels) above the view
michael@0 198 d.viewOffset = 0;
michael@0 199 d.lastSizeC = 0;
michael@0 200 d.updateLineNumbers = null;
michael@0 201
michael@0 202 // Used to only resize the line number gutter when necessary (when
michael@0 203 // the amount of lines crosses a boundary that makes its width change)
michael@0 204 d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
michael@0 205 // See readInput and resetInput
michael@0 206 d.prevInput = "";
michael@0 207 // Set to true when a non-horizontal-scrolling line widget is
michael@0 208 // added. As an optimization, line widget aligning is skipped when
michael@0 209 // this is false.
michael@0 210 d.alignWidgets = false;
michael@0 211 // Flag that indicates whether we expect input to appear real soon
michael@0 212 // now (after some event like 'keypress' or 'input') and are
michael@0 213 // polling intensively.
michael@0 214 d.pollingFast = false;
michael@0 215 // Self-resetting timeout for the poller
michael@0 216 d.poll = new Delayed();
michael@0 217
michael@0 218 d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
michael@0 219
michael@0 220 // Tracks when resetInput has punted to just putting a short
michael@0 221 // string into the textarea instead of the full selection.
michael@0 222 d.inaccurateSelection = false;
michael@0 223
michael@0 224 // Tracks the maximum line length so that the horizontal scrollbar
michael@0 225 // can be kept static when scrolling.
michael@0 226 d.maxLine = null;
michael@0 227 d.maxLineLength = 0;
michael@0 228 d.maxLineChanged = false;
michael@0 229
michael@0 230 // Used for measuring wheel scrolling granularity
michael@0 231 d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
michael@0 232
michael@0 233 // True when shift is held down.
michael@0 234 d.shift = false;
michael@0 235 }
michael@0 236
michael@0 237 // STATE UPDATES
michael@0 238
michael@0 239 // Used to get the editor into a consistent state again when options change.
michael@0 240
michael@0 241 function loadMode(cm) {
michael@0 242 cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
michael@0 243 resetModeState(cm);
michael@0 244 }
michael@0 245
michael@0 246 function resetModeState(cm) {
michael@0 247 cm.doc.iter(function(line) {
michael@0 248 if (line.stateAfter) line.stateAfter = null;
michael@0 249 if (line.styles) line.styles = null;
michael@0 250 });
michael@0 251 cm.doc.frontier = cm.doc.first;
michael@0 252 startWorker(cm, 100);
michael@0 253 cm.state.modeGen++;
michael@0 254 if (cm.curOp) regChange(cm);
michael@0 255 }
michael@0 256
michael@0 257 function wrappingChanged(cm) {
michael@0 258 if (cm.options.lineWrapping) {
michael@0 259 cm.display.wrapper.className += " CodeMirror-wrap";
michael@0 260 cm.display.sizer.style.minWidth = "";
michael@0 261 } else {
michael@0 262 cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", "");
michael@0 263 findMaxLine(cm);
michael@0 264 }
michael@0 265 estimateLineHeights(cm);
michael@0 266 regChange(cm);
michael@0 267 clearCaches(cm);
michael@0 268 setTimeout(function(){updateScrollbars(cm);}, 100);
michael@0 269 }
michael@0 270
michael@0 271 // Returns a function that estimates the height of a line, to use as
michael@0 272 // first approximation until the line becomes visible (and is thus
michael@0 273 // properly measurable).
michael@0 274 function estimateHeight(cm) {
michael@0 275 var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
michael@0 276 var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
michael@0 277 return function(line) {
michael@0 278 if (lineIsHidden(cm.doc, line)) return 0;
michael@0 279
michael@0 280 var widgetsHeight = 0;
michael@0 281 if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
michael@0 282 if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
michael@0 283 }
michael@0 284
michael@0 285 if (wrapping)
michael@0 286 return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
michael@0 287 else
michael@0 288 return widgetsHeight + th;
michael@0 289 };
michael@0 290 }
michael@0 291
michael@0 292 function estimateLineHeights(cm) {
michael@0 293 var doc = cm.doc, est = estimateHeight(cm);
michael@0 294 doc.iter(function(line) {
michael@0 295 var estHeight = est(line);
michael@0 296 if (estHeight != line.height) updateLineHeight(line, estHeight);
michael@0 297 });
michael@0 298 }
michael@0 299
michael@0 300 function keyMapChanged(cm) {
michael@0 301 var map = keyMap[cm.options.keyMap], style = map.style;
michael@0 302 cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") +
michael@0 303 (style ? " cm-keymap-" + style : "");
michael@0 304 }
michael@0 305
michael@0 306 function themeChanged(cm) {
michael@0 307 cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
michael@0 308 cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
michael@0 309 clearCaches(cm);
michael@0 310 }
michael@0 311
michael@0 312 function guttersChanged(cm) {
michael@0 313 updateGutters(cm);
michael@0 314 regChange(cm);
michael@0 315 setTimeout(function(){alignHorizontally(cm);}, 20);
michael@0 316 }
michael@0 317
michael@0 318 // Rebuild the gutter elements, ensure the margin to the left of the
michael@0 319 // code matches their width.
michael@0 320 function updateGutters(cm) {
michael@0 321 var gutters = cm.display.gutters, specs = cm.options.gutters;
michael@0 322 removeChildren(gutters);
michael@0 323 for (var i = 0; i < specs.length; ++i) {
michael@0 324 var gutterClass = specs[i];
michael@0 325 var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
michael@0 326 if (gutterClass == "CodeMirror-linenumbers") {
michael@0 327 cm.display.lineGutter = gElt;
michael@0 328 gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
michael@0 329 }
michael@0 330 }
michael@0 331 gutters.style.display = i ? "" : "none";
michael@0 332 var width = gutters.offsetWidth;
michael@0 333 cm.display.sizer.style.marginLeft = width + "px";
michael@0 334 if (i) cm.display.scrollbarH.style.left = cm.options.fixedGutter ? width + "px" : 0;
michael@0 335 }
michael@0 336
michael@0 337 // Compute the character length of a line, taking into account
michael@0 338 // collapsed ranges (see markText) that might hide parts, and join
michael@0 339 // other lines onto it.
michael@0 340 function lineLength(line) {
michael@0 341 if (line.height == 0) return 0;
michael@0 342 var len = line.text.length, merged, cur = line;
michael@0 343 while (merged = collapsedSpanAtStart(cur)) {
michael@0 344 var found = merged.find(0, true);
michael@0 345 cur = found.from.line;
michael@0 346 len += found.from.ch - found.to.ch;
michael@0 347 }
michael@0 348 cur = line;
michael@0 349 while (merged = collapsedSpanAtEnd(cur)) {
michael@0 350 var found = merged.find(0, true);
michael@0 351 len -= cur.text.length - found.from.ch;
michael@0 352 cur = found.to.line;
michael@0 353 len += cur.text.length - found.to.ch;
michael@0 354 }
michael@0 355 return len;
michael@0 356 }
michael@0 357
michael@0 358 // Find the longest line in the document.
michael@0 359 function findMaxLine(cm) {
michael@0 360 var d = cm.display, doc = cm.doc;
michael@0 361 d.maxLine = getLine(doc, doc.first);
michael@0 362 d.maxLineLength = lineLength(d.maxLine);
michael@0 363 d.maxLineChanged = true;
michael@0 364 doc.iter(function(line) {
michael@0 365 var len = lineLength(line);
michael@0 366 if (len > d.maxLineLength) {
michael@0 367 d.maxLineLength = len;
michael@0 368 d.maxLine = line;
michael@0 369 }
michael@0 370 });
michael@0 371 }
michael@0 372
michael@0 373 // Make sure the gutters options contains the element
michael@0 374 // "CodeMirror-linenumbers" when the lineNumbers option is true.
michael@0 375 function setGuttersForLineNumbers(options) {
michael@0 376 var found = indexOf(options.gutters, "CodeMirror-linenumbers");
michael@0 377 if (found == -1 && options.lineNumbers) {
michael@0 378 options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
michael@0 379 } else if (found > -1 && !options.lineNumbers) {
michael@0 380 options.gutters = options.gutters.slice(0);
michael@0 381 options.gutters.splice(found, 1);
michael@0 382 }
michael@0 383 }
michael@0 384
michael@0 385 // SCROLLBARS
michael@0 386
michael@0 387 // Prepare DOM reads needed to update the scrollbars. Done in one
michael@0 388 // shot to minimize update/measure roundtrips.
michael@0 389 function measureForScrollbars(cm) {
michael@0 390 var scroll = cm.display.scroller;
michael@0 391 return {
michael@0 392 clientHeight: scroll.clientHeight,
michael@0 393 barHeight: cm.display.scrollbarV.clientHeight,
michael@0 394 scrollWidth: scroll.scrollWidth, clientWidth: scroll.clientWidth,
michael@0 395 barWidth: cm.display.scrollbarH.clientWidth,
michael@0 396 docHeight: Math.round(cm.doc.height + paddingVert(cm.display))
michael@0 397 };
michael@0 398 }
michael@0 399
michael@0 400 // Re-synchronize the fake scrollbars with the actual size of the
michael@0 401 // content.
michael@0 402 function updateScrollbars(cm, measure) {
michael@0 403 if (!measure) measure = measureForScrollbars(cm);
michael@0 404 var d = cm.display;
michael@0 405 var scrollHeight = measure.docHeight + scrollerCutOff;
michael@0 406 var needsH = measure.scrollWidth > measure.clientWidth;
michael@0 407 var needsV = scrollHeight > measure.clientHeight;
michael@0 408 if (needsV) {
michael@0 409 d.scrollbarV.style.display = "block";
michael@0 410 d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0";
michael@0 411 // A bug in IE8 can cause this value to be negative, so guard it.
michael@0 412 d.scrollbarV.firstChild.style.height =
michael@0 413 Math.max(0, scrollHeight - measure.clientHeight + (measure.barHeight || d.scrollbarV.clientHeight)) + "px";
michael@0 414 } else {
michael@0 415 d.scrollbarV.style.display = "";
michael@0 416 d.scrollbarV.firstChild.style.height = "0";
michael@0 417 }
michael@0 418 if (needsH) {
michael@0 419 d.scrollbarH.style.display = "block";
michael@0 420 d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0";
michael@0 421 d.scrollbarH.firstChild.style.width =
michael@0 422 (measure.scrollWidth - measure.clientWidth + (measure.barWidth || d.scrollbarH.clientWidth)) + "px";
michael@0 423 } else {
michael@0 424 d.scrollbarH.style.display = "";
michael@0 425 d.scrollbarH.firstChild.style.width = "0";
michael@0 426 }
michael@0 427 if (needsH && needsV) {
michael@0 428 d.scrollbarFiller.style.display = "block";
michael@0 429 d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px";
michael@0 430 } else d.scrollbarFiller.style.display = "";
michael@0 431 if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
michael@0 432 d.gutterFiller.style.display = "block";
michael@0 433 d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px";
michael@0 434 d.gutterFiller.style.width = d.gutters.offsetWidth + "px";
michael@0 435 } else d.gutterFiller.style.display = "";
michael@0 436
michael@0 437 if (mac_geLion && scrollbarWidth(d.measure) === 0) {
michael@0 438 d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px";
michael@0 439 var barMouseDown = function(e) {
michael@0 440 if (e_target(e) != d.scrollbarV && e_target(e) != d.scrollbarH)
michael@0 441 operation(cm, onMouseDown)(e);
michael@0 442 };
michael@0 443 on(d.scrollbarV, "mousedown", barMouseDown);
michael@0 444 on(d.scrollbarH, "mousedown", barMouseDown);
michael@0 445 }
michael@0 446 }
michael@0 447
michael@0 448 // Compute the lines that are visible in a given viewport (defaults
michael@0 449 // the the current scroll position). viewPort may contain top,
michael@0 450 // height, and ensure (see op.scrollToPos) properties.
michael@0 451 function visibleLines(display, doc, viewPort) {
michael@0 452 var top = viewPort && viewPort.top != null ? viewPort.top : display.scroller.scrollTop;
michael@0 453 top = Math.floor(top - paddingTop(display));
michael@0 454 var bottom = viewPort && viewPort.bottom != null ? viewPort.bottom : top + display.wrapper.clientHeight;
michael@0 455
michael@0 456 var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
michael@0 457 // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
michael@0 458 // forces those lines into the viewport (if possible).
michael@0 459 if (viewPort && viewPort.ensure) {
michael@0 460 var ensureFrom = viewPort.ensure.from.line, ensureTo = viewPort.ensure.to.line;
michael@0 461 if (ensureFrom < from)
michael@0 462 return {from: ensureFrom,
michael@0 463 to: lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight)};
michael@0 464 if (Math.min(ensureTo, doc.lastLine()) >= to)
michael@0 465 return {from: lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight),
michael@0 466 to: ensureTo};
michael@0 467 }
michael@0 468 return {from: from, to: to};
michael@0 469 }
michael@0 470
michael@0 471 // LINE NUMBERS
michael@0 472
michael@0 473 // Re-align line numbers and gutter marks to compensate for
michael@0 474 // horizontal scrolling.
michael@0 475 function alignHorizontally(cm) {
michael@0 476 var display = cm.display, view = display.view;
michael@0 477 if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
michael@0 478 var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
michael@0 479 var gutterW = display.gutters.offsetWidth, left = comp + "px";
michael@0 480 for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
michael@0 481 if (cm.options.fixedGutter && view[i].gutter)
michael@0 482 view[i].gutter.style.left = left;
michael@0 483 var align = view[i].alignable;
michael@0 484 if (align) for (var j = 0; j < align.length; j++)
michael@0 485 align[j].style.left = left;
michael@0 486 }
michael@0 487 if (cm.options.fixedGutter)
michael@0 488 display.gutters.style.left = (comp + gutterW) + "px";
michael@0 489 }
michael@0 490
michael@0 491 // Used to ensure that the line number gutter is still the right
michael@0 492 // size for the current document size. Returns true when an update
michael@0 493 // is needed.
michael@0 494 function maybeUpdateLineNumberWidth(cm) {
michael@0 495 if (!cm.options.lineNumbers) return false;
michael@0 496 var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
michael@0 497 if (last.length != display.lineNumChars) {
michael@0 498 var test = display.measure.appendChild(elt("div", [elt("div", last)],
michael@0 499 "CodeMirror-linenumber CodeMirror-gutter-elt"));
michael@0 500 var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
michael@0 501 display.lineGutter.style.width = "";
michael@0 502 display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);
michael@0 503 display.lineNumWidth = display.lineNumInnerWidth + padding;
michael@0 504 display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
michael@0 505 display.lineGutter.style.width = display.lineNumWidth + "px";
michael@0 506 var width = display.gutters.offsetWidth;
michael@0 507 display.scrollbarH.style.left = cm.options.fixedGutter ? width + "px" : 0;
michael@0 508 display.sizer.style.marginLeft = width + "px";
michael@0 509 return true;
michael@0 510 }
michael@0 511 return false;
michael@0 512 }
michael@0 513
michael@0 514 function lineNumberFor(options, i) {
michael@0 515 return String(options.lineNumberFormatter(i + options.firstLineNumber));
michael@0 516 }
michael@0 517
michael@0 518 // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
michael@0 519 // but using getBoundingClientRect to get a sub-pixel-accurate
michael@0 520 // result.
michael@0 521 function compensateForHScroll(display) {
michael@0 522 return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
michael@0 523 }
michael@0 524
michael@0 525 // DISPLAY DRAWING
michael@0 526
michael@0 527 // Updates the display, selection, and scrollbars, using the
michael@0 528 // information in display.view to find out which nodes are no longer
michael@0 529 // up-to-date. Tries to bail out early when no changes are needed,
michael@0 530 // unless forced is true.
michael@0 531 // Returns true if an actual update happened, false otherwise.
michael@0 532 function updateDisplay(cm, viewPort, forced) {
michael@0 533 var oldFrom = cm.display.viewFrom, oldTo = cm.display.viewTo, updated;
michael@0 534 var visible = visibleLines(cm.display, cm.doc, viewPort);
michael@0 535 for (var first = true;; first = false) {
michael@0 536 var oldWidth = cm.display.scroller.clientWidth;
michael@0 537 if (!updateDisplayInner(cm, visible, forced)) break;
michael@0 538 updated = true;
michael@0 539
michael@0 540 // If the max line changed since it was last measured, measure it,
michael@0 541 // and ensure the document's width matches it.
michael@0 542 if (cm.display.maxLineChanged && !cm.options.lineWrapping)
michael@0 543 adjustContentWidth(cm);
michael@0 544
michael@0 545 var barMeasure = measureForScrollbars(cm);
michael@0 546 updateSelection(cm);
michael@0 547 setDocumentHeight(cm, barMeasure);
michael@0 548 updateScrollbars(cm, barMeasure);
michael@0 549 if (first && cm.options.lineWrapping && oldWidth != cm.display.scroller.clientWidth) {
michael@0 550 forced = true;
michael@0 551 continue;
michael@0 552 }
michael@0 553 forced = false;
michael@0 554
michael@0 555 // Clip forced viewport to actual scrollable area.
michael@0 556 if (viewPort && viewPort.top != null)
michael@0 557 viewPort = {top: Math.min(barMeasure.docHeight - scrollerCutOff - barMeasure.clientHeight, viewPort.top)};
michael@0 558 // Updated line heights might result in the drawn area not
michael@0 559 // actually covering the viewport. Keep looping until it does.
michael@0 560 visible = visibleLines(cm.display, cm.doc, viewPort);
michael@0 561 if (visible.from >= cm.display.viewFrom && visible.to <= cm.display.viewTo)
michael@0 562 break;
michael@0 563 }
michael@0 564
michael@0 565 cm.display.updateLineNumbers = null;
michael@0 566 if (updated) {
michael@0 567 signalLater(cm, "update", cm);
michael@0 568 if (cm.display.viewFrom != oldFrom || cm.display.viewTo != oldTo)
michael@0 569 signalLater(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
michael@0 570 }
michael@0 571 return updated;
michael@0 572 }
michael@0 573
michael@0 574 // Does the actual updating of the line display. Bails out
michael@0 575 // (returning false) when there is nothing to be done and forced is
michael@0 576 // false.
michael@0 577 function updateDisplayInner(cm, visible, forced) {
michael@0 578 var display = cm.display, doc = cm.doc;
michael@0 579 if (!display.wrapper.offsetWidth) {
michael@0 580 resetView(cm);
michael@0 581 return;
michael@0 582 }
michael@0 583
michael@0 584 // Bail out if the visible area is already rendered and nothing changed.
michael@0 585 if (!forced && visible.from >= display.viewFrom && visible.to <= display.viewTo &&
michael@0 586 countDirtyView(cm) == 0)
michael@0 587 return;
michael@0 588
michael@0 589 if (maybeUpdateLineNumberWidth(cm))
michael@0 590 resetView(cm);
michael@0 591 var dims = getDimensions(cm);
michael@0 592
michael@0 593 // Compute a suitable new viewport (from & to)
michael@0 594 var end = doc.first + doc.size;
michael@0 595 var from = Math.max(visible.from - cm.options.viewportMargin, doc.first);
michael@0 596 var to = Math.min(end, visible.to + cm.options.viewportMargin);
michael@0 597 if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
michael@0 598 if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
michael@0 599 if (sawCollapsedSpans) {
michael@0 600 from = visualLineNo(cm.doc, from);
michael@0 601 to = visualLineEndNo(cm.doc, to);
michael@0 602 }
michael@0 603
michael@0 604 var different = from != display.viewFrom || to != display.viewTo ||
michael@0 605 display.lastSizeC != display.wrapper.clientHeight;
michael@0 606 adjustView(cm, from, to);
michael@0 607
michael@0 608 display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
michael@0 609 // Position the mover div to align with the current scroll position
michael@0 610 cm.display.mover.style.top = display.viewOffset + "px";
michael@0 611
michael@0 612 var toUpdate = countDirtyView(cm);
michael@0 613 if (!different && toUpdate == 0 && !forced) return;
michael@0 614
michael@0 615 // For big changes, we hide the enclosing element during the
michael@0 616 // update, since that speeds up the operations on most browsers.
michael@0 617 var focused = activeElt();
michael@0 618 if (toUpdate > 4) display.lineDiv.style.display = "none";
michael@0 619 patchDisplay(cm, display.updateLineNumbers, dims);
michael@0 620 if (toUpdate > 4) display.lineDiv.style.display = "";
michael@0 621 // There might have been a widget with a focused element that got
michael@0 622 // hidden or updated, if so re-focus it.
michael@0 623 if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
michael@0 624
michael@0 625 // Prevent selection and cursors from interfering with the scroll
michael@0 626 // width.
michael@0 627 removeChildren(display.cursorDiv);
michael@0 628 removeChildren(display.selectionDiv);
michael@0 629
michael@0 630 if (different) {
michael@0 631 display.lastSizeC = display.wrapper.clientHeight;
michael@0 632 startWorker(cm, 400);
michael@0 633 }
michael@0 634
michael@0 635 updateHeightsInViewport(cm);
michael@0 636
michael@0 637 return true;
michael@0 638 }
michael@0 639
michael@0 640 function adjustContentWidth(cm) {
michael@0 641 var display = cm.display;
michael@0 642 var width = measureChar(cm, display.maxLine, display.maxLine.text.length).left;
michael@0 643 display.maxLineChanged = false;
michael@0 644 var minWidth = Math.max(0, width + 3);
michael@0 645 var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + minWidth + scrollerCutOff - display.scroller.clientWidth);
michael@0 646 display.sizer.style.minWidth = minWidth + "px";
michael@0 647 if (maxScrollLeft < cm.doc.scrollLeft)
michael@0 648 setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft), true);
michael@0 649 }
michael@0 650
michael@0 651 function setDocumentHeight(cm, measure) {
michael@0 652 cm.display.sizer.style.minHeight = cm.display.heightForcer.style.top = measure.docHeight + "px";
michael@0 653 cm.display.gutters.style.height = Math.max(measure.docHeight, measure.clientHeight - scrollerCutOff) + "px";
michael@0 654 }
michael@0 655
michael@0 656 // Read the actual heights of the rendered lines, and update their
michael@0 657 // stored heights to match.
michael@0 658 function updateHeightsInViewport(cm) {
michael@0 659 var display = cm.display;
michael@0 660 var prevBottom = display.lineDiv.offsetTop;
michael@0 661 for (var i = 0; i < display.view.length; i++) {
michael@0 662 var cur = display.view[i], height;
michael@0 663 if (cur.hidden) continue;
michael@0 664 if (ie_upto7) {
michael@0 665 var bot = cur.node.offsetTop + cur.node.offsetHeight;
michael@0 666 height = bot - prevBottom;
michael@0 667 prevBottom = bot;
michael@0 668 } else {
michael@0 669 var box = cur.node.getBoundingClientRect();
michael@0 670 height = box.bottom - box.top;
michael@0 671 }
michael@0 672 var diff = cur.line.height - height;
michael@0 673 if (height < 2) height = textHeight(display);
michael@0 674 if (diff > .001 || diff < -.001) {
michael@0 675 updateLineHeight(cur.line, height);
michael@0 676 updateWidgetHeight(cur.line);
michael@0 677 if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
michael@0 678 updateWidgetHeight(cur.rest[j]);
michael@0 679 }
michael@0 680 }
michael@0 681 }
michael@0 682
michael@0 683 // Read and store the height of line widgets associated with the
michael@0 684 // given line.
michael@0 685 function updateWidgetHeight(line) {
michael@0 686 if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
michael@0 687 line.widgets[i].height = line.widgets[i].node.offsetHeight;
michael@0 688 }
michael@0 689
michael@0 690 // Do a bulk-read of the DOM positions and sizes needed to draw the
michael@0 691 // view, so that we don't interleave reading and writing to the DOM.
michael@0 692 function getDimensions(cm) {
michael@0 693 var d = cm.display, left = {}, width = {};
michael@0 694 for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
michael@0 695 left[cm.options.gutters[i]] = n.offsetLeft;
michael@0 696 width[cm.options.gutters[i]] = n.offsetWidth;
michael@0 697 }
michael@0 698 return {fixedPos: compensateForHScroll(d),
michael@0 699 gutterTotalWidth: d.gutters.offsetWidth,
michael@0 700 gutterLeft: left,
michael@0 701 gutterWidth: width,
michael@0 702 wrapperWidth: d.wrapper.clientWidth};
michael@0 703 }
michael@0 704
michael@0 705 // Sync the actual display DOM structure with display.view, removing
michael@0 706 // nodes for lines that are no longer in view, and creating the ones
michael@0 707 // that are not there yet, and updating the ones that are out of
michael@0 708 // date.
michael@0 709 function patchDisplay(cm, updateNumbersFrom, dims) {
michael@0 710 var display = cm.display, lineNumbers = cm.options.lineNumbers;
michael@0 711 var container = display.lineDiv, cur = container.firstChild;
michael@0 712
michael@0 713 function rm(node) {
michael@0 714 var next = node.nextSibling;
michael@0 715 // Works around a throw-scroll bug in OS X Webkit
michael@0 716 if (webkit && mac && cm.display.currentWheelTarget == node)
michael@0 717 node.style.display = "none";
michael@0 718 else
michael@0 719 node.parentNode.removeChild(node);
michael@0 720 return next;
michael@0 721 }
michael@0 722
michael@0 723 var view = display.view, lineN = display.viewFrom;
michael@0 724 // Loop over the elements in the view, syncing cur (the DOM nodes
michael@0 725 // in display.lineDiv) with the view as we go.
michael@0 726 for (var i = 0; i < view.length; i++) {
michael@0 727 var lineView = view[i];
michael@0 728 if (lineView.hidden) {
michael@0 729 } else if (!lineView.node) { // Not drawn yet
michael@0 730 var node = buildLineElement(cm, lineView, lineN, dims);
michael@0 731 container.insertBefore(node, cur);
michael@0 732 } else { // Already drawn
michael@0 733 while (cur != lineView.node) cur = rm(cur);
michael@0 734 var updateNumber = lineNumbers && updateNumbersFrom != null &&
michael@0 735 updateNumbersFrom <= lineN && lineView.lineNumber;
michael@0 736 if (lineView.changes) {
michael@0 737 if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
michael@0 738 updateLineForChanges(cm, lineView, lineN, dims);
michael@0 739 }
michael@0 740 if (updateNumber) {
michael@0 741 removeChildren(lineView.lineNumber);
michael@0 742 lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
michael@0 743 }
michael@0 744 cur = lineView.node.nextSibling;
michael@0 745 }
michael@0 746 lineN += lineView.size;
michael@0 747 }
michael@0 748 while (cur) cur = rm(cur);
michael@0 749 }
michael@0 750
michael@0 751 // When an aspect of a line changes, a string is added to
michael@0 752 // lineView.changes. This updates the relevant part of the line's
michael@0 753 // DOM structure.
michael@0 754 function updateLineForChanges(cm, lineView, lineN, dims) {
michael@0 755 for (var j = 0; j < lineView.changes.length; j++) {
michael@0 756 var type = lineView.changes[j];
michael@0 757 if (type == "text") updateLineText(cm, lineView);
michael@0 758 else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
michael@0 759 else if (type == "class") updateLineClasses(lineView);
michael@0 760 else if (type == "widget") updateLineWidgets(lineView, dims);
michael@0 761 }
michael@0 762 lineView.changes = null;
michael@0 763 }
michael@0 764
michael@0 765 // Lines with gutter elements, widgets or a background class need to
michael@0 766 // be wrapped, and have the extra elements added to the wrapper div
michael@0 767 function ensureLineWrapped(lineView) {
michael@0 768 if (lineView.node == lineView.text) {
michael@0 769 lineView.node = elt("div", null, null, "position: relative");
michael@0 770 if (lineView.text.parentNode)
michael@0 771 lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
michael@0 772 lineView.node.appendChild(lineView.text);
michael@0 773 if (ie_upto7) lineView.node.style.zIndex = 2;
michael@0 774 }
michael@0 775 return lineView.node;
michael@0 776 }
michael@0 777
michael@0 778 function updateLineBackground(lineView) {
michael@0 779 var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
michael@0 780 if (cls) cls += " CodeMirror-linebackground";
michael@0 781 if (lineView.background) {
michael@0 782 if (cls) lineView.background.className = cls;
michael@0 783 else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
michael@0 784 } else if (cls) {
michael@0 785 var wrap = ensureLineWrapped(lineView);
michael@0 786 lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
michael@0 787 }
michael@0 788 }
michael@0 789
michael@0 790 // Wrapper around buildLineContent which will reuse the structure
michael@0 791 // in display.externalMeasured when possible.
michael@0 792 function getLineContent(cm, lineView) {
michael@0 793 var ext = cm.display.externalMeasured;
michael@0 794 if (ext && ext.line == lineView.line) {
michael@0 795 cm.display.externalMeasured = null;
michael@0 796 lineView.measure = ext.measure;
michael@0 797 return ext.built;
michael@0 798 }
michael@0 799 return buildLineContent(cm, lineView);
michael@0 800 }
michael@0 801
michael@0 802 // Redraw the line's text. Interacts with the background and text
michael@0 803 // classes because the mode may output tokens that influence these
michael@0 804 // classes.
michael@0 805 function updateLineText(cm, lineView) {
michael@0 806 var cls = lineView.text.className;
michael@0 807 var built = getLineContent(cm, lineView);
michael@0 808 if (lineView.text == lineView.node) lineView.node = built.pre;
michael@0 809 lineView.text.parentNode.replaceChild(built.pre, lineView.text);
michael@0 810 lineView.text = built.pre;
michael@0 811 if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
michael@0 812 lineView.bgClass = built.bgClass;
michael@0 813 lineView.textClass = built.textClass;
michael@0 814 updateLineClasses(lineView);
michael@0 815 } else if (cls) {
michael@0 816 lineView.text.className = cls;
michael@0 817 }
michael@0 818 }
michael@0 819
michael@0 820 function updateLineClasses(lineView) {
michael@0 821 updateLineBackground(lineView);
michael@0 822 if (lineView.line.wrapClass)
michael@0 823 ensureLineWrapped(lineView).className = lineView.line.wrapClass;
michael@0 824 else if (lineView.node != lineView.text)
michael@0 825 lineView.node.className = "";
michael@0 826 var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
michael@0 827 lineView.text.className = textClass || "";
michael@0 828 }
michael@0 829
michael@0 830 function updateLineGutter(cm, lineView, lineN, dims) {
michael@0 831 if (lineView.gutter) {
michael@0 832 lineView.node.removeChild(lineView.gutter);
michael@0 833 lineView.gutter = null;
michael@0 834 }
michael@0 835 var markers = lineView.line.gutterMarkers;
michael@0 836 if (cm.options.lineNumbers || markers) {
michael@0 837 var wrap = ensureLineWrapped(lineView);
michael@0 838 var gutterWrap = lineView.gutter =
michael@0 839 wrap.insertBefore(elt("div", null, "CodeMirror-gutter-wrapper", "position: absolute; left: " +
michael@0 840 (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"),
michael@0 841 lineView.text);
michael@0 842 if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
michael@0 843 lineView.lineNumber = gutterWrap.appendChild(
michael@0 844 elt("div", lineNumberFor(cm.options, lineN),
michael@0 845 "CodeMirror-linenumber CodeMirror-gutter-elt",
michael@0 846 "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
michael@0 847 + cm.display.lineNumInnerWidth + "px"));
michael@0 848 if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
michael@0 849 var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
michael@0 850 if (found)
michael@0 851 gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
michael@0 852 dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
michael@0 853 }
michael@0 854 }
michael@0 855 }
michael@0 856
michael@0 857 function updateLineWidgets(lineView, dims) {
michael@0 858 if (lineView.alignable) lineView.alignable = null;
michael@0 859 for (var node = lineView.node.firstChild, next; node; node = next) {
michael@0 860 var next = node.nextSibling;
michael@0 861 if (node.className == "CodeMirror-linewidget")
michael@0 862 lineView.node.removeChild(node);
michael@0 863 }
michael@0 864 insertLineWidgets(lineView, dims);
michael@0 865 }
michael@0 866
michael@0 867 // Build a line's DOM representation from scratch
michael@0 868 function buildLineElement(cm, lineView, lineN, dims) {
michael@0 869 var built = getLineContent(cm, lineView);
michael@0 870 lineView.text = lineView.node = built.pre;
michael@0 871 if (built.bgClass) lineView.bgClass = built.bgClass;
michael@0 872 if (built.textClass) lineView.textClass = built.textClass;
michael@0 873
michael@0 874 updateLineClasses(lineView);
michael@0 875 updateLineGutter(cm, lineView, lineN, dims);
michael@0 876 insertLineWidgets(lineView, dims);
michael@0 877 return lineView.node;
michael@0 878 }
michael@0 879
michael@0 880 // A lineView may contain multiple logical lines (when merged by
michael@0 881 // collapsed spans). The widgets for all of them need to be drawn.
michael@0 882 function insertLineWidgets(lineView, dims) {
michael@0 883 insertLineWidgetsFor(lineView.line, lineView, dims, true);
michael@0 884 if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
michael@0 885 insertLineWidgetsFor(lineView.rest[i], lineView, dims, false);
michael@0 886 }
michael@0 887
michael@0 888 function insertLineWidgetsFor(line, lineView, dims, allowAbove) {
michael@0 889 if (!line.widgets) return;
michael@0 890 var wrap = ensureLineWrapped(lineView);
michael@0 891 for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
michael@0 892 var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
michael@0 893 if (!widget.handleMouseEvents) node.ignoreEvents = true;
michael@0 894 positionLineWidget(widget, node, lineView, dims);
michael@0 895 if (allowAbove && widget.above)
michael@0 896 wrap.insertBefore(node, lineView.gutter || lineView.text);
michael@0 897 else
michael@0 898 wrap.appendChild(node);
michael@0 899 signalLater(widget, "redraw");
michael@0 900 }
michael@0 901 }
michael@0 902
michael@0 903 function positionLineWidget(widget, node, lineView, dims) {
michael@0 904 if (widget.noHScroll) {
michael@0 905 (lineView.alignable || (lineView.alignable = [])).push(node);
michael@0 906 var width = dims.wrapperWidth;
michael@0 907 node.style.left = dims.fixedPos + "px";
michael@0 908 if (!widget.coverGutter) {
michael@0 909 width -= dims.gutterTotalWidth;
michael@0 910 node.style.paddingLeft = dims.gutterTotalWidth + "px";
michael@0 911 }
michael@0 912 node.style.width = width + "px";
michael@0 913 }
michael@0 914 if (widget.coverGutter) {
michael@0 915 node.style.zIndex = 5;
michael@0 916 node.style.position = "relative";
michael@0 917 if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
michael@0 918 }
michael@0 919 }
michael@0 920
michael@0 921 // POSITION OBJECT
michael@0 922
michael@0 923 // A Pos instance represents a position within the text.
michael@0 924 var Pos = CodeMirror.Pos = function(line, ch) {
michael@0 925 if (!(this instanceof Pos)) return new Pos(line, ch);
michael@0 926 this.line = line; this.ch = ch;
michael@0 927 };
michael@0 928
michael@0 929 // Compare two positions, return 0 if they are the same, a negative
michael@0 930 // number when a is less, and a positive number otherwise.
michael@0 931 var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
michael@0 932
michael@0 933 function copyPos(x) {return Pos(x.line, x.ch);}
michael@0 934 function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
michael@0 935 function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
michael@0 936
michael@0 937 // SELECTION / CURSOR
michael@0 938
michael@0 939 // Selection objects are immutable. A new one is created every time
michael@0 940 // the selection changes. A selection is one or more non-overlapping
michael@0 941 // (and non-touching) ranges, sorted, and an integer that indicates
michael@0 942 // which one is the primary selection (the one that's scrolled into
michael@0 943 // view, that getCursor returns, etc).
michael@0 944 function Selection(ranges, primIndex) {
michael@0 945 this.ranges = ranges;
michael@0 946 this.primIndex = primIndex;
michael@0 947 }
michael@0 948
michael@0 949 Selection.prototype = {
michael@0 950 primary: function() { return this.ranges[this.primIndex]; },
michael@0 951 equals: function(other) {
michael@0 952 if (other == this) return true;
michael@0 953 if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
michael@0 954 for (var i = 0; i < this.ranges.length; i++) {
michael@0 955 var here = this.ranges[i], there = other.ranges[i];
michael@0 956 if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
michael@0 957 }
michael@0 958 return true;
michael@0 959 },
michael@0 960 deepCopy: function() {
michael@0 961 for (var out = [], i = 0; i < this.ranges.length; i++)
michael@0 962 out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
michael@0 963 return new Selection(out, this.primIndex);
michael@0 964 },
michael@0 965 somethingSelected: function() {
michael@0 966 for (var i = 0; i < this.ranges.length; i++)
michael@0 967 if (!this.ranges[i].empty()) return true;
michael@0 968 return false;
michael@0 969 },
michael@0 970 contains: function(pos, end) {
michael@0 971 if (!end) end = pos;
michael@0 972 for (var i = 0; i < this.ranges.length; i++) {
michael@0 973 var range = this.ranges[i];
michael@0 974 if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
michael@0 975 return i;
michael@0 976 }
michael@0 977 return -1;
michael@0 978 }
michael@0 979 };
michael@0 980
michael@0 981 function Range(anchor, head) {
michael@0 982 this.anchor = anchor; this.head = head;
michael@0 983 }
michael@0 984
michael@0 985 Range.prototype = {
michael@0 986 from: function() { return minPos(this.anchor, this.head); },
michael@0 987 to: function() { return maxPos(this.anchor, this.head); },
michael@0 988 empty: function() {
michael@0 989 return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
michael@0 990 }
michael@0 991 };
michael@0 992
michael@0 993 // Take an unsorted, potentially overlapping set of ranges, and
michael@0 994 // build a selection out of it. 'Consumes' ranges array (modifying
michael@0 995 // it).
michael@0 996 function normalizeSelection(ranges, primIndex) {
michael@0 997 var prim = ranges[primIndex];
michael@0 998 ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
michael@0 999 primIndex = indexOf(ranges, prim);
michael@0 1000 for (var i = 1; i < ranges.length; i++) {
michael@0 1001 var cur = ranges[i], prev = ranges[i - 1];
michael@0 1002 if (cmp(prev.to(), cur.from()) >= 0) {
michael@0 1003 var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
michael@0 1004 var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
michael@0 1005 if (i <= primIndex) --primIndex;
michael@0 1006 ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
michael@0 1007 }
michael@0 1008 }
michael@0 1009 return new Selection(ranges, primIndex);
michael@0 1010 }
michael@0 1011
michael@0 1012 function simpleSelection(anchor, head) {
michael@0 1013 return new Selection([new Range(anchor, head || anchor)], 0);
michael@0 1014 }
michael@0 1015
michael@0 1016 // Most of the external API clips given positions to make sure they
michael@0 1017 // actually exist within the document.
michael@0 1018 function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
michael@0 1019 function clipPos(doc, pos) {
michael@0 1020 if (pos.line < doc.first) return Pos(doc.first, 0);
michael@0 1021 var last = doc.first + doc.size - 1;
michael@0 1022 if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
michael@0 1023 return clipToLen(pos, getLine(doc, pos.line).text.length);
michael@0 1024 }
michael@0 1025 function clipToLen(pos, linelen) {
michael@0 1026 var ch = pos.ch;
michael@0 1027 if (ch == null || ch > linelen) return Pos(pos.line, linelen);
michael@0 1028 else if (ch < 0) return Pos(pos.line, 0);
michael@0 1029 else return pos;
michael@0 1030 }
michael@0 1031 function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
michael@0 1032 function clipPosArray(doc, array) {
michael@0 1033 for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
michael@0 1034 return out;
michael@0 1035 }
michael@0 1036
michael@0 1037 // SELECTION UPDATES
michael@0 1038
michael@0 1039 // The 'scroll' parameter given to many of these indicated whether
michael@0 1040 // the new cursor position should be scrolled into view after
michael@0 1041 // modifying the selection.
michael@0 1042
michael@0 1043 // If shift is held or the extend flag is set, extends a range to
michael@0 1044 // include a given position (and optionally a second position).
michael@0 1045 // Otherwise, simply returns the range between the given positions.
michael@0 1046 // Used for cursor motion and such.
michael@0 1047 function extendRange(doc, range, head, other) {
michael@0 1048 if (doc.cm && doc.cm.display.shift || doc.extend) {
michael@0 1049 var anchor = range.anchor;
michael@0 1050 if (other) {
michael@0 1051 var posBefore = cmp(head, anchor) < 0;
michael@0 1052 if (posBefore != (cmp(other, anchor) < 0)) {
michael@0 1053 anchor = head;
michael@0 1054 head = other;
michael@0 1055 } else if (posBefore != (cmp(head, other) < 0)) {
michael@0 1056 head = other;
michael@0 1057 }
michael@0 1058 }
michael@0 1059 return new Range(anchor, head);
michael@0 1060 } else {
michael@0 1061 return new Range(other || head, head);
michael@0 1062 }
michael@0 1063 }
michael@0 1064
michael@0 1065 // Extend the primary selection range, discard the rest.
michael@0 1066 function extendSelection(doc, head, other, options) {
michael@0 1067 setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
michael@0 1068 }
michael@0 1069
michael@0 1070 // Extend all selections (pos is an array of selections with length
michael@0 1071 // equal the number of selections)
michael@0 1072 function extendSelections(doc, heads, options) {
michael@0 1073 for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
michael@0 1074 out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
michael@0 1075 var newSel = normalizeSelection(out, doc.sel.primIndex);
michael@0 1076 setSelection(doc, newSel, options);
michael@0 1077 }
michael@0 1078
michael@0 1079 // Updates a single range in the selection.
michael@0 1080 function replaceOneSelection(doc, i, range, options) {
michael@0 1081 var ranges = doc.sel.ranges.slice(0);
michael@0 1082 ranges[i] = range;
michael@0 1083 setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
michael@0 1084 }
michael@0 1085
michael@0 1086 // Reset the selection to a single range.
michael@0 1087 function setSimpleSelection(doc, anchor, head, options) {
michael@0 1088 setSelection(doc, simpleSelection(anchor, head), options);
michael@0 1089 }
michael@0 1090
michael@0 1091 // Give beforeSelectionChange handlers a change to influence a
michael@0 1092 // selection update.
michael@0 1093 function filterSelectionChange(doc, sel) {
michael@0 1094 var obj = {
michael@0 1095 ranges: sel.ranges,
michael@0 1096 update: function(ranges) {
michael@0 1097 this.ranges = [];
michael@0 1098 for (var i = 0; i < ranges.length; i++)
michael@0 1099 this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
michael@0 1100 clipPos(doc, ranges[i].head));
michael@0 1101 }
michael@0 1102 };
michael@0 1103 signal(doc, "beforeSelectionChange", doc, obj);
michael@0 1104 if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
michael@0 1105 if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
michael@0 1106 else return sel;
michael@0 1107 }
michael@0 1108
michael@0 1109 function setSelectionReplaceHistory(doc, sel, options) {
michael@0 1110 var done = doc.history.done, last = lst(done);
michael@0 1111 if (last && last.ranges) {
michael@0 1112 done[done.length - 1] = sel;
michael@0 1113 setSelectionNoUndo(doc, sel, options);
michael@0 1114 } else {
michael@0 1115 setSelection(doc, sel, options);
michael@0 1116 }
michael@0 1117 }
michael@0 1118
michael@0 1119 // Set a new selection.
michael@0 1120 function setSelection(doc, sel, options) {
michael@0 1121 setSelectionNoUndo(doc, sel, options);
michael@0 1122 addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
michael@0 1123 }
michael@0 1124
michael@0 1125 function setSelectionNoUndo(doc, sel, options) {
michael@0 1126 if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
michael@0 1127 sel = filterSelectionChange(doc, sel);
michael@0 1128
michael@0 1129 var bias = cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1;
michael@0 1130 setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
michael@0 1131
michael@0 1132 if (!(options && options.scroll === false) && doc.cm)
michael@0 1133 ensureCursorVisible(doc.cm);
michael@0 1134 }
michael@0 1135
michael@0 1136 function setSelectionInner(doc, sel) {
michael@0 1137 if (sel.equals(doc.sel)) return;
michael@0 1138
michael@0 1139 doc.sel = sel;
michael@0 1140
michael@0 1141 if (doc.cm)
michael@0 1142 doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged =
michael@0 1143 doc.cm.curOp.cursorActivity = true;
michael@0 1144 signalLater(doc, "cursorActivity", doc);
michael@0 1145 }
michael@0 1146
michael@0 1147 // Verify that the selection does not partially select any atomic
michael@0 1148 // marked ranges.
michael@0 1149 function reCheckSelection(doc) {
michael@0 1150 setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
michael@0 1151 }
michael@0 1152
michael@0 1153 // Return a selection that does not partially select any atomic
michael@0 1154 // ranges.
michael@0 1155 function skipAtomicInSelection(doc, sel, bias, mayClear) {
michael@0 1156 var out;
michael@0 1157 for (var i = 0; i < sel.ranges.length; i++) {
michael@0 1158 var range = sel.ranges[i];
michael@0 1159 var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear);
michael@0 1160 var newHead = skipAtomic(doc, range.head, bias, mayClear);
michael@0 1161 if (out || newAnchor != range.anchor || newHead != range.head) {
michael@0 1162 if (!out) out = sel.ranges.slice(0, i);
michael@0 1163 out[i] = new Range(newAnchor, newHead);
michael@0 1164 }
michael@0 1165 }
michael@0 1166 return out ? normalizeSelection(out, sel.primIndex) : sel;
michael@0 1167 }
michael@0 1168
michael@0 1169 // Ensure a given position is not inside an atomic range.
michael@0 1170 function skipAtomic(doc, pos, bias, mayClear) {
michael@0 1171 var flipped = false, curPos = pos;
michael@0 1172 var dir = bias || 1;
michael@0 1173 doc.cantEdit = false;
michael@0 1174 search: for (;;) {
michael@0 1175 var line = getLine(doc, curPos.line);
michael@0 1176 if (line.markedSpans) {
michael@0 1177 for (var i = 0; i < line.markedSpans.length; ++i) {
michael@0 1178 var sp = line.markedSpans[i], m = sp.marker;
michael@0 1179 if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
michael@0 1180 (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
michael@0 1181 if (mayClear) {
michael@0 1182 signal(m, "beforeCursorEnter");
michael@0 1183 if (m.explicitlyCleared) {
michael@0 1184 if (!line.markedSpans) break;
michael@0 1185 else {--i; continue;}
michael@0 1186 }
michael@0 1187 }
michael@0 1188 if (!m.atomic) continue;
michael@0 1189 var newPos = m.find(dir < 0 ? -1 : 1);
michael@0 1190 if (cmp(newPos, curPos) == 0) {
michael@0 1191 newPos.ch += dir;
michael@0 1192 if (newPos.ch < 0) {
michael@0 1193 if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
michael@0 1194 else newPos = null;
michael@0 1195 } else if (newPos.ch > line.text.length) {
michael@0 1196 if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
michael@0 1197 else newPos = null;
michael@0 1198 }
michael@0 1199 if (!newPos) {
michael@0 1200 if (flipped) {
michael@0 1201 // Driven in a corner -- no valid cursor position found at all
michael@0 1202 // -- try again *with* clearing, if we didn't already
michael@0 1203 if (!mayClear) return skipAtomic(doc, pos, bias, true);
michael@0 1204 // Otherwise, turn off editing until further notice, and return the start of the doc
michael@0 1205 doc.cantEdit = true;
michael@0 1206 return Pos(doc.first, 0);
michael@0 1207 }
michael@0 1208 flipped = true; newPos = pos; dir = -dir;
michael@0 1209 }
michael@0 1210 }
michael@0 1211 curPos = newPos;
michael@0 1212 continue search;
michael@0 1213 }
michael@0 1214 }
michael@0 1215 }
michael@0 1216 return curPos;
michael@0 1217 }
michael@0 1218 }
michael@0 1219
michael@0 1220 // SELECTION DRAWING
michael@0 1221
michael@0 1222 // Redraw the selection and/or cursor
michael@0 1223 function updateSelection(cm) {
michael@0 1224 var display = cm.display, doc = cm.doc;
michael@0 1225 var curFragment = document.createDocumentFragment();
michael@0 1226 var selFragment = document.createDocumentFragment();
michael@0 1227
michael@0 1228 for (var i = 0; i < doc.sel.ranges.length; i++) {
michael@0 1229 var range = doc.sel.ranges[i];
michael@0 1230 var collapsed = range.empty();
michael@0 1231 if (collapsed || cm.options.showCursorWhenSelecting)
michael@0 1232 updateSelectionCursor(cm, range, curFragment);
michael@0 1233 if (!collapsed)
michael@0 1234 updateSelectionRange(cm, range, selFragment);
michael@0 1235 }
michael@0 1236
michael@0 1237 // Move the hidden textarea near the cursor to prevent scrolling artifacts
michael@0 1238 if (cm.options.moveInputWithCursor) {
michael@0 1239 var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
michael@0 1240 var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
michael@0 1241 var top = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
michael@0 1242 headPos.top + lineOff.top - wrapOff.top));
michael@0 1243 var left = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
michael@0 1244 headPos.left + lineOff.left - wrapOff.left));
michael@0 1245 display.inputDiv.style.top = top + "px";
michael@0 1246 display.inputDiv.style.left = left + "px";
michael@0 1247 }
michael@0 1248
michael@0 1249 removeChildrenAndAdd(display.cursorDiv, curFragment);
michael@0 1250 removeChildrenAndAdd(display.selectionDiv, selFragment);
michael@0 1251 }
michael@0 1252
michael@0 1253 // Draws a cursor for the given range
michael@0 1254 function updateSelectionCursor(cm, range, output) {
michael@0 1255 var pos = cursorCoords(cm, range.head, "div");
michael@0 1256
michael@0 1257 var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
michael@0 1258 cursor.style.left = pos.left + "px";
michael@0 1259 cursor.style.top = pos.top + "px";
michael@0 1260 cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
michael@0 1261
michael@0 1262 if (pos.other) {
michael@0 1263 // Secondary cursor, shown when on a 'jump' in bi-directional text
michael@0 1264 var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
michael@0 1265 otherCursor.style.display = "";
michael@0 1266 otherCursor.style.left = pos.other.left + "px";
michael@0 1267 otherCursor.style.top = pos.other.top + "px";
michael@0 1268 otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
michael@0 1269 }
michael@0 1270 }
michael@0 1271
michael@0 1272 // Draws the given range as a highlighted selection
michael@0 1273 function updateSelectionRange(cm, range, output) {
michael@0 1274 var display = cm.display, doc = cm.doc;
michael@0 1275 var fragment = document.createDocumentFragment();
michael@0 1276 var padding = paddingH(cm.display), leftSide = padding.left, rightSide = display.lineSpace.offsetWidth - padding.right;
michael@0 1277
michael@0 1278 function add(left, top, width, bottom) {
michael@0 1279 if (top < 0) top = 0;
michael@0 1280 fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
michael@0 1281 "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
michael@0 1282 "px; height: " + (bottom - top) + "px"));
michael@0 1283 }
michael@0 1284
michael@0 1285 function drawForLine(line, fromArg, toArg) {
michael@0 1286 var lineObj = getLine(doc, line);
michael@0 1287 var lineLen = lineObj.text.length;
michael@0 1288 var start, end;
michael@0 1289 function coords(ch, bias) {
michael@0 1290 return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
michael@0 1291 }
michael@0 1292
michael@0 1293 iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
michael@0 1294 var leftPos = coords(from, "left"), rightPos, left, right;
michael@0 1295 if (from == to) {
michael@0 1296 rightPos = leftPos;
michael@0 1297 left = right = leftPos.left;
michael@0 1298 } else {
michael@0 1299 rightPos = coords(to - 1, "right");
michael@0 1300 if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
michael@0 1301 left = leftPos.left;
michael@0 1302 right = rightPos.right;
michael@0 1303 }
michael@0 1304 if (fromArg == null && from == 0) left = leftSide;
michael@0 1305 if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
michael@0 1306 add(left, leftPos.top, null, leftPos.bottom);
michael@0 1307 left = leftSide;
michael@0 1308 if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
michael@0 1309 }
michael@0 1310 if (toArg == null && to == lineLen) right = rightSide;
michael@0 1311 if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
michael@0 1312 start = leftPos;
michael@0 1313 if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
michael@0 1314 end = rightPos;
michael@0 1315 if (left < leftSide + 1) left = leftSide;
michael@0 1316 add(left, rightPos.top, right - left, rightPos.bottom);
michael@0 1317 });
michael@0 1318 return {start: start, end: end};
michael@0 1319 }
michael@0 1320
michael@0 1321 var sFrom = range.from(), sTo = range.to();
michael@0 1322 if (sFrom.line == sTo.line) {
michael@0 1323 drawForLine(sFrom.line, sFrom.ch, sTo.ch);
michael@0 1324 } else {
michael@0 1325 var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
michael@0 1326 var singleVLine = visualLine(fromLine) == visualLine(toLine);
michael@0 1327 var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
michael@0 1328 var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
michael@0 1329 if (singleVLine) {
michael@0 1330 if (leftEnd.top < rightStart.top - 2) {
michael@0 1331 add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
michael@0 1332 add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
michael@0 1333 } else {
michael@0 1334 add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
michael@0 1335 }
michael@0 1336 }
michael@0 1337 if (leftEnd.bottom < rightStart.top)
michael@0 1338 add(leftSide, leftEnd.bottom, null, rightStart.top);
michael@0 1339 }
michael@0 1340
michael@0 1341 output.appendChild(fragment);
michael@0 1342 }
michael@0 1343
michael@0 1344 // Cursor-blinking
michael@0 1345 function restartBlink(cm) {
michael@0 1346 if (!cm.state.focused) return;
michael@0 1347 var display = cm.display;
michael@0 1348 clearInterval(display.blinker);
michael@0 1349 var on = true;
michael@0 1350 display.cursorDiv.style.visibility = "";
michael@0 1351 if (cm.options.cursorBlinkRate > 0)
michael@0 1352 display.blinker = setInterval(function() {
michael@0 1353 display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
michael@0 1354 }, cm.options.cursorBlinkRate);
michael@0 1355 }
michael@0 1356
michael@0 1357 // HIGHLIGHT WORKER
michael@0 1358
michael@0 1359 function startWorker(cm, time) {
michael@0 1360 if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
michael@0 1361 cm.state.highlight.set(time, bind(highlightWorker, cm));
michael@0 1362 }
michael@0 1363
michael@0 1364 function highlightWorker(cm) {
michael@0 1365 var doc = cm.doc;
michael@0 1366 if (doc.frontier < doc.first) doc.frontier = doc.first;
michael@0 1367 if (doc.frontier >= cm.display.viewTo) return;
michael@0 1368 var end = +new Date + cm.options.workTime;
michael@0 1369 var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
michael@0 1370
michael@0 1371 runInOp(cm, function() {
michael@0 1372 doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
michael@0 1373 if (doc.frontier >= cm.display.viewFrom) { // Visible
michael@0 1374 var oldStyles = line.styles;
michael@0 1375 line.styles = highlightLine(cm, line, state, true);
michael@0 1376 var ischange = !oldStyles || oldStyles.length != line.styles.length;
michael@0 1377 for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
michael@0 1378 if (ischange) regLineChange(cm, doc.frontier, "text");
michael@0 1379 line.stateAfter = copyState(doc.mode, state);
michael@0 1380 } else {
michael@0 1381 processLine(cm, line.text, state);
michael@0 1382 line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
michael@0 1383 }
michael@0 1384 ++doc.frontier;
michael@0 1385 if (+new Date > end) {
michael@0 1386 startWorker(cm, cm.options.workDelay);
michael@0 1387 return true;
michael@0 1388 }
michael@0 1389 });
michael@0 1390 });
michael@0 1391 }
michael@0 1392
michael@0 1393 // Finds the line to start with when starting a parse. Tries to
michael@0 1394 // find a line with a stateAfter, so that it can start with a
michael@0 1395 // valid state. If that fails, it returns the line with the
michael@0 1396 // smallest indentation, which tends to need the least context to
michael@0 1397 // parse correctly.
michael@0 1398 function findStartLine(cm, n, precise) {
michael@0 1399 var minindent, minline, doc = cm.doc;
michael@0 1400 var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
michael@0 1401 for (var search = n; search > lim; --search) {
michael@0 1402 if (search <= doc.first) return doc.first;
michael@0 1403 var line = getLine(doc, search - 1);
michael@0 1404 if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
michael@0 1405 var indented = countColumn(line.text, null, cm.options.tabSize);
michael@0 1406 if (minline == null || minindent > indented) {
michael@0 1407 minline = search - 1;
michael@0 1408 minindent = indented;
michael@0 1409 }
michael@0 1410 }
michael@0 1411 return minline;
michael@0 1412 }
michael@0 1413
michael@0 1414 function getStateBefore(cm, n, precise) {
michael@0 1415 var doc = cm.doc, display = cm.display;
michael@0 1416 if (!doc.mode.startState) return true;
michael@0 1417 var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
michael@0 1418 if (!state) state = startState(doc.mode);
michael@0 1419 else state = copyState(doc.mode, state);
michael@0 1420 doc.iter(pos, n, function(line) {
michael@0 1421 processLine(cm, line.text, state);
michael@0 1422 var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
michael@0 1423 line.stateAfter = save ? copyState(doc.mode, state) : null;
michael@0 1424 ++pos;
michael@0 1425 });
michael@0 1426 if (precise) doc.frontier = pos;
michael@0 1427 return state;
michael@0 1428 }
michael@0 1429
michael@0 1430 // POSITION MEASUREMENT
michael@0 1431
michael@0 1432 function paddingTop(display) {return display.lineSpace.offsetTop;}
michael@0 1433 function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
michael@0 1434 function paddingH(display) {
michael@0 1435 if (display.cachedPaddingH) return display.cachedPaddingH;
michael@0 1436 var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
michael@0 1437 var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
michael@0 1438 return display.cachedPaddingH = {left: parseInt(style.paddingLeft),
michael@0 1439 right: parseInt(style.paddingRight)};
michael@0 1440 }
michael@0 1441
michael@0 1442 // Ensure the lineView.wrapping.heights array is populated. This is
michael@0 1443 // an array of bottom offsets for the lines that make up a drawn
michael@0 1444 // line. When lineWrapping is on, there might be more than one
michael@0 1445 // height.
michael@0 1446 function ensureLineHeights(cm, lineView, rect) {
michael@0 1447 var wrapping = cm.options.lineWrapping;
michael@0 1448 var curWidth = wrapping && cm.display.scroller.clientWidth;
michael@0 1449 if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
michael@0 1450 var heights = lineView.measure.heights = [];
michael@0 1451 if (wrapping) {
michael@0 1452 lineView.measure.width = curWidth;
michael@0 1453 var rects = lineView.text.firstChild.getClientRects();
michael@0 1454 for (var i = 0; i < rects.length - 1; i++) {
michael@0 1455 var cur = rects[i], next = rects[i + 1];
michael@0 1456 if (Math.abs(cur.bottom - next.bottom) > 2)
michael@0 1457 heights.push((cur.bottom + next.top) / 2 - rect.top);
michael@0 1458 }
michael@0 1459 }
michael@0 1460 heights.push(rect.bottom - rect.top);
michael@0 1461 }
michael@0 1462 }
michael@0 1463
michael@0 1464 // Find a line map (mapping character offsets to text nodes) and a
michael@0 1465 // measurement cache for the given line number. (A line view might
michael@0 1466 // contain multiple lines when collapsed ranges are present.)
michael@0 1467 function mapFromLineView(lineView, line, lineN) {
michael@0 1468 if (lineView.line == line)
michael@0 1469 return {map: lineView.measure.map, cache: lineView.measure.cache};
michael@0 1470 for (var i = 0; i < lineView.rest.length; i++)
michael@0 1471 if (lineView.rest[i] == line)
michael@0 1472 return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
michael@0 1473 for (var i = 0; i < lineView.rest.length; i++)
michael@0 1474 if (lineNo(lineView.rest[i]) > lineN)
michael@0 1475 return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
michael@0 1476 }
michael@0 1477
michael@0 1478 // Render a line into the hidden node display.externalMeasured. Used
michael@0 1479 // when measurement is needed for a line that's not in the viewport.
michael@0 1480 function updateExternalMeasurement(cm, line) {
michael@0 1481 line = visualLine(line);
michael@0 1482 var lineN = lineNo(line);
michael@0 1483 var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
michael@0 1484 view.lineN = lineN;
michael@0 1485 var built = view.built = buildLineContent(cm, view);
michael@0 1486 view.text = built.pre;
michael@0 1487 removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
michael@0 1488 return view;
michael@0 1489 }
michael@0 1490
michael@0 1491 // Get a {top, bottom, left, right} box (in line-local coordinates)
michael@0 1492 // for a given character.
michael@0 1493 function measureChar(cm, line, ch, bias) {
michael@0 1494 return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
michael@0 1495 }
michael@0 1496
michael@0 1497 // Find a line view that corresponds to the given line number.
michael@0 1498 function findViewForLine(cm, lineN) {
michael@0 1499 if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
michael@0 1500 return cm.display.view[findViewIndex(cm, lineN)];
michael@0 1501 var ext = cm.display.externalMeasured;
michael@0 1502 if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
michael@0 1503 return ext;
michael@0 1504 }
michael@0 1505
michael@0 1506 // Measurement can be split in two steps, the set-up work that
michael@0 1507 // applies to the whole line, and the measurement of the actual
michael@0 1508 // character. Functions like coordsChar, that need to do a lot of
michael@0 1509 // measurements in a row, can thus ensure that the set-up work is
michael@0 1510 // only done once.
michael@0 1511 function prepareMeasureForLine(cm, line) {
michael@0 1512 var lineN = lineNo(line);
michael@0 1513 var view = findViewForLine(cm, lineN);
michael@0 1514 if (view && !view.text)
michael@0 1515 view = null;
michael@0 1516 else if (view && view.changes)
michael@0 1517 updateLineForChanges(cm, view, lineN, getDimensions(cm));
michael@0 1518 if (!view)
michael@0 1519 view = updateExternalMeasurement(cm, line);
michael@0 1520
michael@0 1521 var info = mapFromLineView(view, line, lineN);
michael@0 1522 return {
michael@0 1523 line: line, view: view, rect: null,
michael@0 1524 map: info.map, cache: info.cache, before: info.before,
michael@0 1525 hasHeights: false
michael@0 1526 };
michael@0 1527 }
michael@0 1528
michael@0 1529 // Given a prepared measurement object, measures the position of an
michael@0 1530 // actual character (or fetches it from the cache).
michael@0 1531 function measureCharPrepared(cm, prepared, ch, bias) {
michael@0 1532 if (prepared.before) ch = -1;
michael@0 1533 var key = ch + (bias || ""), found;
michael@0 1534 if (prepared.cache.hasOwnProperty(key)) {
michael@0 1535 found = prepared.cache[key];
michael@0 1536 } else {
michael@0 1537 if (!prepared.rect)
michael@0 1538 prepared.rect = prepared.view.text.getBoundingClientRect();
michael@0 1539 if (!prepared.hasHeights) {
michael@0 1540 ensureLineHeights(cm, prepared.view, prepared.rect);
michael@0 1541 prepared.hasHeights = true;
michael@0 1542 }
michael@0 1543 found = measureCharInner(cm, prepared, ch, bias);
michael@0 1544 if (!found.bogus) prepared.cache[key] = found;
michael@0 1545 }
michael@0 1546 return {left: found.left, right: found.right, top: found.top, bottom: found.bottom};
michael@0 1547 }
michael@0 1548
michael@0 1549 var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
michael@0 1550
michael@0 1551 function measureCharInner(cm, prepared, ch, bias) {
michael@0 1552 var map = prepared.map;
michael@0 1553
michael@0 1554 var node, start, end, collapse;
michael@0 1555 // First, search the line map for the text node corresponding to,
michael@0 1556 // or closest to, the target character.
michael@0 1557 for (var i = 0; i < map.length; i += 3) {
michael@0 1558 var mStart = map[i], mEnd = map[i + 1];
michael@0 1559 if (ch < mStart) {
michael@0 1560 start = 0; end = 1;
michael@0 1561 collapse = "left";
michael@0 1562 } else if (ch < mEnd) {
michael@0 1563 start = ch - mStart;
michael@0 1564 end = start + 1;
michael@0 1565 } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
michael@0 1566 end = mEnd - mStart;
michael@0 1567 start = end - 1;
michael@0 1568 if (ch >= mEnd) collapse = "right";
michael@0 1569 }
michael@0 1570 if (start != null) {
michael@0 1571 node = map[i + 2];
michael@0 1572 if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
michael@0 1573 collapse = bias;
michael@0 1574 if (bias == "left" && start == 0)
michael@0 1575 while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
michael@0 1576 node = map[(i -= 3) + 2];
michael@0 1577 collapse = "left";
michael@0 1578 }
michael@0 1579 if (bias == "right" && start == mEnd - mStart)
michael@0 1580 while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
michael@0 1581 node = map[(i += 3) + 2];
michael@0 1582 collapse = "right";
michael@0 1583 }
michael@0 1584 break;
michael@0 1585 }
michael@0 1586 }
michael@0 1587
michael@0 1588 var rect;
michael@0 1589 if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
michael@0 1590 while (start && isExtendingChar(prepared.line.text.charAt(mStart + start))) --start;
michael@0 1591 while (mStart + end < mEnd && isExtendingChar(prepared.line.text.charAt(mStart + end))) ++end;
michael@0 1592 if (ie_upto8 && start == 0 && end == mEnd - mStart) {
michael@0 1593 rect = node.parentNode.getBoundingClientRect();
michael@0 1594 } else if (ie && cm.options.lineWrapping) {
michael@0 1595 var rects = range(node, start, end).getClientRects();
michael@0 1596 if (rects.length)
michael@0 1597 rect = rects[bias == "right" ? rects.length - 1 : 0];
michael@0 1598 else
michael@0 1599 rect = nullRect;
michael@0 1600 } else {
michael@0 1601 rect = range(node, start, end).getBoundingClientRect();
michael@0 1602 }
michael@0 1603 } else { // If it is a widget, simply get the box for the whole widget.
michael@0 1604 if (start > 0) collapse = bias = "right";
michael@0 1605 var rects;
michael@0 1606 if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
michael@0 1607 rect = rects[bias == "right" ? rects.length - 1 : 0];
michael@0 1608 else
michael@0 1609 rect = node.getBoundingClientRect();
michael@0 1610 }
michael@0 1611 if (ie_upto8 && !start && (!rect || !rect.left && !rect.right)) {
michael@0 1612 var rSpan = node.parentNode.getClientRects()[0];
michael@0 1613 if (rSpan)
michael@0 1614 rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
michael@0 1615 else
michael@0 1616 rect = nullRect;
michael@0 1617 }
michael@0 1618
michael@0 1619 var top, bot = (rect.bottom + rect.top) / 2 - prepared.rect.top;
michael@0 1620 var heights = prepared.view.measure.heights;
michael@0 1621 for (var i = 0; i < heights.length - 1; i++)
michael@0 1622 if (bot < heights[i]) break;
michael@0 1623 top = i ? heights[i - 1] : 0; bot = heights[i];
michael@0 1624 var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
michael@0 1625 right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
michael@0 1626 top: top, bottom: bot};
michael@0 1627 if (!rect.left && !rect.right) result.bogus = true;
michael@0 1628 return result;
michael@0 1629 }
michael@0 1630
michael@0 1631 function clearLineMeasurementCacheFor(lineView) {
michael@0 1632 if (lineView.measure) {
michael@0 1633 lineView.measure.cache = {};
michael@0 1634 lineView.measure.heights = null;
michael@0 1635 if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
michael@0 1636 lineView.measure.caches[i] = {};
michael@0 1637 }
michael@0 1638 }
michael@0 1639
michael@0 1640 function clearLineMeasurementCache(cm) {
michael@0 1641 cm.display.externalMeasure = null;
michael@0 1642 removeChildren(cm.display.lineMeasure);
michael@0 1643 for (var i = 0; i < cm.display.view.length; i++)
michael@0 1644 clearLineMeasurementCacheFor(cm.display.view[i]);
michael@0 1645 }
michael@0 1646
michael@0 1647 function clearCaches(cm) {
michael@0 1648 clearLineMeasurementCache(cm);
michael@0 1649 cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
michael@0 1650 if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
michael@0 1651 cm.display.lineNumChars = null;
michael@0 1652 }
michael@0 1653
michael@0 1654 function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
michael@0 1655 function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
michael@0 1656
michael@0 1657 // Converts a {top, bottom, left, right} box from line-local
michael@0 1658 // coordinates into another coordinate system. Context may be one of
michael@0 1659 // "line", "div" (display.lineDiv), "local"/null (editor), or "page".
michael@0 1660 function intoCoordSystem(cm, lineObj, rect, context) {
michael@0 1661 if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
michael@0 1662 var size = widgetHeight(lineObj.widgets[i]);
michael@0 1663 rect.top += size; rect.bottom += size;
michael@0 1664 }
michael@0 1665 if (context == "line") return rect;
michael@0 1666 if (!context) context = "local";
michael@0 1667 var yOff = heightAtLine(lineObj);
michael@0 1668 if (context == "local") yOff += paddingTop(cm.display);
michael@0 1669 else yOff -= cm.display.viewOffset;
michael@0 1670 if (context == "page" || context == "window") {
michael@0 1671 var lOff = cm.display.lineSpace.getBoundingClientRect();
michael@0 1672 yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
michael@0 1673 var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
michael@0 1674 rect.left += xOff; rect.right += xOff;
michael@0 1675 }
michael@0 1676 rect.top += yOff; rect.bottom += yOff;
michael@0 1677 return rect;
michael@0 1678 }
michael@0 1679
michael@0 1680 // Coverts a box from "div" coords to another coordinate system.
michael@0 1681 // Context may be "window", "page", "div", or "local"/null.
michael@0 1682 function fromCoordSystem(cm, coords, context) {
michael@0 1683 if (context == "div") return coords;
michael@0 1684 var left = coords.left, top = coords.top;
michael@0 1685 // First move into "page" coordinate system
michael@0 1686 if (context == "page") {
michael@0 1687 left -= pageScrollX();
michael@0 1688 top -= pageScrollY();
michael@0 1689 } else if (context == "local" || !context) {
michael@0 1690 var localBox = cm.display.sizer.getBoundingClientRect();
michael@0 1691 left += localBox.left;
michael@0 1692 top += localBox.top;
michael@0 1693 }
michael@0 1694
michael@0 1695 var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
michael@0 1696 return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
michael@0 1697 }
michael@0 1698
michael@0 1699 function charCoords(cm, pos, context, lineObj, bias) {
michael@0 1700 if (!lineObj) lineObj = getLine(cm.doc, pos.line);
michael@0 1701 return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
michael@0 1702 }
michael@0 1703
michael@0 1704 // Returns a box for a given cursor position, which may have an
michael@0 1705 // 'other' property containing the position of the secondary cursor
michael@0 1706 // on a bidi boundary.
michael@0 1707 function cursorCoords(cm, pos, context, lineObj, preparedMeasure) {
michael@0 1708 lineObj = lineObj || getLine(cm.doc, pos.line);
michael@0 1709 if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
michael@0 1710 function get(ch, right) {
michael@0 1711 var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left");
michael@0 1712 if (right) m.left = m.right; else m.right = m.left;
michael@0 1713 return intoCoordSystem(cm, lineObj, m, context);
michael@0 1714 }
michael@0 1715 function getBidi(ch, partPos) {
michael@0 1716 var part = order[partPos], right = part.level % 2;
michael@0 1717 if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
michael@0 1718 part = order[--partPos];
michael@0 1719 ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
michael@0 1720 right = true;
michael@0 1721 } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
michael@0 1722 part = order[++partPos];
michael@0 1723 ch = bidiLeft(part) - part.level % 2;
michael@0 1724 right = false;
michael@0 1725 }
michael@0 1726 if (right && ch == part.to && ch > part.from) return get(ch - 1);
michael@0 1727 return get(ch, right);
michael@0 1728 }
michael@0 1729 var order = getOrder(lineObj), ch = pos.ch;
michael@0 1730 if (!order) return get(ch);
michael@0 1731 var partPos = getBidiPartAt(order, ch);
michael@0 1732 var val = getBidi(ch, partPos);
michael@0 1733 if (bidiOther != null) val.other = getBidi(ch, bidiOther);
michael@0 1734 return val;
michael@0 1735 }
michael@0 1736
michael@0 1737 // Used to cheaply estimate the coordinates for a position. Used for
michael@0 1738 // intermediate scroll updates.
michael@0 1739 function estimateCoords(cm, pos) {
michael@0 1740 var left = 0, pos = clipPos(cm.doc, pos);
michael@0 1741 if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
michael@0 1742 var lineObj = getLine(cm.doc, pos.line);
michael@0 1743 var top = heightAtLine(lineObj) + paddingTop(cm.display);
michael@0 1744 return {left: left, right: left, top: top, bottom: top + lineObj.height};
michael@0 1745 }
michael@0 1746
michael@0 1747 // Positions returned by coordsChar contain some extra information.
michael@0 1748 // xRel is the relative x position of the input coordinates compared
michael@0 1749 // to the found position (so xRel > 0 means the coordinates are to
michael@0 1750 // the right of the character position, for example). When outside
michael@0 1751 // is true, that means the coordinates lie outside the line's
michael@0 1752 // vertical range.
michael@0 1753 function PosWithInfo(line, ch, outside, xRel) {
michael@0 1754 var pos = Pos(line, ch);
michael@0 1755 pos.xRel = xRel;
michael@0 1756 if (outside) pos.outside = true;
michael@0 1757 return pos;
michael@0 1758 }
michael@0 1759
michael@0 1760 // Compute the character position closest to the given coordinates.
michael@0 1761 // Input must be lineSpace-local ("div" coordinate system).
michael@0 1762 function coordsChar(cm, x, y) {
michael@0 1763 var doc = cm.doc;
michael@0 1764 y += cm.display.viewOffset;
michael@0 1765 if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
michael@0 1766 var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
michael@0 1767 if (lineN > last)
michael@0 1768 return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
michael@0 1769 if (x < 0) x = 0;
michael@0 1770
michael@0 1771 var lineObj = getLine(doc, lineN);
michael@0 1772 for (;;) {
michael@0 1773 var found = coordsCharInner(cm, lineObj, lineN, x, y);
michael@0 1774 var merged = collapsedSpanAtEnd(lineObj);
michael@0 1775 var mergedPos = merged && merged.find(0, true);
michael@0 1776 if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
michael@0 1777 lineN = lineNo(lineObj = mergedPos.to.line);
michael@0 1778 else
michael@0 1779 return found;
michael@0 1780 }
michael@0 1781 }
michael@0 1782
michael@0 1783 function coordsCharInner(cm, lineObj, lineNo, x, y) {
michael@0 1784 var innerOff = y - heightAtLine(lineObj);
michael@0 1785 var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
michael@0 1786 var preparedMeasure = prepareMeasureForLine(cm, lineObj);
michael@0 1787
michael@0 1788 function getX(ch) {
michael@0 1789 var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
michael@0 1790 wrongLine = true;
michael@0 1791 if (innerOff > sp.bottom) return sp.left - adjust;
michael@0 1792 else if (innerOff < sp.top) return sp.left + adjust;
michael@0 1793 else wrongLine = false;
michael@0 1794 return sp.left;
michael@0 1795 }
michael@0 1796
michael@0 1797 var bidi = getOrder(lineObj), dist = lineObj.text.length;
michael@0 1798 var from = lineLeft(lineObj), to = lineRight(lineObj);
michael@0 1799 var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
michael@0 1800
michael@0 1801 if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
michael@0 1802 // Do a binary search between these bounds.
michael@0 1803 for (;;) {
michael@0 1804 if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
michael@0 1805 var ch = x < fromX || x - fromX <= toX - x ? from : to;
michael@0 1806 var xDiff = x - (ch == from ? fromX : toX);
michael@0 1807 while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
michael@0 1808 var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
michael@0 1809 xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
michael@0 1810 return pos;
michael@0 1811 }
michael@0 1812 var step = Math.ceil(dist / 2), middle = from + step;
michael@0 1813 if (bidi) {
michael@0 1814 middle = from;
michael@0 1815 for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
michael@0 1816 }
michael@0 1817 var middleX = getX(middle);
michael@0 1818 if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
michael@0 1819 else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
michael@0 1820 }
michael@0 1821 }
michael@0 1822
michael@0 1823 var measureText;
michael@0 1824 // Compute the default text height.
michael@0 1825 function textHeight(display) {
michael@0 1826 if (display.cachedTextHeight != null) return display.cachedTextHeight;
michael@0 1827 if (measureText == null) {
michael@0 1828 measureText = elt("pre");
michael@0 1829 // Measure a bunch of lines, for browsers that compute
michael@0 1830 // fractional heights.
michael@0 1831 for (var i = 0; i < 49; ++i) {
michael@0 1832 measureText.appendChild(document.createTextNode("x"));
michael@0 1833 measureText.appendChild(elt("br"));
michael@0 1834 }
michael@0 1835 measureText.appendChild(document.createTextNode("x"));
michael@0 1836 }
michael@0 1837 removeChildrenAndAdd(display.measure, measureText);
michael@0 1838 var height = measureText.offsetHeight / 50;
michael@0 1839 if (height > 3) display.cachedTextHeight = height;
michael@0 1840 removeChildren(display.measure);
michael@0 1841 return height || 1;
michael@0 1842 }
michael@0 1843
michael@0 1844 // Compute the default character width.
michael@0 1845 function charWidth(display) {
michael@0 1846 if (display.cachedCharWidth != null) return display.cachedCharWidth;
michael@0 1847 var anchor = elt("span", "xxxxxxxxxx");
michael@0 1848 var pre = elt("pre", [anchor]);
michael@0 1849 removeChildrenAndAdd(display.measure, pre);
michael@0 1850 var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
michael@0 1851 if (width > 2) display.cachedCharWidth = width;
michael@0 1852 return width || 10;
michael@0 1853 }
michael@0 1854
michael@0 1855 // OPERATIONS
michael@0 1856
michael@0 1857 // Operations are used to wrap a series of changes to the editor
michael@0 1858 // state in such a way that each change won't have to update the
michael@0 1859 // cursor and display (which would be awkward, slow, and
michael@0 1860 // error-prone). Instead, display updates are batched and then all
michael@0 1861 // combined and executed at once.
michael@0 1862
michael@0 1863 var nextOpId = 0;
michael@0 1864 // Start a new operation.
michael@0 1865 function startOperation(cm) {
michael@0 1866 cm.curOp = {
michael@0 1867 viewChanged: false, // Flag that indicates that lines might need to be redrawn
michael@0 1868 startHeight: cm.doc.height, // Used to detect need to update scrollbar
michael@0 1869 forceUpdate: false, // Used to force a redraw
michael@0 1870 updateInput: null, // Whether to reset the input textarea
michael@0 1871 typing: false, // Whether this reset should be careful to leave existing text (for compositing)
michael@0 1872 changeObjs: null, // Accumulated changes, for firing change events
michael@0 1873 cursorActivity: false, // Whether to fire a cursorActivity event
michael@0 1874 selectionChanged: false, // Whether the selection needs to be redrawn
michael@0 1875 updateMaxLine: false, // Set when the widest line needs to be determined anew
michael@0 1876 scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
michael@0 1877 scrollToPos: null, // Used to scroll to a specific position
michael@0 1878 id: ++nextOpId // Unique ID
michael@0 1879 };
michael@0 1880 if (!delayedCallbackDepth++) delayedCallbacks = [];
michael@0 1881 }
michael@0 1882
michael@0 1883 // Finish an operation, updating the display and signalling delayed events
michael@0 1884 function endOperation(cm) {
michael@0 1885 var op = cm.curOp, doc = cm.doc, display = cm.display;
michael@0 1886 cm.curOp = null;
michael@0 1887
michael@0 1888 if (op.updateMaxLine) findMaxLine(cm);
michael@0 1889
michael@0 1890 // If it looks like an update might be needed, call updateDisplay
michael@0 1891 if (op.viewChanged || op.forceUpdate || op.scrollTop != null ||
michael@0 1892 op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
michael@0 1893 op.scrollToPos.to.line >= display.viewTo) ||
michael@0 1894 display.maxLineChanged && cm.options.lineWrapping) {
michael@0 1895 var updated = updateDisplay(cm, {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
michael@0 1896 if (cm.display.scroller.offsetHeight) cm.doc.scrollTop = cm.display.scroller.scrollTop;
michael@0 1897 }
michael@0 1898 // If no update was run, but the selection changed, redraw that.
michael@0 1899 if (!updated && op.selectionChanged) updateSelection(cm);
michael@0 1900 if (!updated && op.startHeight != cm.doc.height) updateScrollbars(cm);
michael@0 1901
michael@0 1902 // Propagate the scroll position to the actual DOM scroller
michael@0 1903 if (op.scrollTop != null && display.scroller.scrollTop != op.scrollTop) {
michael@0 1904 var top = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
michael@0 1905 display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = top;
michael@0 1906 }
michael@0 1907 if (op.scrollLeft != null && display.scroller.scrollLeft != op.scrollLeft) {
michael@0 1908 var left = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft));
michael@0 1909 display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = left;
michael@0 1910 alignHorizontally(cm);
michael@0 1911 }
michael@0 1912 // If we need to scroll a specific position into view, do so.
michael@0 1913 if (op.scrollToPos) {
michael@0 1914 var coords = scrollPosIntoView(cm, clipPos(cm.doc, op.scrollToPos.from),
michael@0 1915 clipPos(cm.doc, op.scrollToPos.to), op.scrollToPos.margin);
michael@0 1916 if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
michael@0 1917 }
michael@0 1918
michael@0 1919 if (op.selectionChanged) restartBlink(cm);
michael@0 1920
michael@0 1921 if (cm.state.focused && op.updateInput)
michael@0 1922 resetInput(cm, op.typing);
michael@0 1923
michael@0 1924 // Fire events for markers that are hidden/unidden by editing or
michael@0 1925 // undoing
michael@0 1926 var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
michael@0 1927 if (hidden) for (var i = 0; i < hidden.length; ++i)
michael@0 1928 if (!hidden[i].lines.length) signal(hidden[i], "hide");
michael@0 1929 if (unhidden) for (var i = 0; i < unhidden.length; ++i)
michael@0 1930 if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
michael@0 1931
michael@0 1932 var delayed;
michael@0 1933 if (!--delayedCallbackDepth) {
michael@0 1934 delayed = delayedCallbacks;
michael@0 1935 delayedCallbacks = null;
michael@0 1936 }
michael@0 1937 // Fire change events, and delayed event handlers
michael@0 1938 if (op.changeObjs) {
michael@0 1939 for (var i = 0; i < op.changeObjs.length; i++)
michael@0 1940 signal(cm, "change", cm, op.changeObjs[i]);
michael@0 1941 signal(cm, "changes", cm, op.changeObjs);
michael@0 1942 }
michael@0 1943 if (op.cursorActivity) signal(cm, "cursorActivity", cm);
michael@0 1944 if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i]();
michael@0 1945 }
michael@0 1946
michael@0 1947 // Run the given function in an operation
michael@0 1948 function runInOp(cm, f) {
michael@0 1949 if (cm.curOp) return f();
michael@0 1950 startOperation(cm);
michael@0 1951 try { return f(); }
michael@0 1952 finally { endOperation(cm); }
michael@0 1953 }
michael@0 1954 // Wraps a function in an operation. Returns the wrapped function.
michael@0 1955 function operation(cm, f) {
michael@0 1956 return function() {
michael@0 1957 if (cm.curOp) return f.apply(cm, arguments);
michael@0 1958 startOperation(cm);
michael@0 1959 try { return f.apply(cm, arguments); }
michael@0 1960 finally { endOperation(cm); }
michael@0 1961 };
michael@0 1962 }
michael@0 1963 // Used to add methods to editor and doc instances, wrapping them in
michael@0 1964 // operations.
michael@0 1965 function methodOp(f) {
michael@0 1966 return function() {
michael@0 1967 if (this.curOp) return f.apply(this, arguments);
michael@0 1968 startOperation(this);
michael@0 1969 try { return f.apply(this, arguments); }
michael@0 1970 finally { endOperation(this); }
michael@0 1971 };
michael@0 1972 }
michael@0 1973 function docMethodOp(f) {
michael@0 1974 return function() {
michael@0 1975 var cm = this.cm;
michael@0 1976 if (!cm || cm.curOp) return f.apply(this, arguments);
michael@0 1977 startOperation(cm);
michael@0 1978 try { return f.apply(this, arguments); }
michael@0 1979 finally { endOperation(cm); }
michael@0 1980 };
michael@0 1981 }
michael@0 1982
michael@0 1983 // VIEW TRACKING
michael@0 1984
michael@0 1985 // These objects are used to represent the visible (currently drawn)
michael@0 1986 // part of the document. A LineView may correspond to multiple
michael@0 1987 // logical lines, if those are connected by collapsed ranges.
michael@0 1988 function LineView(doc, line, lineN) {
michael@0 1989 // The starting line
michael@0 1990 this.line = line;
michael@0 1991 // Continuing lines, if any
michael@0 1992 this.rest = visualLineContinued(line);
michael@0 1993 // Number of logical lines in this visual line
michael@0 1994 this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
michael@0 1995 this.node = this.text = null;
michael@0 1996 this.hidden = lineIsHidden(doc, line);
michael@0 1997 }
michael@0 1998
michael@0 1999 // Create a range of LineView objects for the given lines.
michael@0 2000 function buildViewArray(cm, from, to) {
michael@0 2001 var array = [], nextPos;
michael@0 2002 for (var pos = from; pos < to; pos = nextPos) {
michael@0 2003 var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
michael@0 2004 nextPos = pos + view.size;
michael@0 2005 array.push(view);
michael@0 2006 }
michael@0 2007 return array;
michael@0 2008 }
michael@0 2009
michael@0 2010 // Updates the display.view data structure for a given change to the
michael@0 2011 // document. From and to are in pre-change coordinates. Lendiff is
michael@0 2012 // the amount of lines added or subtracted by the change. This is
michael@0 2013 // used for changes that span multiple lines, or change the way
michael@0 2014 // lines are divided into visual lines. regLineChange (below)
michael@0 2015 // registers single-line changes.
michael@0 2016 function regChange(cm, from, to, lendiff) {
michael@0 2017 if (from == null) from = cm.doc.first;
michael@0 2018 if (to == null) to = cm.doc.first + cm.doc.size;
michael@0 2019 if (!lendiff) lendiff = 0;
michael@0 2020
michael@0 2021 var display = cm.display;
michael@0 2022 if (lendiff && to < display.viewTo &&
michael@0 2023 (display.updateLineNumbers == null || display.updateLineNumbers > from))
michael@0 2024 display.updateLineNumbers = from;
michael@0 2025
michael@0 2026 cm.curOp.viewChanged = true;
michael@0 2027
michael@0 2028 if (from >= display.viewTo) { // Change after
michael@0 2029 if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
michael@0 2030 resetView(cm);
michael@0 2031 } else if (to <= display.viewFrom) { // Change before
michael@0 2032 if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
michael@0 2033 resetView(cm);
michael@0 2034 } else {
michael@0 2035 display.viewFrom += lendiff;
michael@0 2036 display.viewTo += lendiff;
michael@0 2037 }
michael@0 2038 } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
michael@0 2039 resetView(cm);
michael@0 2040 } else if (from <= display.viewFrom) { // Top overlap
michael@0 2041 var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
michael@0 2042 if (cut) {
michael@0 2043 display.view = display.view.slice(cut.index);
michael@0 2044 display.viewFrom = cut.lineN;
michael@0 2045 display.viewTo += lendiff;
michael@0 2046 } else {
michael@0 2047 resetView(cm);
michael@0 2048 }
michael@0 2049 } else if (to >= display.viewTo) { // Bottom overlap
michael@0 2050 var cut = viewCuttingPoint(cm, from, from, -1);
michael@0 2051 if (cut) {
michael@0 2052 display.view = display.view.slice(0, cut.index);
michael@0 2053 display.viewTo = cut.lineN;
michael@0 2054 } else {
michael@0 2055 resetView(cm);
michael@0 2056 }
michael@0 2057 } else { // Gap in the middle
michael@0 2058 var cutTop = viewCuttingPoint(cm, from, from, -1);
michael@0 2059 var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
michael@0 2060 if (cutTop && cutBot) {
michael@0 2061 display.view = display.view.slice(0, cutTop.index)
michael@0 2062 .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
michael@0 2063 .concat(display.view.slice(cutBot.index));
michael@0 2064 display.viewTo += lendiff;
michael@0 2065 } else {
michael@0 2066 resetView(cm);
michael@0 2067 }
michael@0 2068 }
michael@0 2069
michael@0 2070 var ext = display.externalMeasured;
michael@0 2071 if (ext) {
michael@0 2072 if (to < ext.lineN)
michael@0 2073 ext.lineN += lendiff;
michael@0 2074 else if (from < ext.lineN + ext.size)
michael@0 2075 display.externalMeasured = null;
michael@0 2076 }
michael@0 2077 }
michael@0 2078
michael@0 2079 // Register a change to a single line. Type must be one of "text",
michael@0 2080 // "gutter", "class", "widget"
michael@0 2081 function regLineChange(cm, line, type) {
michael@0 2082 cm.curOp.viewChanged = true;
michael@0 2083 var display = cm.display, ext = cm.display.externalMeasured;
michael@0 2084 if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
michael@0 2085 display.externalMeasured = null;
michael@0 2086
michael@0 2087 if (line < display.viewFrom || line >= display.viewTo) return;
michael@0 2088 var lineView = display.view[findViewIndex(cm, line)];
michael@0 2089 if (lineView.node == null) return;
michael@0 2090 var arr = lineView.changes || (lineView.changes = []);
michael@0 2091 if (indexOf(arr, type) == -1) arr.push(type);
michael@0 2092 }
michael@0 2093
michael@0 2094 // Clear the view.
michael@0 2095 function resetView(cm) {
michael@0 2096 cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
michael@0 2097 cm.display.view = [];
michael@0 2098 cm.display.viewOffset = 0;
michael@0 2099 }
michael@0 2100
michael@0 2101 // Find the view element corresponding to a given line. Return null
michael@0 2102 // when the line isn't visible.
michael@0 2103 function findViewIndex(cm, n) {
michael@0 2104 if (n >= cm.display.viewTo) return null;
michael@0 2105 n -= cm.display.viewFrom;
michael@0 2106 if (n < 0) return null;
michael@0 2107 var view = cm.display.view;
michael@0 2108 for (var i = 0; i < view.length; i++) {
michael@0 2109 n -= view[i].size;
michael@0 2110 if (n < 0) return i;
michael@0 2111 }
michael@0 2112 }
michael@0 2113
michael@0 2114 function viewCuttingPoint(cm, oldN, newN, dir) {
michael@0 2115 var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
michael@0 2116 if (!sawCollapsedSpans) return {index: index, lineN: newN};
michael@0 2117 for (var i = 0, n = cm.display.viewFrom; i < index; i++)
michael@0 2118 n += view[i].size;
michael@0 2119 if (n != oldN) {
michael@0 2120 if (dir > 0) {
michael@0 2121 if (index == view.length - 1) return null;
michael@0 2122 diff = (n + view[index].size) - oldN;
michael@0 2123 index++;
michael@0 2124 } else {
michael@0 2125 diff = n - oldN;
michael@0 2126 }
michael@0 2127 oldN += diff; newN += diff;
michael@0 2128 }
michael@0 2129 while (visualLineNo(cm.doc, newN) != newN) {
michael@0 2130 if (index == (dir < 0 ? 0 : view.length - 1)) return null;
michael@0 2131 newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
michael@0 2132 index += dir;
michael@0 2133 }
michael@0 2134 return {index: index, lineN: newN};
michael@0 2135 }
michael@0 2136
michael@0 2137 // Force the view to cover a given range, adding empty view element
michael@0 2138 // or clipping off existing ones as needed.
michael@0 2139 function adjustView(cm, from, to) {
michael@0 2140 var display = cm.display, view = display.view;
michael@0 2141 if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
michael@0 2142 display.view = buildViewArray(cm, from, to);
michael@0 2143 display.viewFrom = from;
michael@0 2144 } else {
michael@0 2145 if (display.viewFrom > from)
michael@0 2146 display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
michael@0 2147 else if (display.viewFrom < from)
michael@0 2148 display.view = display.view.slice(findViewIndex(cm, from));
michael@0 2149 display.viewFrom = from;
michael@0 2150 if (display.viewTo < to)
michael@0 2151 display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
michael@0 2152 else if (display.viewTo > to)
michael@0 2153 display.view = display.view.slice(0, findViewIndex(cm, to));
michael@0 2154 }
michael@0 2155 display.viewTo = to;
michael@0 2156 }
michael@0 2157
michael@0 2158 // Count the number of lines in the view whose DOM representation is
michael@0 2159 // out of date (or nonexistent).
michael@0 2160 function countDirtyView(cm) {
michael@0 2161 var view = cm.display.view, dirty = 0;
michael@0 2162 for (var i = 0; i < view.length; i++) {
michael@0 2163 var lineView = view[i];
michael@0 2164 if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
michael@0 2165 }
michael@0 2166 return dirty;
michael@0 2167 }
michael@0 2168
michael@0 2169 // INPUT HANDLING
michael@0 2170
michael@0 2171 // Poll for input changes, using the normal rate of polling. This
michael@0 2172 // runs as long as the editor is focused.
michael@0 2173 function slowPoll(cm) {
michael@0 2174 if (cm.display.pollingFast) return;
michael@0 2175 cm.display.poll.set(cm.options.pollInterval, function() {
michael@0 2176 readInput(cm);
michael@0 2177 if (cm.state.focused) slowPoll(cm);
michael@0 2178 });
michael@0 2179 }
michael@0 2180
michael@0 2181 // When an event has just come in that is likely to add or change
michael@0 2182 // something in the input textarea, we poll faster, to ensure that
michael@0 2183 // the change appears on the screen quickly.
michael@0 2184 function fastPoll(cm) {
michael@0 2185 var missed = false;
michael@0 2186 cm.display.pollingFast = true;
michael@0 2187 function p() {
michael@0 2188 var changed = readInput(cm);
michael@0 2189 if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);}
michael@0 2190 else {cm.display.pollingFast = false; slowPoll(cm);}
michael@0 2191 }
michael@0 2192 cm.display.poll.set(20, p);
michael@0 2193 }
michael@0 2194
michael@0 2195 // Read input from the textarea, and update the document to match.
michael@0 2196 // When something is selected, it is present in the textarea, and
michael@0 2197 // selected (unless it is huge, in which case a placeholder is
michael@0 2198 // used). When nothing is selected, the cursor sits after previously
michael@0 2199 // seen text (can be empty), which is stored in prevInput (we must
michael@0 2200 // not reset the textarea when typing, because that breaks IME).
michael@0 2201 function readInput(cm) {
michael@0 2202 var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc;
michael@0 2203 // Since this is called a *lot*, try to bail out as cheaply as
michael@0 2204 // possible when it is clear that nothing happened. hasSelection
michael@0 2205 // will be the case when there is a lot of text in the textarea,
michael@0 2206 // in which case reading its value would be expensive.
michael@0 2207 if (!cm.state.focused || hasSelection(input) || isReadOnly(cm) || cm.options.disableInput) return false;
michael@0 2208 var text = input.value;
michael@0 2209 // If nothing changed, bail.
michael@0 2210 if (text == prevInput && !cm.somethingSelected()) return false;
michael@0 2211 // Work around nonsensical selection resetting in IE9/10
michael@0 2212 if (ie && !ie_upto8 && cm.display.inputHasSelection === text) {
michael@0 2213 resetInput(cm);
michael@0 2214 return false;
michael@0 2215 }
michael@0 2216
michael@0 2217 var withOp = !cm.curOp;
michael@0 2218 if (withOp) startOperation(cm);
michael@0 2219 cm.display.shift = false;
michael@0 2220
michael@0 2221 // Find the part of the input that is actually new
michael@0 2222 var same = 0, l = Math.min(prevInput.length, text.length);
michael@0 2223 while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
michael@0 2224 var inserted = text.slice(same), textLines = splitLines(inserted);
michael@0 2225
michael@0 2226 // When pasing N lines into N selections, insert one line per selection
michael@0 2227 var multiPaste = cm.state.pasteIncoming && textLines.length > 1 && doc.sel.ranges.length == textLines.length;
michael@0 2228
michael@0 2229 // Normal behavior is to insert the new text into every selection
michael@0 2230 for (var i = doc.sel.ranges.length - 1; i >= 0; i--) {
michael@0 2231 var range = doc.sel.ranges[i];
michael@0 2232 var from = range.from(), to = range.to();
michael@0 2233 // Handle deletion
michael@0 2234 if (same < prevInput.length)
michael@0 2235 from = Pos(from.line, from.ch - (prevInput.length - same));
michael@0 2236 // Handle overwrite
michael@0 2237 else if (cm.state.overwrite && range.empty() && !cm.state.pasteIncoming)
michael@0 2238 to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
michael@0 2239 var updateInput = cm.curOp.updateInput;
michael@0 2240 var changeEvent = {from: from, to: to, text: multiPaste ? [textLines[i]] : textLines,
michael@0 2241 origin: cm.state.pasteIncoming ? "paste" : cm.state.cutIncoming ? "cut" : "+input"};
michael@0 2242 makeChange(cm.doc, changeEvent);
michael@0 2243 signalLater(cm, "inputRead", cm, changeEvent);
michael@0 2244 // When an 'electric' character is inserted, immediately trigger a reindent
michael@0 2245 if (inserted && !cm.state.pasteIncoming && cm.options.electricChars &&
michael@0 2246 cm.options.smartIndent && range.head.ch < 100 &&
michael@0 2247 (!i || doc.sel.ranges[i - 1].head.line != range.head.line)) {
michael@0 2248 var electric = cm.getModeAt(range.head).electricChars;
michael@0 2249 if (electric) for (var j = 0; j < electric.length; j++)
michael@0 2250 if (inserted.indexOf(electric.charAt(j)) > -1) {
michael@0 2251 indentLine(cm, range.head.line, "smart");
michael@0 2252 break;
michael@0 2253 }
michael@0 2254 }
michael@0 2255 }
michael@0 2256 ensureCursorVisible(cm);
michael@0 2257 cm.curOp.updateInput = updateInput;
michael@0 2258 cm.curOp.typing = true;
michael@0 2259
michael@0 2260 // Don't leave long text in the textarea, since it makes further polling slow
michael@0 2261 if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.prevInput = "";
michael@0 2262 else cm.display.prevInput = text;
michael@0 2263 if (withOp) endOperation(cm);
michael@0 2264 cm.state.pasteIncoming = cm.state.cutIncoming = false;
michael@0 2265 return true;
michael@0 2266 }
michael@0 2267
michael@0 2268 // Reset the input to correspond to the selection (or to be empty,
michael@0 2269 // when not typing and nothing is selected)
michael@0 2270 function resetInput(cm, typing) {
michael@0 2271 var minimal, selected, doc = cm.doc;
michael@0 2272 if (cm.somethingSelected()) {
michael@0 2273 cm.display.prevInput = "";
michael@0 2274 var range = doc.sel.primary();
michael@0 2275 minimal = hasCopyEvent &&
michael@0 2276 (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
michael@0 2277 var content = minimal ? "-" : selected || cm.getSelection();
michael@0 2278 cm.display.input.value = content;
michael@0 2279 if (cm.state.focused) selectInput(cm.display.input);
michael@0 2280 if (ie && !ie_upto8) cm.display.inputHasSelection = content;
michael@0 2281 } else if (!typing) {
michael@0 2282 cm.display.prevInput = cm.display.input.value = "";
michael@0 2283 if (ie && !ie_upto8) cm.display.inputHasSelection = null;
michael@0 2284 }
michael@0 2285 cm.display.inaccurateSelection = minimal;
michael@0 2286 }
michael@0 2287
michael@0 2288 function focusInput(cm) {
michael@0 2289 if (cm.options.readOnly != "nocursor" && (!mobile || activeElt() != cm.display.input))
michael@0 2290 cm.display.input.focus();
michael@0 2291 }
michael@0 2292
michael@0 2293 function ensureFocus(cm) {
michael@0 2294 if (!cm.state.focused) { focusInput(cm); onFocus(cm); }
michael@0 2295 }
michael@0 2296
michael@0 2297 function isReadOnly(cm) {
michael@0 2298 return cm.options.readOnly || cm.doc.cantEdit;
michael@0 2299 }
michael@0 2300
michael@0 2301 // EVENT HANDLERS
michael@0 2302
michael@0 2303 // Attach the necessary event handlers when initializing the editor
michael@0 2304 function registerEventHandlers(cm) {
michael@0 2305 var d = cm.display;
michael@0 2306 on(d.scroller, "mousedown", operation(cm, onMouseDown));
michael@0 2307 // Older IE's will not fire a second mousedown for a double click
michael@0 2308 if (ie_upto10)
michael@0 2309 on(d.scroller, "dblclick", operation(cm, function(e) {
michael@0 2310 if (signalDOMEvent(cm, e)) return;
michael@0 2311 var pos = posFromMouse(cm, e);
michael@0 2312 if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
michael@0 2313 e_preventDefault(e);
michael@0 2314 var word = findWordAt(cm.doc, pos);
michael@0 2315 extendSelection(cm.doc, word.anchor, word.head);
michael@0 2316 }));
michael@0 2317 else
michael@0 2318 on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
michael@0 2319 // Prevent normal selection in the editor (we handle our own)
michael@0 2320 on(d.lineSpace, "selectstart", function(e) {
michael@0 2321 if (!eventInWidget(d, e)) e_preventDefault(e);
michael@0 2322 });
michael@0 2323 // Some browsers fire contextmenu *after* opening the menu, at
michael@0 2324 // which point we can't mess with it anymore. Context menu is
michael@0 2325 // handled in onMouseDown for these browsers.
michael@0 2326 if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
michael@0 2327
michael@0 2328 // Sync scrolling between fake scrollbars and real scrollable
michael@0 2329 // area, ensure viewport is updated when scrolling.
michael@0 2330 on(d.scroller, "scroll", function() {
michael@0 2331 if (d.scroller.clientHeight) {
michael@0 2332 setScrollTop(cm, d.scroller.scrollTop);
michael@0 2333 setScrollLeft(cm, d.scroller.scrollLeft, true);
michael@0 2334 signal(cm, "scroll", cm);
michael@0 2335 }
michael@0 2336 });
michael@0 2337 on(d.scrollbarV, "scroll", function() {
michael@0 2338 if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop);
michael@0 2339 });
michael@0 2340 on(d.scrollbarH, "scroll", function() {
michael@0 2341 if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft);
michael@0 2342 });
michael@0 2343
michael@0 2344 // Listen to wheel events in order to try and update the viewport on time.
michael@0 2345 on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
michael@0 2346 on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
michael@0 2347
michael@0 2348 // Prevent clicks in the scrollbars from killing focus
michael@0 2349 function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm), 0); }
michael@0 2350 on(d.scrollbarH, "mousedown", reFocus);
michael@0 2351 on(d.scrollbarV, "mousedown", reFocus);
michael@0 2352 // Prevent wrapper from ever scrolling
michael@0 2353 on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
michael@0 2354
michael@0 2355 // When the window resizes, we need to refresh active editors.
michael@0 2356 var resizeTimer;
michael@0 2357 function onResize() {
michael@0 2358 if (resizeTimer == null) resizeTimer = setTimeout(function() {
michael@0 2359 resizeTimer = null;
michael@0 2360 // Might be a text scaling operation, clear size caches.
michael@0 2361 d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = knownScrollbarWidth = null;
michael@0 2362 cm.setSize();
michael@0 2363 }, 100);
michael@0 2364 }
michael@0 2365 on(window, "resize", onResize);
michael@0 2366 // The above handler holds on to the editor and its data
michael@0 2367 // structures. Here we poll to unregister it when the editor is no
michael@0 2368 // longer in the document, so that it can be garbage-collected.
michael@0 2369 function unregister() {
michael@0 2370 if (contains(document.body, d.wrapper)) setTimeout(unregister, 5000);
michael@0 2371 else off(window, "resize", onResize);
michael@0 2372 }
michael@0 2373 setTimeout(unregister, 5000);
michael@0 2374
michael@0 2375 on(d.input, "keyup", operation(cm, onKeyUp));
michael@0 2376 on(d.input, "input", function() {
michael@0 2377 if (ie && !ie_upto8 && cm.display.inputHasSelection) cm.display.inputHasSelection = null;
michael@0 2378 fastPoll(cm);
michael@0 2379 });
michael@0 2380 on(d.input, "keydown", operation(cm, onKeyDown));
michael@0 2381 on(d.input, "keypress", operation(cm, onKeyPress));
michael@0 2382 on(d.input, "focus", bind(onFocus, cm));
michael@0 2383 on(d.input, "blur", bind(onBlur, cm));
michael@0 2384
michael@0 2385 function drag_(e) {
michael@0 2386 if (!signalDOMEvent(cm, e)) e_stop(e);
michael@0 2387 }
michael@0 2388 if (cm.options.dragDrop) {
michael@0 2389 on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});
michael@0 2390 on(d.scroller, "dragenter", drag_);
michael@0 2391 on(d.scroller, "dragover", drag_);
michael@0 2392 on(d.scroller, "drop", operation(cm, onDrop));
michael@0 2393 }
michael@0 2394 on(d.scroller, "paste", function(e) {
michael@0 2395 if (eventInWidget(d, e)) return;
michael@0 2396 cm.state.pasteIncoming = true;
michael@0 2397 focusInput(cm);
michael@0 2398 fastPoll(cm);
michael@0 2399 });
michael@0 2400 on(d.input, "paste", function() {
michael@0 2401 cm.state.pasteIncoming = true;
michael@0 2402 fastPoll(cm);
michael@0 2403 });
michael@0 2404
michael@0 2405 function prepareCopy(e) {
michael@0 2406 if (d.inaccurateSelection) {
michael@0 2407 d.prevInput = "";
michael@0 2408 d.inaccurateSelection = false;
michael@0 2409 d.input.value = cm.getSelection();
michael@0 2410 selectInput(d.input);
michael@0 2411 }
michael@0 2412 if (e.type == "cut") cm.state.cutIncoming = true;
michael@0 2413 }
michael@0 2414 on(d.input, "cut", prepareCopy);
michael@0 2415 on(d.input, "copy", prepareCopy);
michael@0 2416
michael@0 2417 // Needed to handle Tab key in KHTML
michael@0 2418 if (khtml) on(d.sizer, "mouseup", function() {
michael@0 2419 if (activeElt() == d.input) d.input.blur();
michael@0 2420 focusInput(cm);
michael@0 2421 });
michael@0 2422 }
michael@0 2423
michael@0 2424 // MOUSE EVENTS
michael@0 2425
michael@0 2426 // Return true when the given mouse event happened in a widget
michael@0 2427 function eventInWidget(display, e) {
michael@0 2428 for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
michael@0 2429 if (!n || n.ignoreEvents || n.parentNode == display.sizer && n != display.mover) return true;
michael@0 2430 }
michael@0 2431 }
michael@0 2432
michael@0 2433 // Given a mouse event, find the corresponding position. If liberal
michael@0 2434 // is false, it checks whether a gutter or scrollbar was clicked,
michael@0 2435 // and returns null if it was. forRect is used by rectangular
michael@0 2436 // selections, and tries to estimate a character position even for
michael@0 2437 // coordinates beyond the right of the text.
michael@0 2438 function posFromMouse(cm, e, liberal, forRect) {
michael@0 2439 var display = cm.display;
michael@0 2440 if (!liberal) {
michael@0 2441 var target = e_target(e);
michael@0 2442 if (target == display.scrollbarH || target == display.scrollbarV ||
michael@0 2443 target == display.scrollbarFiller || target == display.gutterFiller) return null;
michael@0 2444 }
michael@0 2445 var x, y, space = display.lineSpace.getBoundingClientRect();
michael@0 2446 // Fails unpredictably on IE[67] when mouse is dragged around quickly.
michael@0 2447 try { x = e.clientX - space.left; y = e.clientY - space.top; }
michael@0 2448 catch (e) { return null; }
michael@0 2449 var coords = coordsChar(cm, x, y), line;
michael@0 2450 if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
michael@0 2451 var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
michael@0 2452 coords = Pos(coords.line, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff);
michael@0 2453 }
michael@0 2454 return coords;
michael@0 2455 }
michael@0 2456
michael@0 2457 // A mouse down can be a single click, double click, triple click,
michael@0 2458 // start of selection drag, start of text drag, new cursor
michael@0 2459 // (ctrl-click), rectangle drag (alt-drag), or xwin
michael@0 2460 // middle-click-paste. Or it might be a click on something we should
michael@0 2461 // not interfere with, such as a scrollbar or widget.
michael@0 2462 function onMouseDown(e) {
michael@0 2463 if (signalDOMEvent(this, e)) return;
michael@0 2464 var cm = this, display = cm.display;
michael@0 2465 display.shift = e.shiftKey;
michael@0 2466
michael@0 2467 if (eventInWidget(display, e)) {
michael@0 2468 if (!webkit) {
michael@0 2469 // Briefly turn off draggability, to allow widgets to do
michael@0 2470 // normal dragging things.
michael@0 2471 display.scroller.draggable = false;
michael@0 2472 setTimeout(function(){display.scroller.draggable = true;}, 100);
michael@0 2473 }
michael@0 2474 return;
michael@0 2475 }
michael@0 2476 if (clickInGutter(cm, e)) return;
michael@0 2477 var start = posFromMouse(cm, e);
michael@0 2478 window.focus();
michael@0 2479
michael@0 2480 switch (e_button(e)) {
michael@0 2481 case 1:
michael@0 2482 if (start)
michael@0 2483 leftButtonDown(cm, e, start);
michael@0 2484 else if (e_target(e) == display.scroller)
michael@0 2485 e_preventDefault(e);
michael@0 2486 break;
michael@0 2487 case 2:
michael@0 2488 if (webkit) cm.state.lastMiddleDown = +new Date;
michael@0 2489 if (start) extendSelection(cm.doc, start);
michael@0 2490 setTimeout(bind(focusInput, cm), 20);
michael@0 2491 e_preventDefault(e);
michael@0 2492 break;
michael@0 2493 case 3:
michael@0 2494 if (captureRightClick) onContextMenu(cm, e);
michael@0 2495 break;
michael@0 2496 }
michael@0 2497 }
michael@0 2498
michael@0 2499 var lastClick, lastDoubleClick;
michael@0 2500 function leftButtonDown(cm, e, start) {
michael@0 2501 setTimeout(bind(ensureFocus, cm), 0);
michael@0 2502
michael@0 2503 var now = +new Date, type;
michael@0 2504 if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
michael@0 2505 type = "triple";
michael@0 2506 } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
michael@0 2507 type = "double";
michael@0 2508 lastDoubleClick = {time: now, pos: start};
michael@0 2509 } else {
michael@0 2510 type = "single";
michael@0 2511 lastClick = {time: now, pos: start};
michael@0 2512 }
michael@0 2513
michael@0 2514 var sel = cm.doc.sel, addNew = mac ? e.metaKey : e.ctrlKey;
michael@0 2515 if (cm.options.dragDrop && dragAndDrop && !addNew && !isReadOnly(cm) &&
michael@0 2516 type == "single" && sel.contains(start) > -1 && sel.somethingSelected())
michael@0 2517 leftButtonStartDrag(cm, e, start);
michael@0 2518 else
michael@0 2519 leftButtonSelect(cm, e, start, type, addNew);
michael@0 2520 }
michael@0 2521
michael@0 2522 // Start a text drag. When it ends, see if any dragging actually
michael@0 2523 // happen, and treat as a click if it didn't.
michael@0 2524 function leftButtonStartDrag(cm, e, start) {
michael@0 2525 var display = cm.display;
michael@0 2526 var dragEnd = operation(cm, function(e2) {
michael@0 2527 if (webkit) display.scroller.draggable = false;
michael@0 2528 cm.state.draggingText = false;
michael@0 2529 off(document, "mouseup", dragEnd);
michael@0 2530 off(display.scroller, "drop", dragEnd);
michael@0 2531 if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
michael@0 2532 e_preventDefault(e2);
michael@0 2533 extendSelection(cm.doc, start);
michael@0 2534 focusInput(cm);
michael@0 2535 // Work around unexplainable focus problem in IE9 (#2127)
michael@0 2536 if (ie_upto10 && !ie_upto8)
michael@0 2537 setTimeout(function() {document.body.focus(); focusInput(cm);}, 20);
michael@0 2538 }
michael@0 2539 });
michael@0 2540 // Let the drag handler handle this.
michael@0 2541 if (webkit) display.scroller.draggable = true;
michael@0 2542 cm.state.draggingText = dragEnd;
michael@0 2543 // IE's approach to draggable
michael@0 2544 if (display.scroller.dragDrop) display.scroller.dragDrop();
michael@0 2545 on(document, "mouseup", dragEnd);
michael@0 2546 on(display.scroller, "drop", dragEnd);
michael@0 2547 }
michael@0 2548
michael@0 2549 // Normal selection, as opposed to text dragging.
michael@0 2550 function leftButtonSelect(cm, e, start, type, addNew) {
michael@0 2551 var display = cm.display, doc = cm.doc;
michael@0 2552 e_preventDefault(e);
michael@0 2553
michael@0 2554 var ourRange, ourIndex, startSel = doc.sel;
michael@0 2555 if (addNew) {
michael@0 2556 ourIndex = doc.sel.contains(start);
michael@0 2557 if (ourIndex > -1)
michael@0 2558 ourRange = doc.sel.ranges[ourIndex];
michael@0 2559 else
michael@0 2560 ourRange = new Range(start, start);
michael@0 2561 } else {
michael@0 2562 ourRange = doc.sel.primary();
michael@0 2563 }
michael@0 2564
michael@0 2565 if (e.altKey) {
michael@0 2566 type = "rect";
michael@0 2567 if (!addNew) ourRange = new Range(start, start);
michael@0 2568 start = posFromMouse(cm, e, true, true);
michael@0 2569 ourIndex = -1;
michael@0 2570 } else if (type == "double") {
michael@0 2571 var word = findWordAt(doc, start);
michael@0 2572 if (cm.display.shift || doc.extend)
michael@0 2573 ourRange = extendRange(doc, ourRange, word.anchor, word.head);
michael@0 2574 else
michael@0 2575 ourRange = word;
michael@0 2576 } else if (type == "triple") {
michael@0 2577 var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
michael@0 2578 if (cm.display.shift || doc.extend)
michael@0 2579 ourRange = extendRange(doc, ourRange, line.anchor, line.head);
michael@0 2580 else
michael@0 2581 ourRange = line;
michael@0 2582 } else {
michael@0 2583 ourRange = extendRange(doc, ourRange, start);
michael@0 2584 }
michael@0 2585
michael@0 2586 if (!addNew) {
michael@0 2587 ourIndex = 0;
michael@0 2588 setSelection(doc, new Selection([ourRange], 0), sel_mouse);
michael@0 2589 } else if (ourIndex > -1) {
michael@0 2590 replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
michael@0 2591 } else {
michael@0 2592 ourIndex = doc.sel.ranges.length;
michael@0 2593 setSelection(doc, normalizeSelection(doc.sel.ranges.concat([ourRange]), ourIndex),
michael@0 2594 {scroll: false, origin: "*mouse"});
michael@0 2595 }
michael@0 2596
michael@0 2597 var lastPos = start;
michael@0 2598 function extendTo(pos) {
michael@0 2599 if (cmp(lastPos, pos) == 0) return;
michael@0 2600 lastPos = pos;
michael@0 2601
michael@0 2602 if (type == "rect") {
michael@0 2603 var ranges = [], tabSize = cm.options.tabSize;
michael@0 2604 var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
michael@0 2605 var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
michael@0 2606 var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
michael@0 2607 for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
michael@0 2608 line <= end; line++) {
michael@0 2609 var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
michael@0 2610 if (left == right)
michael@0 2611 ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
michael@0 2612 else if (text.length > leftPos)
michael@0 2613 ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
michael@0 2614 }
michael@0 2615 if (!ranges.length) ranges.push(new Range(start, start));
michael@0 2616 setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), sel_mouse);
michael@0 2617 } else {
michael@0 2618 var oldRange = ourRange;
michael@0 2619 var anchor = oldRange.anchor, head = pos;
michael@0 2620 if (type != "single") {
michael@0 2621 if (type == "double")
michael@0 2622 var range = findWordAt(doc, pos);
michael@0 2623 else
michael@0 2624 var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
michael@0 2625 if (cmp(range.anchor, anchor) > 0) {
michael@0 2626 head = range.head;
michael@0 2627 anchor = minPos(oldRange.from(), range.anchor);
michael@0 2628 } else {
michael@0 2629 head = range.anchor;
michael@0 2630 anchor = maxPos(oldRange.to(), range.head);
michael@0 2631 }
michael@0 2632 }
michael@0 2633 var ranges = startSel.ranges.slice(0);
michael@0 2634 ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
michael@0 2635 setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
michael@0 2636 }
michael@0 2637 }
michael@0 2638
michael@0 2639 var editorSize = display.wrapper.getBoundingClientRect();
michael@0 2640 // Used to ensure timeout re-tries don't fire when another extend
michael@0 2641 // happened in the meantime (clearTimeout isn't reliable -- at
michael@0 2642 // least on Chrome, the timeouts still happen even when cleared,
michael@0 2643 // if the clear happens after their scheduled firing time).
michael@0 2644 var counter = 0;
michael@0 2645
michael@0 2646 function extend(e) {
michael@0 2647 var curCount = ++counter;
michael@0 2648 var cur = posFromMouse(cm, e, true, type == "rect");
michael@0 2649 if (!cur) return;
michael@0 2650 if (cmp(cur, lastPos) != 0) {
michael@0 2651 ensureFocus(cm);
michael@0 2652 extendTo(cur);
michael@0 2653 var visible = visibleLines(display, doc);
michael@0 2654 if (cur.line >= visible.to || cur.line < visible.from)
michael@0 2655 setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
michael@0 2656 } else {
michael@0 2657 var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
michael@0 2658 if (outside) setTimeout(operation(cm, function() {
michael@0 2659 if (counter != curCount) return;
michael@0 2660 display.scroller.scrollTop += outside;
michael@0 2661 extend(e);
michael@0 2662 }), 50);
michael@0 2663 }
michael@0 2664 }
michael@0 2665
michael@0 2666 function done(e) {
michael@0 2667 counter = Infinity;
michael@0 2668 e_preventDefault(e);
michael@0 2669 focusInput(cm);
michael@0 2670 off(document, "mousemove", move);
michael@0 2671 off(document, "mouseup", up);
michael@0 2672 doc.history.lastSelOrigin = null;
michael@0 2673 }
michael@0 2674
michael@0 2675 var move = operation(cm, function(e) {
michael@0 2676 if ((ie && !ie_upto9) ? !e.buttons : !e_button(e)) done(e);
michael@0 2677 else extend(e);
michael@0 2678 });
michael@0 2679 var up = operation(cm, done);
michael@0 2680 on(document, "mousemove", move);
michael@0 2681 on(document, "mouseup", up);
michael@0 2682 }
michael@0 2683
michael@0 2684 // Determines whether an event happened in the gutter, and fires the
michael@0 2685 // handlers for the corresponding event.
michael@0 2686 function gutterEvent(cm, e, type, prevent, signalfn) {
michael@0 2687 try { var mX = e.clientX, mY = e.clientY; }
michael@0 2688 catch(e) { return false; }
michael@0 2689 if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
michael@0 2690 if (prevent) e_preventDefault(e);
michael@0 2691
michael@0 2692 var display = cm.display;
michael@0 2693 var lineBox = display.lineDiv.getBoundingClientRect();
michael@0 2694
michael@0 2695 if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
michael@0 2696 mY -= lineBox.top - display.viewOffset;
michael@0 2697
michael@0 2698 for (var i = 0; i < cm.options.gutters.length; ++i) {
michael@0 2699 var g = display.gutters.childNodes[i];
michael@0 2700 if (g && g.getBoundingClientRect().right >= mX) {
michael@0 2701 var line = lineAtHeight(cm.doc, mY);
michael@0 2702 var gutter = cm.options.gutters[i];
michael@0 2703 signalfn(cm, type, cm, line, gutter, e);
michael@0 2704 return e_defaultPrevented(e);
michael@0 2705 }
michael@0 2706 }
michael@0 2707 }
michael@0 2708
michael@0 2709 function clickInGutter(cm, e) {
michael@0 2710 return gutterEvent(cm, e, "gutterClick", true, signalLater);
michael@0 2711 }
michael@0 2712
michael@0 2713 // Kludge to work around strange IE behavior where it'll sometimes
michael@0 2714 // re-fire a series of drag-related events right after the drop (#1551)
michael@0 2715 var lastDrop = 0;
michael@0 2716
michael@0 2717 function onDrop(e) {
michael@0 2718 var cm = this;
michael@0 2719 if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
michael@0 2720 return;
michael@0 2721 e_preventDefault(e);
michael@0 2722 if (ie_upto10) lastDrop = +new Date;
michael@0 2723 var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
michael@0 2724 if (!pos || isReadOnly(cm)) return;
michael@0 2725 // Might be a file drop, in which case we simply extract the text
michael@0 2726 // and insert it.
michael@0 2727 if (files && files.length && window.FileReader && window.File) {
michael@0 2728 var n = files.length, text = Array(n), read = 0;
michael@0 2729 var loadFile = function(file, i) {
michael@0 2730 var reader = new FileReader;
michael@0 2731 reader.onload = function() {
michael@0 2732 text[i] = reader.result;
michael@0 2733 if (++read == n) {
michael@0 2734 pos = clipPos(cm.doc, pos);
michael@0 2735 var change = {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"};
michael@0 2736 makeChange(cm.doc, change);
michael@0 2737 setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
michael@0 2738 }
michael@0 2739 };
michael@0 2740 reader.readAsText(file);
michael@0 2741 };
michael@0 2742 for (var i = 0; i < n; ++i) loadFile(files[i], i);
michael@0 2743 } else { // Normal drop
michael@0 2744 // Don't do a replace if the drop happened inside of the selected text.
michael@0 2745 if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
michael@0 2746 cm.state.draggingText(e);
michael@0 2747 // Ensure the editor is re-focused
michael@0 2748 setTimeout(bind(focusInput, cm), 20);
michael@0 2749 return;
michael@0 2750 }
michael@0 2751 try {
michael@0 2752 var text = e.dataTransfer.getData("Text");
michael@0 2753 if (text) {
michael@0 2754 var selected = cm.state.draggingText && cm.listSelections();
michael@0 2755 setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
michael@0 2756 if (selected) for (var i = 0; i < selected.length; ++i)
michael@0 2757 replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
michael@0 2758 cm.replaceSelection(text, "around", "paste");
michael@0 2759 focusInput(cm);
michael@0 2760 }
michael@0 2761 }
michael@0 2762 catch(e){}
michael@0 2763 }
michael@0 2764 }
michael@0 2765
michael@0 2766 function onDragStart(cm, e) {
michael@0 2767 if (ie_upto10 && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
michael@0 2768 if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
michael@0 2769
michael@0 2770 e.dataTransfer.setData("Text", cm.getSelection());
michael@0 2771
michael@0 2772 // Use dummy image instead of default browsers image.
michael@0 2773 // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
michael@0 2774 if (e.dataTransfer.setDragImage && !safari) {
michael@0 2775 var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
michael@0 2776 img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
michael@0 2777 if (presto) {
michael@0 2778 img.width = img.height = 1;
michael@0 2779 cm.display.wrapper.appendChild(img);
michael@0 2780 // Force a relayout, or Opera won't use our image for some obscure reason
michael@0 2781 img._top = img.offsetTop;
michael@0 2782 }
michael@0 2783 e.dataTransfer.setDragImage(img, 0, 0);
michael@0 2784 if (presto) img.parentNode.removeChild(img);
michael@0 2785 }
michael@0 2786 }
michael@0 2787
michael@0 2788 // SCROLL EVENTS
michael@0 2789
michael@0 2790 // Sync the scrollable area and scrollbars, ensure the viewport
michael@0 2791 // covers the visible area.
michael@0 2792 function setScrollTop(cm, val) {
michael@0 2793 if (Math.abs(cm.doc.scrollTop - val) < 2) return;
michael@0 2794 cm.doc.scrollTop = val;
michael@0 2795 if (!gecko) updateDisplay(cm, {top: val});
michael@0 2796 if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
michael@0 2797 if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val;
michael@0 2798 if (gecko) updateDisplay(cm);
michael@0 2799 startWorker(cm, 100);
michael@0 2800 }
michael@0 2801 // Sync scroller and scrollbar, ensure the gutter elements are
michael@0 2802 // aligned.
michael@0 2803 function setScrollLeft(cm, val, isScroller) {
michael@0 2804 if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
michael@0 2805 val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
michael@0 2806 cm.doc.scrollLeft = val;
michael@0 2807 alignHorizontally(cm);
michael@0 2808 if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
michael@0 2809 if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val;
michael@0 2810 }
michael@0 2811
michael@0 2812 // Since the delta values reported on mouse wheel events are
michael@0 2813 // unstandardized between browsers and even browser versions, and
michael@0 2814 // generally horribly unpredictable, this code starts by measuring
michael@0 2815 // the scroll effect that the first few mouse wheel events have,
michael@0 2816 // and, from that, detects the way it can convert deltas to pixel
michael@0 2817 // offsets afterwards.
michael@0 2818 //
michael@0 2819 // The reason we want to know the amount a wheel event will scroll
michael@0 2820 // is that it gives us a chance to update the display before the
michael@0 2821 // actual scrolling happens, reducing flickering.
michael@0 2822
michael@0 2823 var wheelSamples = 0, wheelPixelsPerUnit = null;
michael@0 2824 // Fill in a browser-detected starting value on browsers where we
michael@0 2825 // know one. These don't have to be accurate -- the result of them
michael@0 2826 // being wrong would just be a slight flicker on the first wheel
michael@0 2827 // scroll (if it is large enough).
michael@0 2828 if (ie) wheelPixelsPerUnit = -.53;
michael@0 2829 else if (gecko) wheelPixelsPerUnit = 15;
michael@0 2830 else if (chrome) wheelPixelsPerUnit = -.7;
michael@0 2831 else if (safari) wheelPixelsPerUnit = -1/3;
michael@0 2832
michael@0 2833 function onScrollWheel(cm, e) {
michael@0 2834 var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
michael@0 2835 if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
michael@0 2836 if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
michael@0 2837 else if (dy == null) dy = e.wheelDelta;
michael@0 2838
michael@0 2839 var display = cm.display, scroll = display.scroller;
michael@0 2840 // Quit if there's nothing to scroll here
michael@0 2841 if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
michael@0 2842 dy && scroll.scrollHeight > scroll.clientHeight)) return;
michael@0 2843
michael@0 2844 // Webkit browsers on OS X abort momentum scrolls when the target
michael@0 2845 // of the scroll event is removed from the scrollable element.
michael@0 2846 // This hack (see related code in patchDisplay) makes sure the
michael@0 2847 // element is kept around.
michael@0 2848 if (dy && mac && webkit) {
michael@0 2849 outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
michael@0 2850 for (var i = 0; i < view.length; i++) {
michael@0 2851 if (view[i].node == cur) {
michael@0 2852 cm.display.currentWheelTarget = cur;
michael@0 2853 break outer;
michael@0 2854 }
michael@0 2855 }
michael@0 2856 }
michael@0 2857 }
michael@0 2858
michael@0 2859 // On some browsers, horizontal scrolling will cause redraws to
michael@0 2860 // happen before the gutter has been realigned, causing it to
michael@0 2861 // wriggle around in a most unseemly way. When we have an
michael@0 2862 // estimated pixels/delta value, we just handle horizontal
michael@0 2863 // scrolling entirely here. It'll be slightly off from native, but
michael@0 2864 // better than glitching out.
michael@0 2865 if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
michael@0 2866 if (dy)
michael@0 2867 setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
michael@0 2868 setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
michael@0 2869 e_preventDefault(e);
michael@0 2870 display.wheelStartX = null; // Abort measurement, if in progress
michael@0 2871 return;
michael@0 2872 }
michael@0 2873
michael@0 2874 // 'Project' the visible viewport to cover the area that is being
michael@0 2875 // scrolled into view (if we know enough to estimate it).
michael@0 2876 if (dy && wheelPixelsPerUnit != null) {
michael@0 2877 var pixels = dy * wheelPixelsPerUnit;
michael@0 2878 var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
michael@0 2879 if (pixels < 0) top = Math.max(0, top + pixels - 50);
michael@0 2880 else bot = Math.min(cm.doc.height, bot + pixels + 50);
michael@0 2881 updateDisplay(cm, {top: top, bottom: bot});
michael@0 2882 }
michael@0 2883
michael@0 2884 if (wheelSamples < 20) {
michael@0 2885 if (display.wheelStartX == null) {
michael@0 2886 display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
michael@0 2887 display.wheelDX = dx; display.wheelDY = dy;
michael@0 2888 setTimeout(function() {
michael@0 2889 if (display.wheelStartX == null) return;
michael@0 2890 var movedX = scroll.scrollLeft - display.wheelStartX;
michael@0 2891 var movedY = scroll.scrollTop - display.wheelStartY;
michael@0 2892 var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
michael@0 2893 (movedX && display.wheelDX && movedX / display.wheelDX);
michael@0 2894 display.wheelStartX = display.wheelStartY = null;
michael@0 2895 if (!sample) return;
michael@0 2896 wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
michael@0 2897 ++wheelSamples;
michael@0 2898 }, 200);
michael@0 2899 } else {
michael@0 2900 display.wheelDX += dx; display.wheelDY += dy;
michael@0 2901 }
michael@0 2902 }
michael@0 2903 }
michael@0 2904
michael@0 2905 // KEY EVENTS
michael@0 2906
michael@0 2907 // Run a handler that was bound to a key.
michael@0 2908 function doHandleBinding(cm, bound, dropShift) {
michael@0 2909 if (typeof bound == "string") {
michael@0 2910 bound = commands[bound];
michael@0 2911 if (!bound) return false;
michael@0 2912 }
michael@0 2913 // Ensure previous input has been read, so that the handler sees a
michael@0 2914 // consistent view of the document
michael@0 2915 if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false;
michael@0 2916 var prevShift = cm.display.shift, done = false;
michael@0 2917 try {
michael@0 2918 if (isReadOnly(cm)) cm.state.suppressEdits = true;
michael@0 2919 if (dropShift) cm.display.shift = false;
michael@0 2920 done = bound(cm) != Pass;
michael@0 2921 } finally {
michael@0 2922 cm.display.shift = prevShift;
michael@0 2923 cm.state.suppressEdits = false;
michael@0 2924 }
michael@0 2925 return done;
michael@0 2926 }
michael@0 2927
michael@0 2928 // Collect the currently active keymaps.
michael@0 2929 function allKeyMaps(cm) {
michael@0 2930 var maps = cm.state.keyMaps.slice(0);
michael@0 2931 if (cm.options.extraKeys) maps.push(cm.options.extraKeys);
michael@0 2932 maps.push(cm.options.keyMap);
michael@0 2933 return maps;
michael@0 2934 }
michael@0 2935
michael@0 2936 var maybeTransition;
michael@0 2937 // Handle a key from the keydown event.
michael@0 2938 function handleKeyBinding(cm, e) {
michael@0 2939 // Handle automatic keymap transitions
michael@0 2940 var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto;
michael@0 2941 clearTimeout(maybeTransition);
michael@0 2942 if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
michael@0 2943 if (getKeyMap(cm.options.keyMap) == startMap) {
michael@0 2944 cm.options.keyMap = (next.call ? next.call(null, cm) : next);
michael@0 2945 keyMapChanged(cm);
michael@0 2946 }
michael@0 2947 }, 50);
michael@0 2948
michael@0 2949 var name = keyName(e, true), handled = false;
michael@0 2950 if (!name) return false;
michael@0 2951 var keymaps = allKeyMaps(cm);
michael@0 2952
michael@0 2953 if (e.shiftKey) {
michael@0 2954 // First try to resolve full name (including 'Shift-'). Failing
michael@0 2955 // that, see if there is a cursor-motion command (starting with
michael@0 2956 // 'go') bound to the keyname without 'Shift-'.
michael@0 2957 handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandleBinding(cm, b, true);})
michael@0 2958 || lookupKey(name, keymaps, function(b) {
michael@0 2959 if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
michael@0 2960 return doHandleBinding(cm, b);
michael@0 2961 });
michael@0 2962 } else {
michael@0 2963 handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm, b); });
michael@0 2964 }
michael@0 2965
michael@0 2966 if (handled) {
michael@0 2967 e_preventDefault(e);
michael@0 2968 restartBlink(cm);
michael@0 2969 signalLater(cm, "keyHandled", cm, name, e);
michael@0 2970 }
michael@0 2971 return handled;
michael@0 2972 }
michael@0 2973
michael@0 2974 // Handle a key from the keypress event
michael@0 2975 function handleCharBinding(cm, e, ch) {
michael@0 2976 var handled = lookupKey("'" + ch + "'", allKeyMaps(cm),
michael@0 2977 function(b) { return doHandleBinding(cm, b, true); });
michael@0 2978 if (handled) {
michael@0 2979 e_preventDefault(e);
michael@0 2980 restartBlink(cm);
michael@0 2981 signalLater(cm, "keyHandled", cm, "'" + ch + "'", e);
michael@0 2982 }
michael@0 2983 return handled;
michael@0 2984 }
michael@0 2985
michael@0 2986 var lastStoppedKey = null;
michael@0 2987 function onKeyDown(e) {
michael@0 2988 var cm = this;
michael@0 2989 ensureFocus(cm);
michael@0 2990 if (signalDOMEvent(cm, e)) return;
michael@0 2991 // IE does strange things with escape.
michael@0 2992 if (ie_upto10 && e.keyCode == 27) e.returnValue = false;
michael@0 2993 var code = e.keyCode;
michael@0 2994 cm.display.shift = code == 16 || e.shiftKey;
michael@0 2995 var handled = handleKeyBinding(cm, e);
michael@0 2996 if (presto) {
michael@0 2997 lastStoppedKey = handled ? code : null;
michael@0 2998 // Opera has no cut event... we try to at least catch the key combo
michael@0 2999 if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
michael@0 3000 cm.replaceSelection("", null, "cut");
michael@0 3001 }
michael@0 3002 }
michael@0 3003
michael@0 3004 function onKeyUp(e) {
michael@0 3005 if (signalDOMEvent(this, e)) return;
michael@0 3006 if (e.keyCode == 16) this.doc.sel.shift = false;
michael@0 3007 }
michael@0 3008
michael@0 3009 function onKeyPress(e) {
michael@0 3010 var cm = this;
michael@0 3011 if (signalDOMEvent(cm, e)) return;
michael@0 3012 var keyCode = e.keyCode, charCode = e.charCode;
michael@0 3013 if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
michael@0 3014 if (((presto && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return;
michael@0 3015 var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
michael@0 3016 if (handleCharBinding(cm, e, ch)) return;
michael@0 3017 if (ie && !ie_upto8) cm.display.inputHasSelection = null;
michael@0 3018 fastPoll(cm);
michael@0 3019 }
michael@0 3020
michael@0 3021 // FOCUS/BLUR EVENTS
michael@0 3022
michael@0 3023 function onFocus(cm) {
michael@0 3024 if (cm.options.readOnly == "nocursor") return;
michael@0 3025 if (!cm.state.focused) {
michael@0 3026 signal(cm, "focus", cm);
michael@0 3027 cm.state.focused = true;
michael@0 3028 if (cm.display.wrapper.className.search(/\bCodeMirror-focused\b/) == -1)
michael@0 3029 cm.display.wrapper.className += " CodeMirror-focused";
michael@0 3030 if (!cm.curOp) {
michael@0 3031 resetInput(cm);
michael@0 3032 if (webkit) setTimeout(bind(resetInput, cm, true), 0); // Issue #1730
michael@0 3033 }
michael@0 3034 }
michael@0 3035 slowPoll(cm);
michael@0 3036 restartBlink(cm);
michael@0 3037 }
michael@0 3038 function onBlur(cm) {
michael@0 3039 if (cm.state.focused) {
michael@0 3040 signal(cm, "blur", cm);
michael@0 3041 cm.state.focused = false;
michael@0 3042 cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-focused", "");
michael@0 3043 }
michael@0 3044 clearInterval(cm.display.blinker);
michael@0 3045 setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
michael@0 3046 }
michael@0 3047
michael@0 3048 // CONTEXT MENU HANDLING
michael@0 3049
michael@0 3050 var detectingSelectAll;
michael@0 3051 // To make the context menu work, we need to briefly unhide the
michael@0 3052 // textarea (making it as unobtrusive as possible) to let the
michael@0 3053 // right-click take effect on it.
michael@0 3054 function onContextMenu(cm, e) {
michael@0 3055 if (signalDOMEvent(cm, e, "contextmenu")) return;
michael@0 3056 var display = cm.display;
michael@0 3057 if (eventInWidget(display, e) || contextMenuInGutter(cm, e)) return;
michael@0 3058
michael@0 3059 var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
michael@0 3060 if (!pos || presto) return; // Opera is difficult.
michael@0 3061
michael@0 3062 // Reset the current text selection only if the click is done outside of the selection
michael@0 3063 // and 'resetSelectionOnContextMenu' option is true.
michael@0 3064 var reset = cm.options.resetSelectionOnContextMenu;
michael@0 3065 if (reset && cm.doc.sel.contains(pos) == -1)
michael@0 3066 operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
michael@0 3067
michael@0 3068 var oldCSS = display.input.style.cssText;
michael@0 3069 display.inputDiv.style.position = "absolute";
michael@0 3070 display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
michael@0 3071 "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " +
michael@0 3072 (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
michael@0 3073 "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
michael@0 3074 focusInput(cm);
michael@0 3075 resetInput(cm);
michael@0 3076 // Adds "Select all" to context menu in FF
michael@0 3077 if (!cm.somethingSelected()) display.input.value = display.prevInput = " ";
michael@0 3078
michael@0 3079 // Select-all will be greyed out if there's nothing to select, so
michael@0 3080 // this adds a zero-width space so that we can later check whether
michael@0 3081 // it got selected.
michael@0 3082 function prepareSelectAllHack() {
michael@0 3083 if (display.input.selectionStart != null) {
michael@0 3084 var extval = display.input.value = "\u200b" + (cm.somethingSelected() ? display.input.value : "");
michael@0 3085 display.prevInput = "\u200b";
michael@0 3086 display.input.selectionStart = 1; display.input.selectionEnd = extval.length;
michael@0 3087 }
michael@0 3088 }
michael@0 3089 function rehide() {
michael@0 3090 display.inputDiv.style.position = "relative";
michael@0 3091 display.input.style.cssText = oldCSS;
michael@0 3092 if (ie_upto8) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos;
michael@0 3093 slowPoll(cm);
michael@0 3094
michael@0 3095 // Try to detect the user choosing select-all
michael@0 3096 if (display.input.selectionStart != null) {
michael@0 3097 if (!ie || ie_upto8) prepareSelectAllHack();
michael@0 3098 clearTimeout(detectingSelectAll);
michael@0 3099 var i = 0, poll = function(){
michael@0 3100 if (display.prevInput == "\u200b" && display.input.selectionStart == 0)
michael@0 3101 operation(cm, commands.selectAll)(cm);
michael@0 3102 else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500);
michael@0 3103 else resetInput(cm);
michael@0 3104 };
michael@0 3105 detectingSelectAll = setTimeout(poll, 200);
michael@0 3106 }
michael@0 3107 }
michael@0 3108
michael@0 3109 if (ie && !ie_upto8) prepareSelectAllHack();
michael@0 3110 if (captureRightClick) {
michael@0 3111 e_stop(e);
michael@0 3112 var mouseup = function() {
michael@0 3113 off(window, "mouseup", mouseup);
michael@0 3114 setTimeout(rehide, 20);
michael@0 3115 };
michael@0 3116 on(window, "mouseup", mouseup);
michael@0 3117 } else {
michael@0 3118 setTimeout(rehide, 50);
michael@0 3119 }
michael@0 3120 }
michael@0 3121
michael@0 3122 function contextMenuInGutter(cm, e) {
michael@0 3123 if (!hasHandler(cm, "gutterContextMenu")) return false;
michael@0 3124 return gutterEvent(cm, e, "gutterContextMenu", false, signal);
michael@0 3125 }
michael@0 3126
michael@0 3127 // UPDATING
michael@0 3128
michael@0 3129 // Compute the position of the end of a change (its 'to' property
michael@0 3130 // refers to the pre-change end).
michael@0 3131 var changeEnd = CodeMirror.changeEnd = function(change) {
michael@0 3132 if (!change.text) return change.to;
michael@0 3133 return Pos(change.from.line + change.text.length - 1,
michael@0 3134 lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
michael@0 3135 };
michael@0 3136
michael@0 3137 // Adjust a position to refer to the post-change position of the
michael@0 3138 // same text, or the end of the change if the change covers it.
michael@0 3139 function adjustForChange(pos, change) {
michael@0 3140 if (cmp(pos, change.from) < 0) return pos;
michael@0 3141 if (cmp(pos, change.to) <= 0) return changeEnd(change);
michael@0 3142
michael@0 3143 var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
michael@0 3144 if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
michael@0 3145 return Pos(line, ch);
michael@0 3146 }
michael@0 3147
michael@0 3148 function computeSelAfterChange(doc, change) {
michael@0 3149 var out = [];
michael@0 3150 for (var i = 0; i < doc.sel.ranges.length; i++) {
michael@0 3151 var range = doc.sel.ranges[i];
michael@0 3152 out.push(new Range(adjustForChange(range.anchor, change),
michael@0 3153 adjustForChange(range.head, change)));
michael@0 3154 }
michael@0 3155 return normalizeSelection(out, doc.sel.primIndex);
michael@0 3156 }
michael@0 3157
michael@0 3158 function offsetPos(pos, old, nw) {
michael@0 3159 if (pos.line == old.line)
michael@0 3160 return Pos(nw.line, pos.ch - old.ch + nw.ch);
michael@0 3161 else
michael@0 3162 return Pos(nw.line + (pos.line - old.line), pos.ch);
michael@0 3163 }
michael@0 3164
michael@0 3165 // Used by replaceSelections to allow moving the selection to the
michael@0 3166 // start or around the replaced test. Hint may be "start" or "around".
michael@0 3167 function computeReplacedSel(doc, changes, hint) {
michael@0 3168 var out = [];
michael@0 3169 var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
michael@0 3170 for (var i = 0; i < changes.length; i++) {
michael@0 3171 var change = changes[i];
michael@0 3172 var from = offsetPos(change.from, oldPrev, newPrev);
michael@0 3173 var to = offsetPos(changeEnd(change), oldPrev, newPrev);
michael@0 3174 oldPrev = change.to;
michael@0 3175 newPrev = to;
michael@0 3176 if (hint == "around") {
michael@0 3177 var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
michael@0 3178 out[i] = new Range(inv ? to : from, inv ? from : to);
michael@0 3179 } else {
michael@0 3180 out[i] = new Range(from, from);
michael@0 3181 }
michael@0 3182 }
michael@0 3183 return new Selection(out, doc.sel.primIndex);
michael@0 3184 }
michael@0 3185
michael@0 3186 // Allow "beforeChange" event handlers to influence a change
michael@0 3187 function filterChange(doc, change, update) {
michael@0 3188 var obj = {
michael@0 3189 canceled: false,
michael@0 3190 from: change.from,
michael@0 3191 to: change.to,
michael@0 3192 text: change.text,
michael@0 3193 origin: change.origin,
michael@0 3194 cancel: function() { this.canceled = true; }
michael@0 3195 };
michael@0 3196 if (update) obj.update = function(from, to, text, origin) {
michael@0 3197 if (from) this.from = clipPos(doc, from);
michael@0 3198 if (to) this.to = clipPos(doc, to);
michael@0 3199 if (text) this.text = text;
michael@0 3200 if (origin !== undefined) this.origin = origin;
michael@0 3201 };
michael@0 3202 signal(doc, "beforeChange", doc, obj);
michael@0 3203 if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
michael@0 3204
michael@0 3205 if (obj.canceled) return null;
michael@0 3206 return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
michael@0 3207 }
michael@0 3208
michael@0 3209 // Apply a change to a document, and add it to the document's
michael@0 3210 // history, and propagating it to all linked documents.
michael@0 3211 function makeChange(doc, change, ignoreReadOnly) {
michael@0 3212 if (doc.cm) {
michael@0 3213 if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
michael@0 3214 if (doc.cm.state.suppressEdits) return;
michael@0 3215 }
michael@0 3216
michael@0 3217 if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
michael@0 3218 change = filterChange(doc, change, true);
michael@0 3219 if (!change) return;
michael@0 3220 }
michael@0 3221
michael@0 3222 // Possibly split or suppress the update based on the presence
michael@0 3223 // of read-only spans in its range.
michael@0 3224 var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
michael@0 3225 if (split) {
michael@0 3226 for (var i = split.length - 1; i >= 0; --i)
michael@0 3227 makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
michael@0 3228 } else {
michael@0 3229 makeChangeInner(doc, change);
michael@0 3230 }
michael@0 3231 }
michael@0 3232
michael@0 3233 function makeChangeInner(doc, change) {
michael@0 3234 if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
michael@0 3235 var selAfter = computeSelAfterChange(doc, change);
michael@0 3236 addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
michael@0 3237
michael@0 3238 makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
michael@0 3239 var rebased = [];
michael@0 3240
michael@0 3241 linkedDocs(doc, function(doc, sharedHist) {
michael@0 3242 if (!sharedHist && indexOf(rebased, doc.history) == -1) {
michael@0 3243 rebaseHist(doc.history, change);
michael@0 3244 rebased.push(doc.history);
michael@0 3245 }
michael@0 3246 makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
michael@0 3247 });
michael@0 3248 }
michael@0 3249
michael@0 3250 // Revert a change stored in a document's history.
michael@0 3251 function makeChangeFromHistory(doc, type, allowSelectionOnly) {
michael@0 3252 if (doc.cm && doc.cm.state.suppressEdits) return;
michael@0 3253
michael@0 3254 var hist = doc.history, event, selAfter = doc.sel;
michael@0 3255 var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
michael@0 3256
michael@0 3257 // Verify that there is a useable event (so that ctrl-z won't
michael@0 3258 // needlessly clear selection events)
michael@0 3259 for (var i = 0; i < source.length; i++) {
michael@0 3260 event = source[i];
michael@0 3261 if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
michael@0 3262 break;
michael@0 3263 }
michael@0 3264 if (i == source.length) return;
michael@0 3265 hist.lastOrigin = hist.lastSelOrigin = null;
michael@0 3266
michael@0 3267 for (;;) {
michael@0 3268 event = source.pop();
michael@0 3269 if (event.ranges) {
michael@0 3270 pushSelectionToHistory(event, dest);
michael@0 3271 if (allowSelectionOnly && !event.equals(doc.sel)) {
michael@0 3272 setSelection(doc, event, {clearRedo: false});
michael@0 3273 return;
michael@0 3274 }
michael@0 3275 selAfter = event;
michael@0 3276 }
michael@0 3277 else break;
michael@0 3278 }
michael@0 3279
michael@0 3280 // Build up a reverse change object to add to the opposite history
michael@0 3281 // stack (redo when undoing, and vice versa).
michael@0 3282 var antiChanges = [];
michael@0 3283 pushSelectionToHistory(selAfter, dest);
michael@0 3284 dest.push({changes: antiChanges, generation: hist.generation});
michael@0 3285 hist.generation = event.generation || ++hist.maxGeneration;
michael@0 3286
michael@0 3287 var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
michael@0 3288
michael@0 3289 for (var i = event.changes.length - 1; i >= 0; --i) {
michael@0 3290 var change = event.changes[i];
michael@0 3291 change.origin = type;
michael@0 3292 if (filter && !filterChange(doc, change, false)) {
michael@0 3293 source.length = 0;
michael@0 3294 return;
michael@0 3295 }
michael@0 3296
michael@0 3297 antiChanges.push(historyChangeFromChange(doc, change));
michael@0 3298
michael@0 3299 var after = i ? computeSelAfterChange(doc, change, null) : lst(source);
michael@0 3300 makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
michael@0 3301 if (doc.cm) ensureCursorVisible(doc.cm);
michael@0 3302 var rebased = [];
michael@0 3303
michael@0 3304 // Propagate to the linked documents
michael@0 3305 linkedDocs(doc, function(doc, sharedHist) {
michael@0 3306 if (!sharedHist && indexOf(rebased, doc.history) == -1) {
michael@0 3307 rebaseHist(doc.history, change);
michael@0 3308 rebased.push(doc.history);
michael@0 3309 }
michael@0 3310 makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
michael@0 3311 });
michael@0 3312 }
michael@0 3313 }
michael@0 3314
michael@0 3315 // Sub-views need their line numbers shifted when text is added
michael@0 3316 // above or below them in the parent document.
michael@0 3317 function shiftDoc(doc, distance) {
michael@0 3318 doc.first += distance;
michael@0 3319 doc.sel = new Selection(map(doc.sel.ranges, function(range) {
michael@0 3320 return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
michael@0 3321 Pos(range.head.line + distance, range.head.ch));
michael@0 3322 }), doc.sel.primIndex);
michael@0 3323 if (doc.cm) regChange(doc.cm, doc.first, doc.first - distance, distance);
michael@0 3324 }
michael@0 3325
michael@0 3326 // More lower-level change function, handling only a single document
michael@0 3327 // (not linked ones).
michael@0 3328 function makeChangeSingleDoc(doc, change, selAfter, spans) {
michael@0 3329 if (doc.cm && !doc.cm.curOp)
michael@0 3330 return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
michael@0 3331
michael@0 3332 if (change.to.line < doc.first) {
michael@0 3333 shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
michael@0 3334 return;
michael@0 3335 }
michael@0 3336 if (change.from.line > doc.lastLine()) return;
michael@0 3337
michael@0 3338 // Clip the change to the size of this doc
michael@0 3339 if (change.from.line < doc.first) {
michael@0 3340 var shift = change.text.length - 1 - (doc.first - change.from.line);
michael@0 3341 shiftDoc(doc, shift);
michael@0 3342 change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
michael@0 3343 text: [lst(change.text)], origin: change.origin};
michael@0 3344 }
michael@0 3345 var last = doc.lastLine();
michael@0 3346 if (change.to.line > last) {
michael@0 3347 change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
michael@0 3348 text: [change.text[0]], origin: change.origin};
michael@0 3349 }
michael@0 3350
michael@0 3351 change.removed = getBetween(doc, change.from, change.to);
michael@0 3352
michael@0 3353 if (!selAfter) selAfter = computeSelAfterChange(doc, change, null);
michael@0 3354 if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
michael@0 3355 else updateDoc(doc, change, spans);
michael@0 3356 setSelectionNoUndo(doc, selAfter, sel_dontScroll);
michael@0 3357 }
michael@0 3358
michael@0 3359 // Handle the interaction of a change to a document with the editor
michael@0 3360 // that this document is part of.
michael@0 3361 function makeChangeSingleDocInEditor(cm, change, spans) {
michael@0 3362 var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
michael@0 3363
michael@0 3364 var recomputeMaxLength = false, checkWidthStart = from.line;
michael@0 3365 if (!cm.options.lineWrapping) {
michael@0 3366 checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
michael@0 3367 doc.iter(checkWidthStart, to.line + 1, function(line) {
michael@0 3368 if (line == display.maxLine) {
michael@0 3369 recomputeMaxLength = true;
michael@0 3370 return true;
michael@0 3371 }
michael@0 3372 });
michael@0 3373 }
michael@0 3374
michael@0 3375 if (doc.sel.contains(change.from, change.to) > -1)
michael@0 3376 cm.curOp.cursorActivity = true;
michael@0 3377
michael@0 3378 updateDoc(doc, change, spans, estimateHeight(cm));
michael@0 3379
michael@0 3380 if (!cm.options.lineWrapping) {
michael@0 3381 doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
michael@0 3382 var len = lineLength(line);
michael@0 3383 if (len > display.maxLineLength) {
michael@0 3384 display.maxLine = line;
michael@0 3385 display.maxLineLength = len;
michael@0 3386 display.maxLineChanged = true;
michael@0 3387 recomputeMaxLength = false;
michael@0 3388 }
michael@0 3389 });
michael@0 3390 if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
michael@0 3391 }
michael@0 3392
michael@0 3393 // Adjust frontier, schedule worker
michael@0 3394 doc.frontier = Math.min(doc.frontier, from.line);
michael@0 3395 startWorker(cm, 400);
michael@0 3396
michael@0 3397 var lendiff = change.text.length - (to.line - from.line) - 1;
michael@0 3398 // Remember that these lines changed, for updating the display
michael@0 3399 if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
michael@0 3400 regLineChange(cm, from.line, "text");
michael@0 3401 else
michael@0 3402 regChange(cm, from.line, to.line + 1, lendiff);
michael@0 3403
michael@0 3404 if (hasHandler(cm, "change") || hasHandler(cm, "changes"))
michael@0 3405 (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push({
michael@0 3406 from: from, to: to,
michael@0 3407 text: change.text,
michael@0 3408 removed: change.removed,
michael@0 3409 origin: change.origin
michael@0 3410 });
michael@0 3411 }
michael@0 3412
michael@0 3413 function replaceRange(doc, code, from, to, origin) {
michael@0 3414 if (!to) to = from;
michael@0 3415 if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
michael@0 3416 if (typeof code == "string") code = splitLines(code);
michael@0 3417 makeChange(doc, {from: from, to: to, text: code, origin: origin});
michael@0 3418 }
michael@0 3419
michael@0 3420 // SCROLLING THINGS INTO VIEW
michael@0 3421
michael@0 3422 // If an editor sits on the top or bottom of the window, partially
michael@0 3423 // scrolled out of view, this ensures that the cursor is visible.
michael@0 3424 function maybeScrollWindow(cm, coords) {
michael@0 3425 var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
michael@0 3426 if (coords.top + box.top < 0) doScroll = true;
michael@0 3427 else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
michael@0 3428 if (doScroll != null && !phantom) {
michael@0 3429 var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
michael@0 3430 (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
michael@0 3431 (coords.bottom - coords.top + scrollerCutOff) + "px; left: " +
michael@0 3432 coords.left + "px; width: 2px;");
michael@0 3433 cm.display.lineSpace.appendChild(scrollNode);
michael@0 3434 scrollNode.scrollIntoView(doScroll);
michael@0 3435 cm.display.lineSpace.removeChild(scrollNode);
michael@0 3436 }
michael@0 3437 }
michael@0 3438
michael@0 3439 // Scroll a given position into view (immediately), verifying that
michael@0 3440 // it actually became visible (as line heights are accurately
michael@0 3441 // measured, the position of something may 'drift' during drawing).
michael@0 3442 function scrollPosIntoView(cm, pos, end, margin) {
michael@0 3443 if (margin == null) margin = 0;
michael@0 3444 for (;;) {
michael@0 3445 var changed = false, coords = cursorCoords(cm, pos);
michael@0 3446 var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
michael@0 3447 var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
michael@0 3448 Math.min(coords.top, endCoords.top) - margin,
michael@0 3449 Math.max(coords.left, endCoords.left),
michael@0 3450 Math.max(coords.bottom, endCoords.bottom) + margin);
michael@0 3451 var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
michael@0 3452 if (scrollPos.scrollTop != null) {
michael@0 3453 setScrollTop(cm, scrollPos.scrollTop);
michael@0 3454 if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
michael@0 3455 }
michael@0 3456 if (scrollPos.scrollLeft != null) {
michael@0 3457 setScrollLeft(cm, scrollPos.scrollLeft);
michael@0 3458 if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
michael@0 3459 }
michael@0 3460 if (!changed) return coords;
michael@0 3461 }
michael@0 3462 }
michael@0 3463
michael@0 3464 // Scroll a given set of coordinates into view (immediately).
michael@0 3465 function scrollIntoView(cm, x1, y1, x2, y2) {
michael@0 3466 var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
michael@0 3467 if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
michael@0 3468 if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
michael@0 3469 }
michael@0 3470
michael@0 3471 // Calculate a new scroll position needed to scroll the given
michael@0 3472 // rectangle into view. Returns an object with scrollTop and
michael@0 3473 // scrollLeft properties. When these are undefined, the
michael@0 3474 // vertical/horizontal position does not need to be adjusted.
michael@0 3475 function calculateScrollPos(cm, x1, y1, x2, y2) {
michael@0 3476 var display = cm.display, snapMargin = textHeight(cm.display);
michael@0 3477 if (y1 < 0) y1 = 0;
michael@0 3478 var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
michael@0 3479 var screen = display.scroller.clientHeight - scrollerCutOff, result = {};
michael@0 3480 var docBottom = cm.doc.height + paddingVert(display);
michael@0 3481 var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
michael@0 3482 if (y1 < screentop) {
michael@0 3483 result.scrollTop = atTop ? 0 : y1;
michael@0 3484 } else if (y2 > screentop + screen) {
michael@0 3485 var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
michael@0 3486 if (newTop != screentop) result.scrollTop = newTop;
michael@0 3487 }
michael@0 3488
michael@0 3489 var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
michael@0 3490 var screenw = display.scroller.clientWidth - scrollerCutOff;
michael@0 3491 x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth;
michael@0 3492 var gutterw = display.gutters.offsetWidth;
michael@0 3493 var atLeft = x1 < gutterw + 10;
michael@0 3494 if (x1 < screenleft + gutterw || atLeft) {
michael@0 3495 if (atLeft) x1 = 0;
michael@0 3496 result.scrollLeft = Math.max(0, x1 - 10 - gutterw);
michael@0 3497 } else if (x2 > screenw + screenleft - 3) {
michael@0 3498 result.scrollLeft = x2 + 10 - screenw;
michael@0 3499 }
michael@0 3500 return result;
michael@0 3501 }
michael@0 3502
michael@0 3503 // Store a relative adjustment to the scroll position in the current
michael@0 3504 // operation (to be applied when the operation finishes).
michael@0 3505 function addToScrollPos(cm, left, top) {
michael@0 3506 if (left != null || top != null) resolveScrollToPos(cm);
michael@0 3507 if (left != null)
michael@0 3508 cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
michael@0 3509 if (top != null)
michael@0 3510 cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
michael@0 3511 }
michael@0 3512
michael@0 3513 // Make sure that at the end of the operation the current cursor is
michael@0 3514 // shown.
michael@0 3515 function ensureCursorVisible(cm) {
michael@0 3516 resolveScrollToPos(cm);
michael@0 3517 var cur = cm.getCursor(), from = cur, to = cur;
michael@0 3518 if (!cm.options.lineWrapping) {
michael@0 3519 from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
michael@0 3520 to = Pos(cur.line, cur.ch + 1);
michael@0 3521 }
michael@0 3522 cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
michael@0 3523 }
michael@0 3524
michael@0 3525 // When an operation has its scrollToPos property set, and another
michael@0 3526 // scroll action is applied before the end of the operation, this
michael@0 3527 // 'simulates' scrolling that position into view in a cheap way, so
michael@0 3528 // that the effect of intermediate scroll commands is not ignored.
michael@0 3529 function resolveScrollToPos(cm) {
michael@0 3530 var range = cm.curOp.scrollToPos;
michael@0 3531 if (range) {
michael@0 3532 cm.curOp.scrollToPos = null;
michael@0 3533 var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
michael@0 3534 var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
michael@0 3535 Math.min(from.top, to.top) - range.margin,
michael@0 3536 Math.max(from.right, to.right),
michael@0 3537 Math.max(from.bottom, to.bottom) + range.margin);
michael@0 3538 cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
michael@0 3539 }
michael@0 3540 }
michael@0 3541
michael@0 3542 // API UTILITIES
michael@0 3543
michael@0 3544 // Indent the given line. The how parameter can be "smart",
michael@0 3545 // "add"/null, "subtract", or "prev". When aggressive is false
michael@0 3546 // (typically set to true for forced single-line indents), empty
michael@0 3547 // lines are not indented, and places where the mode returns Pass
michael@0 3548 // are left alone.
michael@0 3549 function indentLine(cm, n, how, aggressive) {
michael@0 3550 var doc = cm.doc, state;
michael@0 3551 if (how == null) how = "add";
michael@0 3552 if (how == "smart") {
michael@0 3553 // Fall back to "prev" when the mode doesn't have an indentation
michael@0 3554 // method.
michael@0 3555 if (!cm.doc.mode.indent) how = "prev";
michael@0 3556 else state = getStateBefore(cm, n);
michael@0 3557 }
michael@0 3558
michael@0 3559 var tabSize = cm.options.tabSize;
michael@0 3560 var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
michael@0 3561 if (line.stateAfter) line.stateAfter = null;
michael@0 3562 var curSpaceString = line.text.match(/^\s*/)[0], indentation;
michael@0 3563 if (!aggressive && !/\S/.test(line.text)) {
michael@0 3564 indentation = 0;
michael@0 3565 how = "not";
michael@0 3566 } else if (how == "smart") {
michael@0 3567 indentation = cm.doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
michael@0 3568 if (indentation == Pass) {
michael@0 3569 if (!aggressive) return;
michael@0 3570 how = "prev";
michael@0 3571 }
michael@0 3572 }
michael@0 3573 if (how == "prev") {
michael@0 3574 if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
michael@0 3575 else indentation = 0;
michael@0 3576 } else if (how == "add") {
michael@0 3577 indentation = curSpace + cm.options.indentUnit;
michael@0 3578 } else if (how == "subtract") {
michael@0 3579 indentation = curSpace - cm.options.indentUnit;
michael@0 3580 } else if (typeof how == "number") {
michael@0 3581 indentation = curSpace + how;
michael@0 3582 }
michael@0 3583 indentation = Math.max(0, indentation);
michael@0 3584
michael@0 3585 var indentString = "", pos = 0;
michael@0 3586 if (cm.options.indentWithTabs)
michael@0 3587 for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
michael@0 3588 if (pos < indentation) indentString += spaceStr(indentation - pos);
michael@0 3589
michael@0 3590 if (indentString != curSpaceString) {
michael@0 3591 replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
michael@0 3592 } else {
michael@0 3593 // Ensure that, if the cursor was in the whitespace at the start
michael@0 3594 // of the line, it is moved to the end of that space.
michael@0 3595 for (var i = 0; i < doc.sel.ranges.length; i++) {
michael@0 3596 var range = doc.sel.ranges[i];
michael@0 3597 if (range.head.line == n && range.head.ch < curSpaceString.length) {
michael@0 3598 var pos = Pos(n, curSpaceString.length);
michael@0 3599 replaceOneSelection(doc, i, new Range(pos, pos));
michael@0 3600 break;
michael@0 3601 }
michael@0 3602 }
michael@0 3603 }
michael@0 3604 line.stateAfter = null;
michael@0 3605 }
michael@0 3606
michael@0 3607 // Utility for applying a change to a line by handle or number,
michael@0 3608 // returning the number and optionally registering the line as
michael@0 3609 // changed.
michael@0 3610 function changeLine(cm, handle, changeType, op) {
michael@0 3611 var no = handle, line = handle, doc = cm.doc;
michael@0 3612 if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
michael@0 3613 else no = lineNo(handle);
michael@0 3614 if (no == null) return null;
michael@0 3615 if (op(line, no)) regLineChange(cm, no, changeType);
michael@0 3616 else return null;
michael@0 3617 return line;
michael@0 3618 }
michael@0 3619
michael@0 3620 // Helper for deleting text near the selection(s), used to implement
michael@0 3621 // backspace, delete, and similar functionality.
michael@0 3622 function deleteNearSelection(cm, compute) {
michael@0 3623 var ranges = cm.doc.sel.ranges, kill = [];
michael@0 3624 // Build up a set of ranges to kill first, merging overlapping
michael@0 3625 // ranges.
michael@0 3626 for (var i = 0; i < ranges.length; i++) {
michael@0 3627 var toKill = compute(ranges[i]);
michael@0 3628 while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
michael@0 3629 var replaced = kill.pop();
michael@0 3630 if (cmp(replaced.from, toKill.from) < 0) {
michael@0 3631 toKill.from = replaced.from;
michael@0 3632 break;
michael@0 3633 }
michael@0 3634 }
michael@0 3635 kill.push(toKill);
michael@0 3636 }
michael@0 3637 // Next, remove those actual ranges.
michael@0 3638 runInOp(cm, function() {
michael@0 3639 for (var i = kill.length - 1; i >= 0; i--)
michael@0 3640 replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
michael@0 3641 ensureCursorVisible(cm);
michael@0 3642 });
michael@0 3643 }
michael@0 3644
michael@0 3645 // Used for horizontal relative motion. Dir is -1 or 1 (left or
michael@0 3646 // right), unit can be "char", "column" (like char, but doesn't
michael@0 3647 // cross line boundaries), "word" (across next word), or "group" (to
michael@0 3648 // the start of next group of word or non-word-non-whitespace
michael@0 3649 // chars). The visually param controls whether, in right-to-left
michael@0 3650 // text, direction 1 means to move towards the next index in the
michael@0 3651 // string, or towards the character to the right of the current
michael@0 3652 // position. The resulting position will have a hitSide=true
michael@0 3653 // property if it reached the end of the document.
michael@0 3654 function findPosH(doc, pos, dir, unit, visually) {
michael@0 3655 var line = pos.line, ch = pos.ch, origDir = dir;
michael@0 3656 var lineObj = getLine(doc, line);
michael@0 3657 var possible = true;
michael@0 3658 function findNextLine() {
michael@0 3659 var l = line + dir;
michael@0 3660 if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
michael@0 3661 line = l;
michael@0 3662 return lineObj = getLine(doc, l);
michael@0 3663 }
michael@0 3664 function moveOnce(boundToLine) {
michael@0 3665 var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
michael@0 3666 if (next == null) {
michael@0 3667 if (!boundToLine && findNextLine()) {
michael@0 3668 if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
michael@0 3669 else ch = dir < 0 ? lineObj.text.length : 0;
michael@0 3670 } else return (possible = false);
michael@0 3671 } else ch = next;
michael@0 3672 return true;
michael@0 3673 }
michael@0 3674
michael@0 3675 if (unit == "char") moveOnce();
michael@0 3676 else if (unit == "column") moveOnce(true);
michael@0 3677 else if (unit == "word" || unit == "group") {
michael@0 3678 var sawType = null, group = unit == "group";
michael@0 3679 for (var first = true;; first = false) {
michael@0 3680 if (dir < 0 && !moveOnce(!first)) break;
michael@0 3681 var cur = lineObj.text.charAt(ch) || "\n";
michael@0 3682 var type = isWordChar(cur) ? "w"
michael@0 3683 : group && cur == "\n" ? "n"
michael@0 3684 : !group || /\s/.test(cur) ? null
michael@0 3685 : "p";
michael@0 3686 if (group && !first && !type) type = "s";
michael@0 3687 if (sawType && sawType != type) {
michael@0 3688 if (dir < 0) {dir = 1; moveOnce();}
michael@0 3689 break;
michael@0 3690 }
michael@0 3691
michael@0 3692 if (type) sawType = type;
michael@0 3693 if (dir > 0 && !moveOnce(!first)) break;
michael@0 3694 }
michael@0 3695 }
michael@0 3696 var result = skipAtomic(doc, Pos(line, ch), origDir, true);
michael@0 3697 if (!possible) result.hitSide = true;
michael@0 3698 return result;
michael@0 3699 }
michael@0 3700
michael@0 3701 // For relative vertical movement. Dir may be -1 or 1. Unit can be
michael@0 3702 // "page" or "line". The resulting position will have a hitSide=true
michael@0 3703 // property if it reached the end of the document.
michael@0 3704 function findPosV(cm, pos, dir, unit) {
michael@0 3705 var doc = cm.doc, x = pos.left, y;
michael@0 3706 if (unit == "page") {
michael@0 3707 var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
michael@0 3708 y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
michael@0 3709 } else if (unit == "line") {
michael@0 3710 y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
michael@0 3711 }
michael@0 3712 for (;;) {
michael@0 3713 var target = coordsChar(cm, x, y);
michael@0 3714 if (!target.outside) break;
michael@0 3715 if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
michael@0 3716 y += dir * 5;
michael@0 3717 }
michael@0 3718 return target;
michael@0 3719 }
michael@0 3720
michael@0 3721 // Find the word at the given position (as returned by coordsChar).
michael@0 3722 function findWordAt(doc, pos) {
michael@0 3723 var line = getLine(doc, pos.line).text;
michael@0 3724 var start = pos.ch, end = pos.ch;
michael@0 3725 if (line) {
michael@0 3726 if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
michael@0 3727 var startChar = line.charAt(start);
michael@0 3728 var check = isWordChar(startChar) ? isWordChar
michael@0 3729 : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
michael@0 3730 : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
michael@0 3731 while (start > 0 && check(line.charAt(start - 1))) --start;
michael@0 3732 while (end < line.length && check(line.charAt(end))) ++end;
michael@0 3733 }
michael@0 3734 return new Range(Pos(pos.line, start), Pos(pos.line, end));
michael@0 3735 }
michael@0 3736
michael@0 3737 // EDITOR METHODS
michael@0 3738
michael@0 3739 // The publicly visible API. Note that methodOp(f) means
michael@0 3740 // 'wrap f in an operation, performed on its `this` parameter'.
michael@0 3741
michael@0 3742 // This is not the complete set of editor methods. Most of the
michael@0 3743 // methods defined on the Doc type are also injected into
michael@0 3744 // CodeMirror.prototype, for backwards compatibility and
michael@0 3745 // convenience.
michael@0 3746
michael@0 3747 CodeMirror.prototype = {
michael@0 3748 constructor: CodeMirror,
michael@0 3749 focus: function(){window.focus(); focusInput(this); fastPoll(this);},
michael@0 3750
michael@0 3751 setOption: function(option, value) {
michael@0 3752 var options = this.options, old = options[option];
michael@0 3753 if (options[option] == value && option != "mode") return;
michael@0 3754 options[option] = value;
michael@0 3755 if (optionHandlers.hasOwnProperty(option))
michael@0 3756 operation(this, optionHandlers[option])(this, value, old);
michael@0 3757 },
michael@0 3758
michael@0 3759 getOption: function(option) {return this.options[option];},
michael@0 3760 getDoc: function() {return this.doc;},
michael@0 3761
michael@0 3762 addKeyMap: function(map, bottom) {
michael@0 3763 this.state.keyMaps[bottom ? "push" : "unshift"](map);
michael@0 3764 },
michael@0 3765 removeKeyMap: function(map) {
michael@0 3766 var maps = this.state.keyMaps;
michael@0 3767 for (var i = 0; i < maps.length; ++i)
michael@0 3768 if (maps[i] == map || (typeof maps[i] != "string" && maps[i].name == map)) {
michael@0 3769 maps.splice(i, 1);
michael@0 3770 return true;
michael@0 3771 }
michael@0 3772 },
michael@0 3773
michael@0 3774 addOverlay: methodOp(function(spec, options) {
michael@0 3775 var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
michael@0 3776 if (mode.startState) throw new Error("Overlays may not be stateful.");
michael@0 3777 this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
michael@0 3778 this.state.modeGen++;
michael@0 3779 regChange(this);
michael@0 3780 }),
michael@0 3781 removeOverlay: methodOp(function(spec) {
michael@0 3782 var overlays = this.state.overlays;
michael@0 3783 for (var i = 0; i < overlays.length; ++i) {
michael@0 3784 var cur = overlays[i].modeSpec;
michael@0 3785 if (cur == spec || typeof spec == "string" && cur.name == spec) {
michael@0 3786 overlays.splice(i, 1);
michael@0 3787 this.state.modeGen++;
michael@0 3788 regChange(this);
michael@0 3789 return;
michael@0 3790 }
michael@0 3791 }
michael@0 3792 }),
michael@0 3793
michael@0 3794 indentLine: methodOp(function(n, dir, aggressive) {
michael@0 3795 if (typeof dir != "string" && typeof dir != "number") {
michael@0 3796 if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
michael@0 3797 else dir = dir ? "add" : "subtract";
michael@0 3798 }
michael@0 3799 if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
michael@0 3800 }),
michael@0 3801 indentSelection: methodOp(function(how) {
michael@0 3802 var ranges = this.doc.sel.ranges, end = -1;
michael@0 3803 for (var i = 0; i < ranges.length; i++) {
michael@0 3804 var range = ranges[i];
michael@0 3805 if (!range.empty()) {
michael@0 3806 var start = Math.max(end, range.from().line);
michael@0 3807 var to = range.to();
michael@0 3808 end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
michael@0 3809 for (var j = start; j < end; ++j)
michael@0 3810 indentLine(this, j, how);
michael@0 3811 } else if (range.head.line > end) {
michael@0 3812 indentLine(this, range.head.line, how, true);
michael@0 3813 end = range.head.line;
michael@0 3814 if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
michael@0 3815 }
michael@0 3816 }
michael@0 3817 }),
michael@0 3818
michael@0 3819 // Fetch the parser token for a given character. Useful for hacks
michael@0 3820 // that want to inspect the mode state (say, for completion).
michael@0 3821 getTokenAt: function(pos, precise) {
michael@0 3822 var doc = this.doc;
michael@0 3823 pos = clipPos(doc, pos);
michael@0 3824 var state = getStateBefore(this, pos.line, precise), mode = this.doc.mode;
michael@0 3825 var line = getLine(doc, pos.line);
michael@0 3826 var stream = new StringStream(line.text, this.options.tabSize);
michael@0 3827 while (stream.pos < pos.ch && !stream.eol()) {
michael@0 3828 stream.start = stream.pos;
michael@0 3829 var style = mode.token(stream, state);
michael@0 3830 }
michael@0 3831 return {start: stream.start,
michael@0 3832 end: stream.pos,
michael@0 3833 string: stream.current(),
michael@0 3834 type: style || null,
michael@0 3835 state: state};
michael@0 3836 },
michael@0 3837
michael@0 3838 getTokenTypeAt: function(pos) {
michael@0 3839 pos = clipPos(this.doc, pos);
michael@0 3840 var styles = getLineStyles(this, getLine(this.doc, pos.line));
michael@0 3841 var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
michael@0 3842 if (ch == 0) return styles[2];
michael@0 3843 for (;;) {
michael@0 3844 var mid = (before + after) >> 1;
michael@0 3845 if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
michael@0 3846 else if (styles[mid * 2 + 1] < ch) before = mid + 1;
michael@0 3847 else return styles[mid * 2 + 2];
michael@0 3848 }
michael@0 3849 },
michael@0 3850
michael@0 3851 getModeAt: function(pos) {
michael@0 3852 var mode = this.doc.mode;
michael@0 3853 if (!mode.innerMode) return mode;
michael@0 3854 return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
michael@0 3855 },
michael@0 3856
michael@0 3857 getHelper: function(pos, type) {
michael@0 3858 return this.getHelpers(pos, type)[0];
michael@0 3859 },
michael@0 3860
michael@0 3861 getHelpers: function(pos, type) {
michael@0 3862 var found = [];
michael@0 3863 if (!helpers.hasOwnProperty(type)) return helpers;
michael@0 3864 var help = helpers[type], mode = this.getModeAt(pos);
michael@0 3865 if (typeof mode[type] == "string") {
michael@0 3866 if (help[mode[type]]) found.push(help[mode[type]]);
michael@0 3867 } else if (mode[type]) {
michael@0 3868 for (var i = 0; i < mode[type].length; i++) {
michael@0 3869 var val = help[mode[type][i]];
michael@0 3870 if (val) found.push(val);
michael@0 3871 }
michael@0 3872 } else if (mode.helperType && help[mode.helperType]) {
michael@0 3873 found.push(help[mode.helperType]);
michael@0 3874 } else if (help[mode.name]) {
michael@0 3875 found.push(help[mode.name]);
michael@0 3876 }
michael@0 3877 for (var i = 0; i < help._global.length; i++) {
michael@0 3878 var cur = help._global[i];
michael@0 3879 if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
michael@0 3880 found.push(cur.val);
michael@0 3881 }
michael@0 3882 return found;
michael@0 3883 },
michael@0 3884
michael@0 3885 getStateAfter: function(line, precise) {
michael@0 3886 var doc = this.doc;
michael@0 3887 line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
michael@0 3888 return getStateBefore(this, line + 1, precise);
michael@0 3889 },
michael@0 3890
michael@0 3891 cursorCoords: function(start, mode) {
michael@0 3892 var pos, range = this.doc.sel.primary();
michael@0 3893 if (start == null) pos = range.head;
michael@0 3894 else if (typeof start == "object") pos = clipPos(this.doc, start);
michael@0 3895 else pos = start ? range.from() : range.to();
michael@0 3896 return cursorCoords(this, pos, mode || "page");
michael@0 3897 },
michael@0 3898
michael@0 3899 charCoords: function(pos, mode) {
michael@0 3900 return charCoords(this, clipPos(this.doc, pos), mode || "page");
michael@0 3901 },
michael@0 3902
michael@0 3903 coordsChar: function(coords, mode) {
michael@0 3904 coords = fromCoordSystem(this, coords, mode || "page");
michael@0 3905 return coordsChar(this, coords.left, coords.top);
michael@0 3906 },
michael@0 3907
michael@0 3908 lineAtHeight: function(height, mode) {
michael@0 3909 height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
michael@0 3910 return lineAtHeight(this.doc, height + this.display.viewOffset);
michael@0 3911 },
michael@0 3912 heightAtLine: function(line, mode) {
michael@0 3913 var end = false, last = this.doc.first + this.doc.size - 1;
michael@0 3914 if (line < this.doc.first) line = this.doc.first;
michael@0 3915 else if (line > last) { line = last; end = true; }
michael@0 3916 var lineObj = getLine(this.doc, line);
michael@0 3917 return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
michael@0 3918 (end ? this.doc.height - heightAtLine(lineObj) : 0);
michael@0 3919 },
michael@0 3920
michael@0 3921 defaultTextHeight: function() { return textHeight(this.display); },
michael@0 3922 defaultCharWidth: function() { return charWidth(this.display); },
michael@0 3923
michael@0 3924 setGutterMarker: methodOp(function(line, gutterID, value) {
michael@0 3925 return changeLine(this, line, "gutter", function(line) {
michael@0 3926 var markers = line.gutterMarkers || (line.gutterMarkers = {});
michael@0 3927 markers[gutterID] = value;
michael@0 3928 if (!value && isEmpty(markers)) line.gutterMarkers = null;
michael@0 3929 return true;
michael@0 3930 });
michael@0 3931 }),
michael@0 3932
michael@0 3933 clearGutter: methodOp(function(gutterID) {
michael@0 3934 var cm = this, doc = cm.doc, i = doc.first;
michael@0 3935 doc.iter(function(line) {
michael@0 3936 if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
michael@0 3937 line.gutterMarkers[gutterID] = null;
michael@0 3938 regLineChange(cm, i, "gutter");
michael@0 3939 if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
michael@0 3940 }
michael@0 3941 ++i;
michael@0 3942 });
michael@0 3943 }),
michael@0 3944
michael@0 3945 addLineClass: methodOp(function(handle, where, cls) {
michael@0 3946 return changeLine(this, handle, "class", function(line) {
michael@0 3947 var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
michael@0 3948 if (!line[prop]) line[prop] = cls;
michael@0 3949 else if (new RegExp("(?:^|\\s)" + cls + "(?:$|\\s)").test(line[prop])) return false;
michael@0 3950 else line[prop] += " " + cls;
michael@0 3951 return true;
michael@0 3952 });
michael@0 3953 }),
michael@0 3954
michael@0 3955 removeLineClass: methodOp(function(handle, where, cls) {
michael@0 3956 return changeLine(this, handle, "class", function(line) {
michael@0 3957 var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
michael@0 3958 var cur = line[prop];
michael@0 3959 if (!cur) return false;
michael@0 3960 else if (cls == null) line[prop] = null;
michael@0 3961 else {
michael@0 3962 var found = cur.match(new RegExp("(?:^|\\s+)" + cls + "(?:$|\\s+)"));
michael@0 3963 if (!found) return false;
michael@0 3964 var end = found.index + found[0].length;
michael@0 3965 line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
michael@0 3966 }
michael@0 3967 return true;
michael@0 3968 });
michael@0 3969 }),
michael@0 3970
michael@0 3971 addLineWidget: methodOp(function(handle, node, options) {
michael@0 3972 return addLineWidget(this, handle, node, options);
michael@0 3973 }),
michael@0 3974
michael@0 3975 removeLineWidget: function(widget) { widget.clear(); },
michael@0 3976
michael@0 3977 lineInfo: function(line) {
michael@0 3978 if (typeof line == "number") {
michael@0 3979 if (!isLine(this.doc, line)) return null;
michael@0 3980 var n = line;
michael@0 3981 line = getLine(this.doc, line);
michael@0 3982 if (!line) return null;
michael@0 3983 } else {
michael@0 3984 var n = lineNo(line);
michael@0 3985 if (n == null) return null;
michael@0 3986 }
michael@0 3987 return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
michael@0 3988 textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
michael@0 3989 widgets: line.widgets};
michael@0 3990 },
michael@0 3991
michael@0 3992 getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
michael@0 3993
michael@0 3994 addWidget: function(pos, node, scroll, vert, horiz) {
michael@0 3995 var display = this.display;
michael@0 3996 pos = cursorCoords(this, clipPos(this.doc, pos));
michael@0 3997 var top = pos.bottom, left = pos.left;
michael@0 3998 node.style.position = "absolute";
michael@0 3999 display.sizer.appendChild(node);
michael@0 4000 if (vert == "over") {
michael@0 4001 top = pos.top;
michael@0 4002 } else if (vert == "above" || vert == "near") {
michael@0 4003 var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
michael@0 4004 hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
michael@0 4005 // Default to positioning above (if specified and possible); otherwise default to positioning below
michael@0 4006 if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
michael@0 4007 top = pos.top - node.offsetHeight;
michael@0 4008 else if (pos.bottom + node.offsetHeight <= vspace)
michael@0 4009 top = pos.bottom;
michael@0 4010 if (left + node.offsetWidth > hspace)
michael@0 4011 left = hspace - node.offsetWidth;
michael@0 4012 }
michael@0 4013 node.style.top = top + "px";
michael@0 4014 node.style.left = node.style.right = "";
michael@0 4015 if (horiz == "right") {
michael@0 4016 left = display.sizer.clientWidth - node.offsetWidth;
michael@0 4017 node.style.right = "0px";
michael@0 4018 } else {
michael@0 4019 if (horiz == "left") left = 0;
michael@0 4020 else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
michael@0 4021 node.style.left = left + "px";
michael@0 4022 }
michael@0 4023 if (scroll)
michael@0 4024 scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
michael@0 4025 },
michael@0 4026
michael@0 4027 triggerOnKeyDown: methodOp(onKeyDown),
michael@0 4028 triggerOnKeyPress: methodOp(onKeyPress),
michael@0 4029 triggerOnKeyUp: methodOp(onKeyUp),
michael@0 4030
michael@0 4031 execCommand: function(cmd) {
michael@0 4032 if (commands.hasOwnProperty(cmd))
michael@0 4033 return commands[cmd](this);
michael@0 4034 },
michael@0 4035
michael@0 4036 findPosH: function(from, amount, unit, visually) {
michael@0 4037 var dir = 1;
michael@0 4038 if (amount < 0) { dir = -1; amount = -amount; }
michael@0 4039 for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
michael@0 4040 cur = findPosH(this.doc, cur, dir, unit, visually);
michael@0 4041 if (cur.hitSide) break;
michael@0 4042 }
michael@0 4043 return cur;
michael@0 4044 },
michael@0 4045
michael@0 4046 moveH: methodOp(function(dir, unit) {
michael@0 4047 var cm = this;
michael@0 4048 cm.extendSelectionsBy(function(range) {
michael@0 4049 if (cm.display.shift || cm.doc.extend || range.empty())
michael@0 4050 return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
michael@0 4051 else
michael@0 4052 return dir < 0 ? range.from() : range.to();
michael@0 4053 }, sel_move);
michael@0 4054 }),
michael@0 4055
michael@0 4056 deleteH: methodOp(function(dir, unit) {
michael@0 4057 var sel = this.doc.sel, doc = this.doc;
michael@0 4058 if (sel.somethingSelected())
michael@0 4059 doc.replaceSelection("", null, "+delete");
michael@0 4060 else
michael@0 4061 deleteNearSelection(this, function(range) {
michael@0 4062 var other = findPosH(doc, range.head, dir, unit, false);
michael@0 4063 return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
michael@0 4064 });
michael@0 4065 }),
michael@0 4066
michael@0 4067 findPosV: function(from, amount, unit, goalColumn) {
michael@0 4068 var dir = 1, x = goalColumn;
michael@0 4069 if (amount < 0) { dir = -1; amount = -amount; }
michael@0 4070 for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
michael@0 4071 var coords = cursorCoords(this, cur, "div");
michael@0 4072 if (x == null) x = coords.left;
michael@0 4073 else coords.left = x;
michael@0 4074 cur = findPosV(this, coords, dir, unit);
michael@0 4075 if (cur.hitSide) break;
michael@0 4076 }
michael@0 4077 return cur;
michael@0 4078 },
michael@0 4079
michael@0 4080 moveV: methodOp(function(dir, unit) {
michael@0 4081 var cm = this, doc = this.doc, goals = [];
michael@0 4082 var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
michael@0 4083 doc.extendSelectionsBy(function(range) {
michael@0 4084 if (collapse)
michael@0 4085 return dir < 0 ? range.from() : range.to();
michael@0 4086 var headPos = cursorCoords(cm, range.head, "div");
michael@0 4087 if (range.goalColumn != null) headPos.left = range.goalColumn;
michael@0 4088 goals.push(headPos.left);
michael@0 4089 var pos = findPosV(cm, headPos, dir, unit);
michael@0 4090 if (unit == "page" && range == doc.sel.primary())
michael@0 4091 addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
michael@0 4092 return pos;
michael@0 4093 }, sel_move);
michael@0 4094 if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
michael@0 4095 doc.sel.ranges[i].goalColumn = goals[i];
michael@0 4096 }),
michael@0 4097
michael@0 4098 toggleOverwrite: function(value) {
michael@0 4099 if (value != null && value == this.state.overwrite) return;
michael@0 4100 if (this.state.overwrite = !this.state.overwrite)
michael@0 4101 this.display.cursorDiv.className += " CodeMirror-overwrite";
michael@0 4102 else
michael@0 4103 this.display.cursorDiv.className = this.display.cursorDiv.className.replace(" CodeMirror-overwrite", "");
michael@0 4104
michael@0 4105 signal(this, "overwriteToggle", this, this.state.overwrite);
michael@0 4106 },
michael@0 4107 hasFocus: function() { return activeElt() == this.display.input; },
michael@0 4108
michael@0 4109 scrollTo: methodOp(function(x, y) {
michael@0 4110 if (x != null || y != null) resolveScrollToPos(this);
michael@0 4111 if (x != null) this.curOp.scrollLeft = x;
michael@0 4112 if (y != null) this.curOp.scrollTop = y;
michael@0 4113 }),
michael@0 4114 getScrollInfo: function() {
michael@0 4115 var scroller = this.display.scroller, co = scrollerCutOff;
michael@0 4116 return {left: scroller.scrollLeft, top: scroller.scrollTop,
michael@0 4117 height: scroller.scrollHeight - co, width: scroller.scrollWidth - co,
michael@0 4118 clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co};
michael@0 4119 },
michael@0 4120
michael@0 4121 scrollIntoView: methodOp(function(range, margin) {
michael@0 4122 if (range == null) {
michael@0 4123 range = {from: this.doc.sel.primary().head, to: null};
michael@0 4124 if (margin == null) margin = this.options.cursorScrollMargin;
michael@0 4125 } else if (typeof range == "number") {
michael@0 4126 range = {from: Pos(range, 0), to: null};
michael@0 4127 } else if (range.from == null) {
michael@0 4128 range = {from: range, to: null};
michael@0 4129 }
michael@0 4130 if (!range.to) range.to = range.from;
michael@0 4131 range.margin = margin || 0;
michael@0 4132
michael@0 4133 if (range.from.line != null) {
michael@0 4134 resolveScrollToPos(this);
michael@0 4135 this.curOp.scrollToPos = range;
michael@0 4136 } else {
michael@0 4137 var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
michael@0 4138 Math.min(range.from.top, range.to.top) - range.margin,
michael@0 4139 Math.max(range.from.right, range.to.right),
michael@0 4140 Math.max(range.from.bottom, range.to.bottom) + range.margin);
michael@0 4141 this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
michael@0 4142 }
michael@0 4143 }),
michael@0 4144
michael@0 4145 setSize: methodOp(function(width, height) {
michael@0 4146 function interpret(val) {
michael@0 4147 return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
michael@0 4148 }
michael@0 4149 if (width != null) this.display.wrapper.style.width = interpret(width);
michael@0 4150 if (height != null) this.display.wrapper.style.height = interpret(height);
michael@0 4151 if (this.options.lineWrapping) clearLineMeasurementCache(this);
michael@0 4152 this.curOp.forceUpdate = true;
michael@0 4153 signal(this, "refresh", this);
michael@0 4154 }),
michael@0 4155
michael@0 4156 operation: function(f){return runInOp(this, f);},
michael@0 4157
michael@0 4158 refresh: methodOp(function() {
michael@0 4159 var oldHeight = this.display.cachedTextHeight;
michael@0 4160 regChange(this);
michael@0 4161 clearCaches(this);
michael@0 4162 this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
michael@0 4163 if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
michael@0 4164 estimateLineHeights(this);
michael@0 4165 signal(this, "refresh", this);
michael@0 4166 }),
michael@0 4167
michael@0 4168 swapDoc: methodOp(function(doc) {
michael@0 4169 var old = this.doc;
michael@0 4170 old.cm = null;
michael@0 4171 attachDoc(this, doc);
michael@0 4172 clearCaches(this);
michael@0 4173 resetInput(this);
michael@0 4174 this.scrollTo(doc.scrollLeft, doc.scrollTop);
michael@0 4175 signalLater(this, "swapDoc", this, old);
michael@0 4176 return old;
michael@0 4177 }),
michael@0 4178
michael@0 4179 getInputField: function(){return this.display.input;},
michael@0 4180 getWrapperElement: function(){return this.display.wrapper;},
michael@0 4181 getScrollerElement: function(){return this.display.scroller;},
michael@0 4182 getGutterElement: function(){return this.display.gutters;}
michael@0 4183 };
michael@0 4184 eventMixin(CodeMirror);
michael@0 4185
michael@0 4186 // OPTION DEFAULTS
michael@0 4187
michael@0 4188 // The default configuration options.
michael@0 4189 var defaults = CodeMirror.defaults = {};
michael@0 4190 // Functions to run when options are changed.
michael@0 4191 var optionHandlers = CodeMirror.optionHandlers = {};
michael@0 4192
michael@0 4193 function option(name, deflt, handle, notOnInit) {
michael@0 4194 CodeMirror.defaults[name] = deflt;
michael@0 4195 if (handle) optionHandlers[name] =
michael@0 4196 notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
michael@0 4197 }
michael@0 4198
michael@0 4199 // Passed to option handlers when there is no old value.
michael@0 4200 var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
michael@0 4201
michael@0 4202 // These two are, on init, called from the constructor because they
michael@0 4203 // have to be initialized before the editor can start at all.
michael@0 4204 option("value", "", function(cm, val) {
michael@0 4205 cm.setValue(val);
michael@0 4206 }, true);
michael@0 4207 option("mode", null, function(cm, val) {
michael@0 4208 cm.doc.modeOption = val;
michael@0 4209 loadMode(cm);
michael@0 4210 }, true);
michael@0 4211
michael@0 4212 option("indentUnit", 2, loadMode, true);
michael@0 4213 option("indentWithTabs", false);
michael@0 4214 option("smartIndent", true);
michael@0 4215 option("tabSize", 4, function(cm) {
michael@0 4216 resetModeState(cm);
michael@0 4217 clearCaches(cm);
michael@0 4218 regChange(cm);
michael@0 4219 }, true);
michael@0 4220 option("specialChars", /[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\ufeff]/g, function(cm, val) {
michael@0 4221 cm.options.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
michael@0 4222 cm.refresh();
michael@0 4223 }, true);
michael@0 4224 option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
michael@0 4225 option("electricChars", true);
michael@0 4226 option("rtlMoveVisually", !windows);
michael@0 4227 option("wholeLineUpdateBefore", true);
michael@0 4228
michael@0 4229 option("theme", "default", function(cm) {
michael@0 4230 themeChanged(cm);
michael@0 4231 guttersChanged(cm);
michael@0 4232 }, true);
michael@0 4233 option("keyMap", "default", keyMapChanged);
michael@0 4234 option("extraKeys", null);
michael@0 4235
michael@0 4236 option("lineWrapping", false, wrappingChanged, true);
michael@0 4237 option("gutters", [], function(cm) {
michael@0 4238 setGuttersForLineNumbers(cm.options);
michael@0 4239 guttersChanged(cm);
michael@0 4240 }, true);
michael@0 4241 option("fixedGutter", true, function(cm, val) {
michael@0 4242 cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
michael@0 4243 cm.refresh();
michael@0 4244 }, true);
michael@0 4245 option("coverGutterNextToScrollbar", false, updateScrollbars, true);
michael@0 4246 option("lineNumbers", false, function(cm) {
michael@0 4247 setGuttersForLineNumbers(cm.options);
michael@0 4248 guttersChanged(cm);
michael@0 4249 }, true);
michael@0 4250 option("firstLineNumber", 1, guttersChanged, true);
michael@0 4251 option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
michael@0 4252 option("showCursorWhenSelecting", false, updateSelection, true);
michael@0 4253
michael@0 4254 option("resetSelectionOnContextMenu", true);
michael@0 4255
michael@0 4256 option("readOnly", false, function(cm, val) {
michael@0 4257 if (val == "nocursor") {
michael@0 4258 onBlur(cm);
michael@0 4259 cm.display.input.blur();
michael@0 4260 cm.display.disabled = true;
michael@0 4261 } else {
michael@0 4262 cm.display.disabled = false;
michael@0 4263 if (!val) resetInput(cm);
michael@0 4264 }
michael@0 4265 });
michael@0 4266 option("disableInput", false, function(cm, val) {if (!val) resetInput(cm);}, true);
michael@0 4267 option("dragDrop", true);
michael@0 4268
michael@0 4269 option("cursorBlinkRate", 530);
michael@0 4270 option("cursorScrollMargin", 0);
michael@0 4271 option("cursorHeight", 1);
michael@0 4272 option("workTime", 100);
michael@0 4273 option("workDelay", 100);
michael@0 4274 option("flattenSpans", true, resetModeState, true);
michael@0 4275 option("addModeClass", false, resetModeState, true);
michael@0 4276 option("pollInterval", 100);
michael@0 4277 option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
michael@0 4278 option("historyEventDelay", 1250);
michael@0 4279 option("viewportMargin", 10, function(cm){cm.refresh();}, true);
michael@0 4280 option("maxHighlightLength", 10000, resetModeState, true);
michael@0 4281 option("moveInputWithCursor", true, function(cm, val) {
michael@0 4282 if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0;
michael@0 4283 });
michael@0 4284
michael@0 4285 option("tabindex", null, function(cm, val) {
michael@0 4286 cm.display.input.tabIndex = val || "";
michael@0 4287 });
michael@0 4288 option("autofocus", null);
michael@0 4289
michael@0 4290 // MODE DEFINITION AND QUERYING
michael@0 4291
michael@0 4292 // Known modes, by name and by MIME
michael@0 4293 var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
michael@0 4294
michael@0 4295 // Extra arguments are stored as the mode's dependencies, which is
michael@0 4296 // used by (legacy) mechanisms like loadmode.js to automatically
michael@0 4297 // load a mode. (Preferred mechanism is the require/define calls.)
michael@0 4298 CodeMirror.defineMode = function(name, mode) {
michael@0 4299 if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
michael@0 4300 if (arguments.length > 2) {
michael@0 4301 mode.dependencies = [];
michael@0 4302 for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
michael@0 4303 }
michael@0 4304 modes[name] = mode;
michael@0 4305 };
michael@0 4306
michael@0 4307 CodeMirror.defineMIME = function(mime, spec) {
michael@0 4308 mimeModes[mime] = spec;
michael@0 4309 };
michael@0 4310
michael@0 4311 // Given a MIME type, a {name, ...options} config object, or a name
michael@0 4312 // string, return a mode config object.
michael@0 4313 CodeMirror.resolveMode = function(spec) {
michael@0 4314 if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
michael@0 4315 spec = mimeModes[spec];
michael@0 4316 } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
michael@0 4317 var found = mimeModes[spec.name];
michael@0 4318 if (typeof found == "string") found = {name: found};
michael@0 4319 spec = createObj(found, spec);
michael@0 4320 spec.name = found.name;
michael@0 4321 } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
michael@0 4322 return CodeMirror.resolveMode("application/xml");
michael@0 4323 }
michael@0 4324 if (typeof spec == "string") return {name: spec};
michael@0 4325 else return spec || {name: "null"};
michael@0 4326 };
michael@0 4327
michael@0 4328 // Given a mode spec (anything that resolveMode accepts), find and
michael@0 4329 // initialize an actual mode object.
michael@0 4330 CodeMirror.getMode = function(options, spec) {
michael@0 4331 var spec = CodeMirror.resolveMode(spec);
michael@0 4332 var mfactory = modes[spec.name];
michael@0 4333 if (!mfactory) return CodeMirror.getMode(options, "text/plain");
michael@0 4334 var modeObj = mfactory(options, spec);
michael@0 4335 if (modeExtensions.hasOwnProperty(spec.name)) {
michael@0 4336 var exts = modeExtensions[spec.name];
michael@0 4337 for (var prop in exts) {
michael@0 4338 if (!exts.hasOwnProperty(prop)) continue;
michael@0 4339 if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
michael@0 4340 modeObj[prop] = exts[prop];
michael@0 4341 }
michael@0 4342 }
michael@0 4343 modeObj.name = spec.name;
michael@0 4344 if (spec.helperType) modeObj.helperType = spec.helperType;
michael@0 4345 if (spec.modeProps) for (var prop in spec.modeProps)
michael@0 4346 modeObj[prop] = spec.modeProps[prop];
michael@0 4347
michael@0 4348 return modeObj;
michael@0 4349 };
michael@0 4350
michael@0 4351 // Minimal default mode.
michael@0 4352 CodeMirror.defineMode("null", function() {
michael@0 4353 return {token: function(stream) {stream.skipToEnd();}};
michael@0 4354 });
michael@0 4355 CodeMirror.defineMIME("text/plain", "null");
michael@0 4356
michael@0 4357 // This can be used to attach properties to mode objects from
michael@0 4358 // outside the actual mode definition.
michael@0 4359 var modeExtensions = CodeMirror.modeExtensions = {};
michael@0 4360 CodeMirror.extendMode = function(mode, properties) {
michael@0 4361 var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
michael@0 4362 copyObj(properties, exts);
michael@0 4363 };
michael@0 4364
michael@0 4365 // EXTENSIONS
michael@0 4366
michael@0 4367 CodeMirror.defineExtension = function(name, func) {
michael@0 4368 CodeMirror.prototype[name] = func;
michael@0 4369 };
michael@0 4370 CodeMirror.defineDocExtension = function(name, func) {
michael@0 4371 Doc.prototype[name] = func;
michael@0 4372 };
michael@0 4373 CodeMirror.defineOption = option;
michael@0 4374
michael@0 4375 var initHooks = [];
michael@0 4376 CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
michael@0 4377
michael@0 4378 var helpers = CodeMirror.helpers = {};
michael@0 4379 CodeMirror.registerHelper = function(type, name, value) {
michael@0 4380 if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
michael@0 4381 helpers[type][name] = value;
michael@0 4382 };
michael@0 4383 CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
michael@0 4384 CodeMirror.registerHelper(type, name, value);
michael@0 4385 helpers[type]._global.push({pred: predicate, val: value});
michael@0 4386 };
michael@0 4387
michael@0 4388 // MODE STATE HANDLING
michael@0 4389
michael@0 4390 // Utility functions for working with state. Exported because nested
michael@0 4391 // modes need to do this for their inner modes.
michael@0 4392
michael@0 4393 var copyState = CodeMirror.copyState = function(mode, state) {
michael@0 4394 if (state === true) return state;
michael@0 4395 if (mode.copyState) return mode.copyState(state);
michael@0 4396 var nstate = {};
michael@0 4397 for (var n in state) {
michael@0 4398 var val = state[n];
michael@0 4399 if (val instanceof Array) val = val.concat([]);
michael@0 4400 nstate[n] = val;
michael@0 4401 }
michael@0 4402 return nstate;
michael@0 4403 };
michael@0 4404
michael@0 4405 var startState = CodeMirror.startState = function(mode, a1, a2) {
michael@0 4406 return mode.startState ? mode.startState(a1, a2) : true;
michael@0 4407 };
michael@0 4408
michael@0 4409 // Given a mode and a state (for that mode), find the inner mode and
michael@0 4410 // state at the position that the state refers to.
michael@0 4411 CodeMirror.innerMode = function(mode, state) {
michael@0 4412 while (mode.innerMode) {
michael@0 4413 var info = mode.innerMode(state);
michael@0 4414 if (!info || info.mode == mode) break;
michael@0 4415 state = info.state;
michael@0 4416 mode = info.mode;
michael@0 4417 }
michael@0 4418 return info || {mode: mode, state: state};
michael@0 4419 };
michael@0 4420
michael@0 4421 // STANDARD COMMANDS
michael@0 4422
michael@0 4423 // Commands are parameter-less actions that can be performed on an
michael@0 4424 // editor, mostly used for keybindings.
michael@0 4425 var commands = CodeMirror.commands = {
michael@0 4426 selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
michael@0 4427 singleSelection: function(cm) {
michael@0 4428 cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
michael@0 4429 },
michael@0 4430 killLine: function(cm) {
michael@0 4431 deleteNearSelection(cm, function(range) {
michael@0 4432 if (range.empty()) {
michael@0 4433 var len = getLine(cm.doc, range.head.line).text.length;
michael@0 4434 if (range.head.ch == len && range.head.line < cm.lastLine())
michael@0 4435 return {from: range.head, to: Pos(range.head.line + 1, 0)};
michael@0 4436 else
michael@0 4437 return {from: range.head, to: Pos(range.head.line, len)};
michael@0 4438 } else {
michael@0 4439 return {from: range.from(), to: range.to()};
michael@0 4440 }
michael@0 4441 });
michael@0 4442 },
michael@0 4443 deleteLine: function(cm) {
michael@0 4444 deleteNearSelection(cm, function(range) {
michael@0 4445 return {from: Pos(range.from().line, 0),
michael@0 4446 to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
michael@0 4447 });
michael@0 4448 },
michael@0 4449 delLineLeft: function(cm) {
michael@0 4450 deleteNearSelection(cm, function(range) {
michael@0 4451 return {from: Pos(range.from().line, 0), to: range.from()};
michael@0 4452 });
michael@0 4453 },
michael@0 4454 undo: function(cm) {cm.undo();},
michael@0 4455 redo: function(cm) {cm.redo();},
michael@0 4456 undoSelection: function(cm) {cm.undoSelection();},
michael@0 4457 redoSelection: function(cm) {cm.redoSelection();},
michael@0 4458 goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
michael@0 4459 goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
michael@0 4460 goLineStart: function(cm) {
michael@0 4461 cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); }, sel_move);
michael@0 4462 },
michael@0 4463 goLineStartSmart: function(cm) {
michael@0 4464 cm.extendSelectionsBy(function(range) {
michael@0 4465 var start = lineStart(cm, range.head.line);
michael@0 4466 var line = cm.getLineHandle(start.line);
michael@0 4467 var order = getOrder(line);
michael@0 4468 if (!order || order[0].level == 0) {
michael@0 4469 var firstNonWS = Math.max(0, line.text.search(/\S/));
michael@0 4470 var inWS = range.head.line == start.line && range.head.ch <= firstNonWS && range.head.ch;
michael@0 4471 return Pos(start.line, inWS ? 0 : firstNonWS);
michael@0 4472 }
michael@0 4473 return start;
michael@0 4474 }, sel_move);
michael@0 4475 },
michael@0 4476 goLineEnd: function(cm) {
michael@0 4477 cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); }, sel_move);
michael@0 4478 },
michael@0 4479 goLineRight: function(cm) {
michael@0 4480 cm.extendSelectionsBy(function(range) {
michael@0 4481 var top = cm.charCoords(range.head, "div").top + 5;
michael@0 4482 return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
michael@0 4483 }, sel_move);
michael@0 4484 },
michael@0 4485 goLineLeft: function(cm) {
michael@0 4486 cm.extendSelectionsBy(function(range) {
michael@0 4487 var top = cm.charCoords(range.head, "div").top + 5;
michael@0 4488 return cm.coordsChar({left: 0, top: top}, "div");
michael@0 4489 }, sel_move);
michael@0 4490 },
michael@0 4491 goLineUp: function(cm) {cm.moveV(-1, "line");},
michael@0 4492 goLineDown: function(cm) {cm.moveV(1, "line");},
michael@0 4493 goPageUp: function(cm) {cm.moveV(-1, "page");},
michael@0 4494 goPageDown: function(cm) {cm.moveV(1, "page");},
michael@0 4495 goCharLeft: function(cm) {cm.moveH(-1, "char");},
michael@0 4496 goCharRight: function(cm) {cm.moveH(1, "char");},
michael@0 4497 goColumnLeft: function(cm) {cm.moveH(-1, "column");},
michael@0 4498 goColumnRight: function(cm) {cm.moveH(1, "column");},
michael@0 4499 goWordLeft: function(cm) {cm.moveH(-1, "word");},
michael@0 4500 goGroupRight: function(cm) {cm.moveH(1, "group");},
michael@0 4501 goGroupLeft: function(cm) {cm.moveH(-1, "group");},
michael@0 4502 goWordRight: function(cm) {cm.moveH(1, "word");},
michael@0 4503 delCharBefore: function(cm) {cm.deleteH(-1, "char");},
michael@0 4504 delCharAfter: function(cm) {cm.deleteH(1, "char");},
michael@0 4505 delWordBefore: function(cm) {cm.deleteH(-1, "word");},
michael@0 4506 delWordAfter: function(cm) {cm.deleteH(1, "word");},
michael@0 4507 delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
michael@0 4508 delGroupAfter: function(cm) {cm.deleteH(1, "group");},
michael@0 4509 indentAuto: function(cm) {cm.indentSelection("smart");},
michael@0 4510 indentMore: function(cm) {cm.indentSelection("add");},
michael@0 4511 indentLess: function(cm) {cm.indentSelection("subtract");},
michael@0 4512 insertTab: function(cm) {cm.replaceSelection("\t");},
michael@0 4513 defaultTab: function(cm) {
michael@0 4514 if (cm.somethingSelected()) cm.indentSelection("add");
michael@0 4515 else cm.execCommand("insertTab");
michael@0 4516 },
michael@0 4517 transposeChars: function(cm) {
michael@0 4518 runInOp(cm, function() {
michael@0 4519 var ranges = cm.listSelections();
michael@0 4520 for (var i = 0; i < ranges.length; i++) {
michael@0 4521 var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
michael@0 4522 if (cur.ch > 0 && cur.ch < line.length - 1)
michael@0 4523 cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1),
michael@0 4524 Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1));
michael@0 4525 }
michael@0 4526 });
michael@0 4527 },
michael@0 4528 newlineAndIndent: function(cm) {
michael@0 4529 runInOp(cm, function() {
michael@0 4530 var len = cm.listSelections().length;
michael@0 4531 for (var i = 0; i < len; i++) {
michael@0 4532 var range = cm.listSelections()[i];
michael@0 4533 cm.replaceRange("\n", range.anchor, range.head, "+input");
michael@0 4534 cm.indentLine(range.from().line + 1, null, true);
michael@0 4535 ensureCursorVisible(cm);
michael@0 4536 }
michael@0 4537 });
michael@0 4538 },
michael@0 4539 toggleOverwrite: function(cm) {cm.toggleOverwrite();}
michael@0 4540 };
michael@0 4541
michael@0 4542 // STANDARD KEYMAPS
michael@0 4543
michael@0 4544 var keyMap = CodeMirror.keyMap = {};
michael@0 4545 keyMap.basic = {
michael@0 4546 "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
michael@0 4547 "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
michael@0 4548 "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
michael@0 4549 "Tab": "defaultTab", "Shift-Tab": "indentAuto",
michael@0 4550 "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
michael@0 4551 "Esc": "singleSelection"
michael@0 4552 };
michael@0 4553 // Note that the save and find-related commands aren't defined by
michael@0 4554 // default. User code or addons can define them. Unknown commands
michael@0 4555 // are simply ignored.
michael@0 4556 keyMap.pcDefault = {
michael@0 4557 "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
michael@0 4558 "Ctrl-Home": "goDocStart", "Ctrl-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
michael@0 4559 "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
michael@0 4560 "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
michael@0 4561 "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
michael@0 4562 "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
michael@0 4563 "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
michael@0 4564 fallthrough: "basic"
michael@0 4565 };
michael@0 4566 keyMap.macDefault = {
michael@0 4567 "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
michael@0 4568 "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
michael@0 4569 "Alt-Right": "goGroupRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delGroupBefore",
michael@0 4570 "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
michael@0 4571 "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
michael@0 4572 "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delLineLeft",
michael@0 4573 "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection",
michael@0 4574 fallthrough: ["basic", "emacsy"]
michael@0 4575 };
michael@0 4576 // Very basic readline/emacs-style bindings, which are standard on Mac.
michael@0 4577 keyMap.emacsy = {
michael@0 4578 "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
michael@0 4579 "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
michael@0 4580 "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
michael@0 4581 "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
michael@0 4582 };
michael@0 4583 keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
michael@0 4584
michael@0 4585 // KEYMAP DISPATCH
michael@0 4586
michael@0 4587 function getKeyMap(val) {
michael@0 4588 if (typeof val == "string") return keyMap[val];
michael@0 4589 else return val;
michael@0 4590 }
michael@0 4591
michael@0 4592 // Given an array of keymaps and a key name, call handle on any
michael@0 4593 // bindings found, until that returns a truthy value, at which point
michael@0 4594 // we consider the key handled. Implements things like binding a key
michael@0 4595 // to false stopping further handling and keymap fallthrough.
michael@0 4596 var lookupKey = CodeMirror.lookupKey = function(name, maps, handle) {
michael@0 4597 function lookup(map) {
michael@0 4598 map = getKeyMap(map);
michael@0 4599 var found = map[name];
michael@0 4600 if (found === false) return "stop";
michael@0 4601 if (found != null && handle(found)) return true;
michael@0 4602 if (map.nofallthrough) return "stop";
michael@0 4603
michael@0 4604 var fallthrough = map.fallthrough;
michael@0 4605 if (fallthrough == null) return false;
michael@0 4606 if (Object.prototype.toString.call(fallthrough) != "[object Array]")
michael@0 4607 return lookup(fallthrough);
michael@0 4608 for (var i = 0; i < fallthrough.length; ++i) {
michael@0 4609 var done = lookup(fallthrough[i]);
michael@0 4610 if (done) return done;
michael@0 4611 }
michael@0 4612 return false;
michael@0 4613 }
michael@0 4614
michael@0 4615 for (var i = 0; i < maps.length; ++i) {
michael@0 4616 var done = lookup(maps[i]);
michael@0 4617 if (done) return done != "stop";
michael@0 4618 }
michael@0 4619 };
michael@0 4620
michael@0 4621 // Modifier key presses don't count as 'real' key presses for the
michael@0 4622 // purpose of keymap fallthrough.
michael@0 4623 var isModifierKey = CodeMirror.isModifierKey = function(event) {
michael@0 4624 var name = keyNames[event.keyCode];
michael@0 4625 return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
michael@0 4626 };
michael@0 4627
michael@0 4628 // Look up the name of a key as indicated by an event object.
michael@0 4629 var keyName = CodeMirror.keyName = function(event, noShift) {
michael@0 4630 if (presto && event.keyCode == 34 && event["char"]) return false;
michael@0 4631 var name = keyNames[event.keyCode];
michael@0 4632 if (name == null || event.altGraphKey) return false;
michael@0 4633 if (event.altKey) name = "Alt-" + name;
michael@0 4634 if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name;
michael@0 4635 if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name;
michael@0 4636 if (!noShift && event.shiftKey) name = "Shift-" + name;
michael@0 4637 return name;
michael@0 4638 };
michael@0 4639
michael@0 4640 // FROMTEXTAREA
michael@0 4641
michael@0 4642 CodeMirror.fromTextArea = function(textarea, options) {
michael@0 4643 if (!options) options = {};
michael@0 4644 options.value = textarea.value;
michael@0 4645 if (!options.tabindex && textarea.tabindex)
michael@0 4646 options.tabindex = textarea.tabindex;
michael@0 4647 if (!options.placeholder && textarea.placeholder)
michael@0 4648 options.placeholder = textarea.placeholder;
michael@0 4649 // Set autofocus to true if this textarea is focused, or if it has
michael@0 4650 // autofocus and no other element is focused.
michael@0 4651 if (options.autofocus == null) {
michael@0 4652 var hasFocus = activeElt();
michael@0 4653 options.autofocus = hasFocus == textarea ||
michael@0 4654 textarea.getAttribute("autofocus") != null && hasFocus == document.body;
michael@0 4655 }
michael@0 4656
michael@0 4657 function save() {textarea.value = cm.getValue();}
michael@0 4658 if (textarea.form) {
michael@0 4659 on(textarea.form, "submit", save);
michael@0 4660 // Deplorable hack to make the submit method do the right thing.
michael@0 4661 if (!options.leaveSubmitMethodAlone) {
michael@0 4662 var form = textarea.form, realSubmit = form.submit;
michael@0 4663 try {
michael@0 4664 var wrappedSubmit = form.submit = function() {
michael@0 4665 save();
michael@0 4666 form.submit = realSubmit;
michael@0 4667 form.submit();
michael@0 4668 form.submit = wrappedSubmit;
michael@0 4669 };
michael@0 4670 } catch(e) {}
michael@0 4671 }
michael@0 4672 }
michael@0 4673
michael@0 4674 textarea.style.display = "none";
michael@0 4675 var cm = CodeMirror(function(node) {
michael@0 4676 textarea.parentNode.insertBefore(node, textarea.nextSibling);
michael@0 4677 }, options);
michael@0 4678 cm.save = save;
michael@0 4679 cm.getTextArea = function() { return textarea; };
michael@0 4680 cm.toTextArea = function() {
michael@0 4681 save();
michael@0 4682 textarea.parentNode.removeChild(cm.getWrapperElement());
michael@0 4683 textarea.style.display = "";
michael@0 4684 if (textarea.form) {
michael@0 4685 off(textarea.form, "submit", save);
michael@0 4686 if (typeof textarea.form.submit == "function")
michael@0 4687 textarea.form.submit = realSubmit;
michael@0 4688 }
michael@0 4689 };
michael@0 4690 return cm;
michael@0 4691 };
michael@0 4692
michael@0 4693 // STRING STREAM
michael@0 4694
michael@0 4695 // Fed to the mode parsers, provides helper functions to make
michael@0 4696 // parsers more succinct.
michael@0 4697
michael@0 4698 var StringStream = CodeMirror.StringStream = function(string, tabSize) {
michael@0 4699 this.pos = this.start = 0;
michael@0 4700 this.string = string;
michael@0 4701 this.tabSize = tabSize || 8;
michael@0 4702 this.lastColumnPos = this.lastColumnValue = 0;
michael@0 4703 this.lineStart = 0;
michael@0 4704 };
michael@0 4705
michael@0 4706 StringStream.prototype = {
michael@0 4707 eol: function() {return this.pos >= this.string.length;},
michael@0 4708 sol: function() {return this.pos == this.lineStart;},
michael@0 4709 peek: function() {return this.string.charAt(this.pos) || undefined;},
michael@0 4710 next: function() {
michael@0 4711 if (this.pos < this.string.length)
michael@0 4712 return this.string.charAt(this.pos++);
michael@0 4713 },
michael@0 4714 eat: function(match) {
michael@0 4715 var ch = this.string.charAt(this.pos);
michael@0 4716 if (typeof match == "string") var ok = ch == match;
michael@0 4717 else var ok = ch && (match.test ? match.test(ch) : match(ch));
michael@0 4718 if (ok) {++this.pos; return ch;}
michael@0 4719 },
michael@0 4720 eatWhile: function(match) {
michael@0 4721 var start = this.pos;
michael@0 4722 while (this.eat(match)){}
michael@0 4723 return this.pos > start;
michael@0 4724 },
michael@0 4725 eatSpace: function() {
michael@0 4726 var start = this.pos;
michael@0 4727 while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
michael@0 4728 return this.pos > start;
michael@0 4729 },
michael@0 4730 skipToEnd: function() {this.pos = this.string.length;},
michael@0 4731 skipTo: function(ch) {
michael@0 4732 var found = this.string.indexOf(ch, this.pos);
michael@0 4733 if (found > -1) {this.pos = found; return true;}
michael@0 4734 },
michael@0 4735 backUp: function(n) {this.pos -= n;},
michael@0 4736 column: function() {
michael@0 4737 if (this.lastColumnPos < this.start) {
michael@0 4738 this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
michael@0 4739 this.lastColumnPos = this.start;
michael@0 4740 }
michael@0 4741 return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
michael@0 4742 },
michael@0 4743 indentation: function() {
michael@0 4744 return countColumn(this.string, null, this.tabSize) -
michael@0 4745 (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
michael@0 4746 },
michael@0 4747 match: function(pattern, consume, caseInsensitive) {
michael@0 4748 if (typeof pattern == "string") {
michael@0 4749 var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
michael@0 4750 var substr = this.string.substr(this.pos, pattern.length);
michael@0 4751 if (cased(substr) == cased(pattern)) {
michael@0 4752 if (consume !== false) this.pos += pattern.length;
michael@0 4753 return true;
michael@0 4754 }
michael@0 4755 } else {
michael@0 4756 var match = this.string.slice(this.pos).match(pattern);
michael@0 4757 if (match && match.index > 0) return null;
michael@0 4758 if (match && consume !== false) this.pos += match[0].length;
michael@0 4759 return match;
michael@0 4760 }
michael@0 4761 },
michael@0 4762 current: function(){return this.string.slice(this.start, this.pos);},
michael@0 4763 hideFirstChars: function(n, inner) {
michael@0 4764 this.lineStart += n;
michael@0 4765 try { return inner(); }
michael@0 4766 finally { this.lineStart -= n; }
michael@0 4767 }
michael@0 4768 };
michael@0 4769
michael@0 4770 // TEXTMARKERS
michael@0 4771
michael@0 4772 // Created with markText and setBookmark methods. A TextMarker is a
michael@0 4773 // handle that can be used to clear or find a marked position in the
michael@0 4774 // document. Line objects hold arrays (markedSpans) containing
michael@0 4775 // {from, to, marker} object pointing to such marker objects, and
michael@0 4776 // indicating that such a marker is present on that line. Multiple
michael@0 4777 // lines may point to the same marker when it spans across lines.
michael@0 4778 // The spans will have null for their from/to properties when the
michael@0 4779 // marker continues beyond the start/end of the line. Markers have
michael@0 4780 // links back to the lines they currently touch.
michael@0 4781
michael@0 4782 var TextMarker = CodeMirror.TextMarker = function(doc, type) {
michael@0 4783 this.lines = [];
michael@0 4784 this.type = type;
michael@0 4785 this.doc = doc;
michael@0 4786 };
michael@0 4787 eventMixin(TextMarker);
michael@0 4788
michael@0 4789 // Clear the marker.
michael@0 4790 TextMarker.prototype.clear = function() {
michael@0 4791 if (this.explicitlyCleared) return;
michael@0 4792 var cm = this.doc.cm, withOp = cm && !cm.curOp;
michael@0 4793 if (withOp) startOperation(cm);
michael@0 4794 if (hasHandler(this, "clear")) {
michael@0 4795 var found = this.find();
michael@0 4796 if (found) signalLater(this, "clear", found.from, found.to);
michael@0 4797 }
michael@0 4798 var min = null, max = null;
michael@0 4799 for (var i = 0; i < this.lines.length; ++i) {
michael@0 4800 var line = this.lines[i];
michael@0 4801 var span = getMarkedSpanFor(line.markedSpans, this);
michael@0 4802 if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
michael@0 4803 else if (cm) {
michael@0 4804 if (span.to != null) max = lineNo(line);
michael@0 4805 if (span.from != null) min = lineNo(line);
michael@0 4806 }
michael@0 4807 line.markedSpans = removeMarkedSpan(line.markedSpans, span);
michael@0 4808 if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
michael@0 4809 updateLineHeight(line, textHeight(cm.display));
michael@0 4810 }
michael@0 4811 if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
michael@0 4812 var visual = visualLine(this.lines[i]), len = lineLength(visual);
michael@0 4813 if (len > cm.display.maxLineLength) {
michael@0 4814 cm.display.maxLine = visual;
michael@0 4815 cm.display.maxLineLength = len;
michael@0 4816 cm.display.maxLineChanged = true;
michael@0 4817 }
michael@0 4818 }
michael@0 4819
michael@0 4820 if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
michael@0 4821 this.lines.length = 0;
michael@0 4822 this.explicitlyCleared = true;
michael@0 4823 if (this.atomic && this.doc.cantEdit) {
michael@0 4824 this.doc.cantEdit = false;
michael@0 4825 if (cm) reCheckSelection(cm.doc);
michael@0 4826 }
michael@0 4827 if (cm) signalLater(cm, "markerCleared", cm, this);
michael@0 4828 if (withOp) endOperation(cm);
michael@0 4829 };
michael@0 4830
michael@0 4831 // Find the position of the marker in the document. Returns a {from,
michael@0 4832 // to} object by default. Side can be passed to get a specific side
michael@0 4833 // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
michael@0 4834 // Pos objects returned contain a line object, rather than a line
michael@0 4835 // number (used to prevent looking up the same line twice).
michael@0 4836 TextMarker.prototype.find = function(side, lineObj) {
michael@0 4837 if (side == null && this.type == "bookmark") side = 1;
michael@0 4838 var from, to;
michael@0 4839 for (var i = 0; i < this.lines.length; ++i) {
michael@0 4840 var line = this.lines[i];
michael@0 4841 var span = getMarkedSpanFor(line.markedSpans, this);
michael@0 4842 if (span.from != null) {
michael@0 4843 from = Pos(lineObj ? line : lineNo(line), span.from);
michael@0 4844 if (side == -1) return from;
michael@0 4845 }
michael@0 4846 if (span.to != null) {
michael@0 4847 to = Pos(lineObj ? line : lineNo(line), span.to);
michael@0 4848 if (side == 1) return to;
michael@0 4849 }
michael@0 4850 }
michael@0 4851 return from && {from: from, to: to};
michael@0 4852 };
michael@0 4853
michael@0 4854 // Signals that the marker's widget changed, and surrounding layout
michael@0 4855 // should be recomputed.
michael@0 4856 TextMarker.prototype.changed = function() {
michael@0 4857 var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
michael@0 4858 if (!pos || !cm) return;
michael@0 4859 runInOp(cm, function() {
michael@0 4860 var line = pos.line, lineN = lineNo(pos.line);
michael@0 4861 var view = findViewForLine(cm, lineN);
michael@0 4862 if (view) {
michael@0 4863 clearLineMeasurementCacheFor(view);
michael@0 4864 cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
michael@0 4865 }
michael@0 4866 cm.curOp.updateMaxLine = true;
michael@0 4867 if (!lineIsHidden(widget.doc, line) && widget.height != null) {
michael@0 4868 var oldHeight = widget.height;
michael@0 4869 widget.height = null;
michael@0 4870 var dHeight = widgetHeight(widget) - oldHeight;
michael@0 4871 if (dHeight)
michael@0 4872 updateLineHeight(line, line.height + dHeight);
michael@0 4873 }
michael@0 4874 });
michael@0 4875 };
michael@0 4876
michael@0 4877 TextMarker.prototype.attachLine = function(line) {
michael@0 4878 if (!this.lines.length && this.doc.cm) {
michael@0 4879 var op = this.doc.cm.curOp;
michael@0 4880 if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
michael@0 4881 (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
michael@0 4882 }
michael@0 4883 this.lines.push(line);
michael@0 4884 };
michael@0 4885 TextMarker.prototype.detachLine = function(line) {
michael@0 4886 this.lines.splice(indexOf(this.lines, line), 1);
michael@0 4887 if (!this.lines.length && this.doc.cm) {
michael@0 4888 var op = this.doc.cm.curOp;
michael@0 4889 (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
michael@0 4890 }
michael@0 4891 };
michael@0 4892
michael@0 4893 // Collapsed markers have unique ids, in order to be able to order
michael@0 4894 // them, which is needed for uniquely determining an outer marker
michael@0 4895 // when they overlap (they may nest, but not partially overlap).
michael@0 4896 var nextMarkerId = 0;
michael@0 4897
michael@0 4898 // Create a marker, wire it up to the right lines, and
michael@0 4899 function markText(doc, from, to, options, type) {
michael@0 4900 // Shared markers (across linked documents) are handled separately
michael@0 4901 // (markTextShared will call out to this again, once per
michael@0 4902 // document).
michael@0 4903 if (options && options.shared) return markTextShared(doc, from, to, options, type);
michael@0 4904 // Ensure we are in an operation.
michael@0 4905 if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
michael@0 4906
michael@0 4907 var marker = new TextMarker(doc, type), diff = cmp(from, to);
michael@0 4908 if (options) copyObj(options, marker);
michael@0 4909 // Don't connect empty markers unless clearWhenEmpty is false
michael@0 4910 if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
michael@0 4911 return marker;
michael@0 4912 if (marker.replacedWith) {
michael@0 4913 // Showing up as a widget implies collapsed (widget replaces text)
michael@0 4914 marker.collapsed = true;
michael@0 4915 marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
michael@0 4916 if (!options.handleMouseEvents) marker.widgetNode.ignoreEvents = true;
michael@0 4917 if (options.insertLeft) marker.widgetNode.insertLeft = true;
michael@0 4918 }
michael@0 4919 if (marker.collapsed) {
michael@0 4920 if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
michael@0 4921 from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
michael@0 4922 throw new Error("Inserting collapsed marker partially overlapping an existing one");
michael@0 4923 sawCollapsedSpans = true;
michael@0 4924 }
michael@0 4925
michael@0 4926 if (marker.addToHistory)
michael@0 4927 addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
michael@0 4928
michael@0 4929 var curLine = from.line, cm = doc.cm, updateMaxLine;
michael@0 4930 doc.iter(curLine, to.line + 1, function(line) {
michael@0 4931 if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
michael@0 4932 updateMaxLine = true;
michael@0 4933 if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
michael@0 4934 addMarkedSpan(line, new MarkedSpan(marker,
michael@0 4935 curLine == from.line ? from.ch : null,
michael@0 4936 curLine == to.line ? to.ch : null));
michael@0 4937 ++curLine;
michael@0 4938 });
michael@0 4939 // lineIsHidden depends on the presence of the spans, so needs a second pass
michael@0 4940 if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
michael@0 4941 if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
michael@0 4942 });
michael@0 4943
michael@0 4944 if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
michael@0 4945
michael@0 4946 if (marker.readOnly) {
michael@0 4947 sawReadOnlySpans = true;
michael@0 4948 if (doc.history.done.length || doc.history.undone.length)
michael@0 4949 doc.clearHistory();
michael@0 4950 }
michael@0 4951 if (marker.collapsed) {
michael@0 4952 marker.id = ++nextMarkerId;
michael@0 4953 marker.atomic = true;
michael@0 4954 }
michael@0 4955 if (cm) {
michael@0 4956 // Sync editor state
michael@0 4957 if (updateMaxLine) cm.curOp.updateMaxLine = true;
michael@0 4958 if (marker.collapsed)
michael@0 4959 regChange(cm, from.line, to.line + 1);
michael@0 4960 else if (marker.className || marker.title || marker.startStyle || marker.endStyle)
michael@0 4961 for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
michael@0 4962 if (marker.atomic) reCheckSelection(cm.doc);
michael@0 4963 signalLater(cm, "markerAdded", cm, marker);
michael@0 4964 }
michael@0 4965 return marker;
michael@0 4966 }
michael@0 4967
michael@0 4968 // SHARED TEXTMARKERS
michael@0 4969
michael@0 4970 // A shared marker spans multiple linked documents. It is
michael@0 4971 // implemented as a meta-marker-object controlling multiple normal
michael@0 4972 // markers.
michael@0 4973 var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
michael@0 4974 this.markers = markers;
michael@0 4975 this.primary = primary;
michael@0 4976 for (var i = 0, me = this; i < markers.length; ++i) {
michael@0 4977 markers[i].parent = this;
michael@0 4978 on(markers[i], "clear", function(){me.clear();});
michael@0 4979 }
michael@0 4980 };
michael@0 4981 eventMixin(SharedTextMarker);
michael@0 4982
michael@0 4983 SharedTextMarker.prototype.clear = function() {
michael@0 4984 if (this.explicitlyCleared) return;
michael@0 4985 this.explicitlyCleared = true;
michael@0 4986 for (var i = 0; i < this.markers.length; ++i)
michael@0 4987 this.markers[i].clear();
michael@0 4988 signalLater(this, "clear");
michael@0 4989 };
michael@0 4990 SharedTextMarker.prototype.find = function(side, lineObj) {
michael@0 4991 return this.primary.find(side, lineObj);
michael@0 4992 };
michael@0 4993
michael@0 4994 function markTextShared(doc, from, to, options, type) {
michael@0 4995 options = copyObj(options);
michael@0 4996 options.shared = false;
michael@0 4997 var markers = [markText(doc, from, to, options, type)], primary = markers[0];
michael@0 4998 var widget = options.widgetNode;
michael@0 4999 linkedDocs(doc, function(doc) {
michael@0 5000 if (widget) options.widgetNode = widget.cloneNode(true);
michael@0 5001 markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
michael@0 5002 for (var i = 0; i < doc.linked.length; ++i)
michael@0 5003 if (doc.linked[i].isParent) return;
michael@0 5004 primary = lst(markers);
michael@0 5005 });
michael@0 5006 return new SharedTextMarker(markers, primary);
michael@0 5007 }
michael@0 5008
michael@0 5009 // TEXTMARKER SPANS
michael@0 5010
michael@0 5011 function MarkedSpan(marker, from, to) {
michael@0 5012 this.marker = marker;
michael@0 5013 this.from = from; this.to = to;
michael@0 5014 }
michael@0 5015
michael@0 5016 // Search an array of spans for a span matching the given marker.
michael@0 5017 function getMarkedSpanFor(spans, marker) {
michael@0 5018 if (spans) for (var i = 0; i < spans.length; ++i) {
michael@0 5019 var span = spans[i];
michael@0 5020 if (span.marker == marker) return span;
michael@0 5021 }
michael@0 5022 }
michael@0 5023 // Remove a span from an array, returning undefined if no spans are
michael@0 5024 // left (we don't store arrays for lines without spans).
michael@0 5025 function removeMarkedSpan(spans, span) {
michael@0 5026 for (var r, i = 0; i < spans.length; ++i)
michael@0 5027 if (spans[i] != span) (r || (r = [])).push(spans[i]);
michael@0 5028 return r;
michael@0 5029 }
michael@0 5030 // Add a span to a line.
michael@0 5031 function addMarkedSpan(line, span) {
michael@0 5032 line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
michael@0 5033 span.marker.attachLine(line);
michael@0 5034 }
michael@0 5035
michael@0 5036 // Used for the algorithm that adjusts markers for a change in the
michael@0 5037 // document. These functions cut an array of spans at a given
michael@0 5038 // character position, returning an array of remaining chunks (or
michael@0 5039 // undefined if nothing remains).
michael@0 5040 function markedSpansBefore(old, startCh, isInsert) {
michael@0 5041 if (old) for (var i = 0, nw; i < old.length; ++i) {
michael@0 5042 var span = old[i], marker = span.marker;
michael@0 5043 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
michael@0 5044 if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
michael@0 5045 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
michael@0 5046 (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
michael@0 5047 }
michael@0 5048 }
michael@0 5049 return nw;
michael@0 5050 }
michael@0 5051 function markedSpansAfter(old, endCh, isInsert) {
michael@0 5052 if (old) for (var i = 0, nw; i < old.length; ++i) {
michael@0 5053 var span = old[i], marker = span.marker;
michael@0 5054 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
michael@0 5055 if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
michael@0 5056 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
michael@0 5057 (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
michael@0 5058 span.to == null ? null : span.to - endCh));
michael@0 5059 }
michael@0 5060 }
michael@0 5061 return nw;
michael@0 5062 }
michael@0 5063
michael@0 5064 // Given a change object, compute the new set of marker spans that
michael@0 5065 // cover the line in which the change took place. Removes spans
michael@0 5066 // entirely within the change, reconnects spans belonging to the
michael@0 5067 // same marker that appear on both sides of the change, and cuts off
michael@0 5068 // spans partially within the change. Returns an array of span
michael@0 5069 // arrays with one element for each line in (after) the change.
michael@0 5070 function stretchSpansOverChange(doc, change) {
michael@0 5071 var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
michael@0 5072 var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
michael@0 5073 if (!oldFirst && !oldLast) return null;
michael@0 5074
michael@0 5075 var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
michael@0 5076 // Get the spans that 'stick out' on both sides
michael@0 5077 var first = markedSpansBefore(oldFirst, startCh, isInsert);
michael@0 5078 var last = markedSpansAfter(oldLast, endCh, isInsert);
michael@0 5079
michael@0 5080 // Next, merge those two ends
michael@0 5081 var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
michael@0 5082 if (first) {
michael@0 5083 // Fix up .to properties of first
michael@0 5084 for (var i = 0; i < first.length; ++i) {
michael@0 5085 var span = first[i];
michael@0 5086 if (span.to == null) {
michael@0 5087 var found = getMarkedSpanFor(last, span.marker);
michael@0 5088 if (!found) span.to = startCh;
michael@0 5089 else if (sameLine) span.to = found.to == null ? null : found.to + offset;
michael@0 5090 }
michael@0 5091 }
michael@0 5092 }
michael@0 5093 if (last) {
michael@0 5094 // Fix up .from in last (or move them into first in case of sameLine)
michael@0 5095 for (var i = 0; i < last.length; ++i) {
michael@0 5096 var span = last[i];
michael@0 5097 if (span.to != null) span.to += offset;
michael@0 5098 if (span.from == null) {
michael@0 5099 var found = getMarkedSpanFor(first, span.marker);
michael@0 5100 if (!found) {
michael@0 5101 span.from = offset;
michael@0 5102 if (sameLine) (first || (first = [])).push(span);
michael@0 5103 }
michael@0 5104 } else {
michael@0 5105 span.from += offset;
michael@0 5106 if (sameLine) (first || (first = [])).push(span);
michael@0 5107 }
michael@0 5108 }
michael@0 5109 }
michael@0 5110 // Make sure we didn't create any zero-length spans
michael@0 5111 if (first) first = clearEmptySpans(first);
michael@0 5112 if (last && last != first) last = clearEmptySpans(last);
michael@0 5113
michael@0 5114 var newMarkers = [first];
michael@0 5115 if (!sameLine) {
michael@0 5116 // Fill gap with whole-line-spans
michael@0 5117 var gap = change.text.length - 2, gapMarkers;
michael@0 5118 if (gap > 0 && first)
michael@0 5119 for (var i = 0; i < first.length; ++i)
michael@0 5120 if (first[i].to == null)
michael@0 5121 (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
michael@0 5122 for (var i = 0; i < gap; ++i)
michael@0 5123 newMarkers.push(gapMarkers);
michael@0 5124 newMarkers.push(last);
michael@0 5125 }
michael@0 5126 return newMarkers;
michael@0 5127 }
michael@0 5128
michael@0 5129 // Remove spans that are empty and don't have a clearWhenEmpty
michael@0 5130 // option of false.
michael@0 5131 function clearEmptySpans(spans) {
michael@0 5132 for (var i = 0; i < spans.length; ++i) {
michael@0 5133 var span = spans[i];
michael@0 5134 if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
michael@0 5135 spans.splice(i--, 1);
michael@0 5136 }
michael@0 5137 if (!spans.length) return null;
michael@0 5138 return spans;
michael@0 5139 }
michael@0 5140
michael@0 5141 // Used for un/re-doing changes from the history. Combines the
michael@0 5142 // result of computing the existing spans with the set of spans that
michael@0 5143 // existed in the history (so that deleting around a span and then
michael@0 5144 // undoing brings back the span).
michael@0 5145 function mergeOldSpans(doc, change) {
michael@0 5146 var old = getOldSpans(doc, change);
michael@0 5147 var stretched = stretchSpansOverChange(doc, change);
michael@0 5148 if (!old) return stretched;
michael@0 5149 if (!stretched) return old;
michael@0 5150
michael@0 5151 for (var i = 0; i < old.length; ++i) {
michael@0 5152 var oldCur = old[i], stretchCur = stretched[i];
michael@0 5153 if (oldCur && stretchCur) {
michael@0 5154 spans: for (var j = 0; j < stretchCur.length; ++j) {
michael@0 5155 var span = stretchCur[j];
michael@0 5156 for (var k = 0; k < oldCur.length; ++k)
michael@0 5157 if (oldCur[k].marker == span.marker) continue spans;
michael@0 5158 oldCur.push(span);
michael@0 5159 }
michael@0 5160 } else if (stretchCur) {
michael@0 5161 old[i] = stretchCur;
michael@0 5162 }
michael@0 5163 }
michael@0 5164 return old;
michael@0 5165 }
michael@0 5166
michael@0 5167 // Used to 'clip' out readOnly ranges when making a change.
michael@0 5168 function removeReadOnlyRanges(doc, from, to) {
michael@0 5169 var markers = null;
michael@0 5170 doc.iter(from.line, to.line + 1, function(line) {
michael@0 5171 if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
michael@0 5172 var mark = line.markedSpans[i].marker;
michael@0 5173 if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
michael@0 5174 (markers || (markers = [])).push(mark);
michael@0 5175 }
michael@0 5176 });
michael@0 5177 if (!markers) return null;
michael@0 5178 var parts = [{from: from, to: to}];
michael@0 5179 for (var i = 0; i < markers.length; ++i) {
michael@0 5180 var mk = markers[i], m = mk.find(0);
michael@0 5181 for (var j = 0; j < parts.length; ++j) {
michael@0 5182 var p = parts[j];
michael@0 5183 if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
michael@0 5184 var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
michael@0 5185 if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
michael@0 5186 newParts.push({from: p.from, to: m.from});
michael@0 5187 if (dto > 0 || !mk.inclusiveRight && !dto)
michael@0 5188 newParts.push({from: m.to, to: p.to});
michael@0 5189 parts.splice.apply(parts, newParts);
michael@0 5190 j += newParts.length - 1;
michael@0 5191 }
michael@0 5192 }
michael@0 5193 return parts;
michael@0 5194 }
michael@0 5195
michael@0 5196 // Connect or disconnect spans from a line.
michael@0 5197 function detachMarkedSpans(line) {
michael@0 5198 var spans = line.markedSpans;
michael@0 5199 if (!spans) return;
michael@0 5200 for (var i = 0; i < spans.length; ++i)
michael@0 5201 spans[i].marker.detachLine(line);
michael@0 5202 line.markedSpans = null;
michael@0 5203 }
michael@0 5204 function attachMarkedSpans(line, spans) {
michael@0 5205 if (!spans) return;
michael@0 5206 for (var i = 0; i < spans.length; ++i)
michael@0 5207 spans[i].marker.attachLine(line);
michael@0 5208 line.markedSpans = spans;
michael@0 5209 }
michael@0 5210
michael@0 5211 // Helpers used when computing which overlapping collapsed span
michael@0 5212 // counts as the larger one.
michael@0 5213 function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
michael@0 5214 function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
michael@0 5215
michael@0 5216 // Returns a number indicating which of two overlapping collapsed
michael@0 5217 // spans is larger (and thus includes the other). Falls back to
michael@0 5218 // comparing ids when the spans cover exactly the same range.
michael@0 5219 function compareCollapsedMarkers(a, b) {
michael@0 5220 var lenDiff = a.lines.length - b.lines.length;
michael@0 5221 if (lenDiff != 0) return lenDiff;
michael@0 5222 var aPos = a.find(), bPos = b.find();
michael@0 5223 var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
michael@0 5224 if (fromCmp) return -fromCmp;
michael@0 5225 var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
michael@0 5226 if (toCmp) return toCmp;
michael@0 5227 return b.id - a.id;
michael@0 5228 }
michael@0 5229
michael@0 5230 // Find out whether a line ends or starts in a collapsed span. If
michael@0 5231 // so, return the marker for that span.
michael@0 5232 function collapsedSpanAtSide(line, start) {
michael@0 5233 var sps = sawCollapsedSpans && line.markedSpans, found;
michael@0 5234 if (sps) for (var sp, i = 0; i < sps.length; ++i) {
michael@0 5235 sp = sps[i];
michael@0 5236 if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
michael@0 5237 (!found || compareCollapsedMarkers(found, sp.marker) < 0))
michael@0 5238 found = sp.marker;
michael@0 5239 }
michael@0 5240 return found;
michael@0 5241 }
michael@0 5242 function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
michael@0 5243 function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
michael@0 5244
michael@0 5245 // Test whether there exists a collapsed span that partially
michael@0 5246 // overlaps (covers the start or end, but not both) of a new span.
michael@0 5247 // Such overlap is not allowed.
michael@0 5248 function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
michael@0 5249 var line = getLine(doc, lineNo);
michael@0 5250 var sps = sawCollapsedSpans && line.markedSpans;
michael@0 5251 if (sps) for (var i = 0; i < sps.length; ++i) {
michael@0 5252 var sp = sps[i];
michael@0 5253 if (!sp.marker.collapsed) continue;
michael@0 5254 var found = sp.marker.find(0);
michael@0 5255 var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
michael@0 5256 var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
michael@0 5257 if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
michael@0 5258 if (fromCmp <= 0 && (cmp(found.to, from) || extraRight(sp.marker) - extraLeft(marker)) > 0 ||
michael@0 5259 fromCmp >= 0 && (cmp(found.from, to) || extraLeft(sp.marker) - extraRight(marker)) < 0)
michael@0 5260 return true;
michael@0 5261 }
michael@0 5262 }
michael@0 5263
michael@0 5264 // A visual line is a line as drawn on the screen. Folding, for
michael@0 5265 // example, can cause multiple logical lines to appear on the same
michael@0 5266 // visual line. This finds the start of the visual line that the
michael@0 5267 // given line is part of (usually that is the line itself).
michael@0 5268 function visualLine(line) {
michael@0 5269 var merged;
michael@0 5270 while (merged = collapsedSpanAtStart(line))
michael@0 5271 line = merged.find(-1, true).line;
michael@0 5272 return line;
michael@0 5273 }
michael@0 5274
michael@0 5275 // Returns an array of logical lines that continue the visual line
michael@0 5276 // started by the argument, or undefined if there are no such lines.
michael@0 5277 function visualLineContinued(line) {
michael@0 5278 var merged, lines;
michael@0 5279 while (merged = collapsedSpanAtEnd(line)) {
michael@0 5280 line = merged.find(1, true).line;
michael@0 5281 (lines || (lines = [])).push(line);
michael@0 5282 }
michael@0 5283 return lines;
michael@0 5284 }
michael@0 5285
michael@0 5286 // Get the line number of the start of the visual line that the
michael@0 5287 // given line number is part of.
michael@0 5288 function visualLineNo(doc, lineN) {
michael@0 5289 var line = getLine(doc, lineN), vis = visualLine(line);
michael@0 5290 if (line == vis) return lineN;
michael@0 5291 return lineNo(vis);
michael@0 5292 }
michael@0 5293 // Get the line number of the start of the next visual line after
michael@0 5294 // the given line.
michael@0 5295 function visualLineEndNo(doc, lineN) {
michael@0 5296 if (lineN > doc.lastLine()) return lineN;
michael@0 5297 var line = getLine(doc, lineN), merged;
michael@0 5298 if (!lineIsHidden(doc, line)) return lineN;
michael@0 5299 while (merged = collapsedSpanAtEnd(line))
michael@0 5300 line = merged.find(1, true).line;
michael@0 5301 return lineNo(line) + 1;
michael@0 5302 }
michael@0 5303
michael@0 5304 // Compute whether a line is hidden. Lines count as hidden when they
michael@0 5305 // are part of a visual line that starts with another line, or when
michael@0 5306 // they are entirely covered by collapsed, non-widget span.
michael@0 5307 function lineIsHidden(doc, line) {
michael@0 5308 var sps = sawCollapsedSpans && line.markedSpans;
michael@0 5309 if (sps) for (var sp, i = 0; i < sps.length; ++i) {
michael@0 5310 sp = sps[i];
michael@0 5311 if (!sp.marker.collapsed) continue;
michael@0 5312 if (sp.from == null) return true;
michael@0 5313 if (sp.marker.widgetNode) continue;
michael@0 5314 if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
michael@0 5315 return true;
michael@0 5316 }
michael@0 5317 }
michael@0 5318 function lineIsHiddenInner(doc, line, span) {
michael@0 5319 if (span.to == null) {
michael@0 5320 var end = span.marker.find(1, true);
michael@0 5321 return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
michael@0 5322 }
michael@0 5323 if (span.marker.inclusiveRight && span.to == line.text.length)
michael@0 5324 return true;
michael@0 5325 for (var sp, i = 0; i < line.markedSpans.length; ++i) {
michael@0 5326 sp = line.markedSpans[i];
michael@0 5327 if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
michael@0 5328 (sp.to == null || sp.to != span.from) &&
michael@0 5329 (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
michael@0 5330 lineIsHiddenInner(doc, line, sp)) return true;
michael@0 5331 }
michael@0 5332 }
michael@0 5333
michael@0 5334 // LINE WIDGETS
michael@0 5335
michael@0 5336 // Line widgets are block elements displayed above or below a line.
michael@0 5337
michael@0 5338 var LineWidget = CodeMirror.LineWidget = function(cm, node, options) {
michael@0 5339 if (options) for (var opt in options) if (options.hasOwnProperty(opt))
michael@0 5340 this[opt] = options[opt];
michael@0 5341 this.cm = cm;
michael@0 5342 this.node = node;
michael@0 5343 };
michael@0 5344 eventMixin(LineWidget);
michael@0 5345
michael@0 5346 function adjustScrollWhenAboveVisible(cm, line, diff) {
michael@0 5347 if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
michael@0 5348 addToScrollPos(cm, null, diff);
michael@0 5349 }
michael@0 5350
michael@0 5351 LineWidget.prototype.clear = function() {
michael@0 5352 var cm = this.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
michael@0 5353 if (no == null || !ws) return;
michael@0 5354 for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
michael@0 5355 if (!ws.length) line.widgets = null;
michael@0 5356 var height = widgetHeight(this);
michael@0 5357 runInOp(cm, function() {
michael@0 5358 adjustScrollWhenAboveVisible(cm, line, -height);
michael@0 5359 regLineChange(cm, no, "widget");
michael@0 5360 updateLineHeight(line, Math.max(0, line.height - height));
michael@0 5361 });
michael@0 5362 };
michael@0 5363 LineWidget.prototype.changed = function() {
michael@0 5364 var oldH = this.height, cm = this.cm, line = this.line;
michael@0 5365 this.height = null;
michael@0 5366 var diff = widgetHeight(this) - oldH;
michael@0 5367 if (!diff) return;
michael@0 5368 runInOp(cm, function() {
michael@0 5369 cm.curOp.forceUpdate = true;
michael@0 5370 adjustScrollWhenAboveVisible(cm, line, diff);
michael@0 5371 updateLineHeight(line, line.height + diff);
michael@0 5372 });
michael@0 5373 };
michael@0 5374
michael@0 5375 function widgetHeight(widget) {
michael@0 5376 if (widget.height != null) return widget.height;
michael@0 5377 if (!contains(document.body, widget.node))
michael@0 5378 removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, "position: relative"));
michael@0 5379 return widget.height = widget.node.offsetHeight;
michael@0 5380 }
michael@0 5381
michael@0 5382 function addLineWidget(cm, handle, node, options) {
michael@0 5383 var widget = new LineWidget(cm, node, options);
michael@0 5384 if (widget.noHScroll) cm.display.alignWidgets = true;
michael@0 5385 changeLine(cm, handle, "widget", function(line) {
michael@0 5386 var widgets = line.widgets || (line.widgets = []);
michael@0 5387 if (widget.insertAt == null) widgets.push(widget);
michael@0 5388 else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
michael@0 5389 widget.line = line;
michael@0 5390 if (!lineIsHidden(cm.doc, line)) {
michael@0 5391 var aboveVisible = heightAtLine(line) < cm.doc.scrollTop;
michael@0 5392 updateLineHeight(line, line.height + widgetHeight(widget));
michael@0 5393 if (aboveVisible) addToScrollPos(cm, null, widget.height);
michael@0 5394 cm.curOp.forceUpdate = true;
michael@0 5395 }
michael@0 5396 return true;
michael@0 5397 });
michael@0 5398 return widget;
michael@0 5399 }
michael@0 5400
michael@0 5401 // LINE DATA STRUCTURE
michael@0 5402
michael@0 5403 // Line objects. These hold state related to a line, including
michael@0 5404 // highlighting info (the styles array).
michael@0 5405 var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
michael@0 5406 this.text = text;
michael@0 5407 attachMarkedSpans(this, markedSpans);
michael@0 5408 this.height = estimateHeight ? estimateHeight(this) : 1;
michael@0 5409 };
michael@0 5410 eventMixin(Line);
michael@0 5411 Line.prototype.lineNo = function() { return lineNo(this); };
michael@0 5412
michael@0 5413 // Change the content (text, markers) of a line. Automatically
michael@0 5414 // invalidates cached information and tries to re-estimate the
michael@0 5415 // line's height.
michael@0 5416 function updateLine(line, text, markedSpans, estimateHeight) {
michael@0 5417 line.text = text;
michael@0 5418 if (line.stateAfter) line.stateAfter = null;
michael@0 5419 if (line.styles) line.styles = null;
michael@0 5420 if (line.order != null) line.order = null;
michael@0 5421 detachMarkedSpans(line);
michael@0 5422 attachMarkedSpans(line, markedSpans);
michael@0 5423 var estHeight = estimateHeight ? estimateHeight(line) : 1;
michael@0 5424 if (estHeight != line.height) updateLineHeight(line, estHeight);
michael@0 5425 }
michael@0 5426
michael@0 5427 // Detach a line from the document tree and its markers.
michael@0 5428 function cleanUpLine(line) {
michael@0 5429 line.parent = null;
michael@0 5430 detachMarkedSpans(line);
michael@0 5431 }
michael@0 5432
michael@0 5433 // Run the given mode's parser over a line, calling f for each token.
michael@0 5434 function runMode(cm, text, mode, state, f, forceToEnd) {
michael@0 5435 var flattenSpans = mode.flattenSpans;
michael@0 5436 if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
michael@0 5437 var curStart = 0, curStyle = null;
michael@0 5438 var stream = new StringStream(text, cm.options.tabSize), style;
michael@0 5439 if (text == "" && mode.blankLine) mode.blankLine(state);
michael@0 5440 while (!stream.eol()) {
michael@0 5441 if (stream.pos > cm.options.maxHighlightLength) {
michael@0 5442 flattenSpans = false;
michael@0 5443 if (forceToEnd) processLine(cm, text, state, stream.pos);
michael@0 5444 stream.pos = text.length;
michael@0 5445 style = null;
michael@0 5446 } else {
michael@0 5447 style = mode.token(stream, state);
michael@0 5448 }
michael@0 5449 if (cm.options.addModeClass) {
michael@0 5450 var mName = CodeMirror.innerMode(mode, state).mode.name;
michael@0 5451 if (mName) style = "m-" + (style ? mName + " " + style : mName);
michael@0 5452 }
michael@0 5453 if (!flattenSpans || curStyle != style) {
michael@0 5454 if (curStart < stream.start) f(stream.start, curStyle);
michael@0 5455 curStart = stream.start; curStyle = style;
michael@0 5456 }
michael@0 5457 stream.start = stream.pos;
michael@0 5458 }
michael@0 5459 while (curStart < stream.pos) {
michael@0 5460 // Webkit seems to refuse to render text nodes longer than 57444 characters
michael@0 5461 var pos = Math.min(stream.pos, curStart + 50000);
michael@0 5462 f(pos, curStyle);
michael@0 5463 curStart = pos;
michael@0 5464 }
michael@0 5465 }
michael@0 5466
michael@0 5467 // Compute a style array (an array starting with a mode generation
michael@0 5468 // -- for invalidation -- followed by pairs of end positions and
michael@0 5469 // style strings), which is used to highlight the tokens on the
michael@0 5470 // line.
michael@0 5471 function highlightLine(cm, line, state, forceToEnd) {
michael@0 5472 // A styles array always starts with a number identifying the
michael@0 5473 // mode/overlays that it is based on (for easy invalidation).
michael@0 5474 var st = [cm.state.modeGen];
michael@0 5475 // Compute the base array of styles
michael@0 5476 runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
michael@0 5477 st.push(end, style);
michael@0 5478 }, forceToEnd);
michael@0 5479
michael@0 5480 // Run overlays, adjust style array.
michael@0 5481 for (var o = 0; o < cm.state.overlays.length; ++o) {
michael@0 5482 var overlay = cm.state.overlays[o], i = 1, at = 0;
michael@0 5483 runMode(cm, line.text, overlay.mode, true, function(end, style) {
michael@0 5484 var start = i;
michael@0 5485 // Ensure there's a token end at the current position, and that i points at it
michael@0 5486 while (at < end) {
michael@0 5487 var i_end = st[i];
michael@0 5488 if (i_end > end)
michael@0 5489 st.splice(i, 1, end, st[i+1], i_end);
michael@0 5490 i += 2;
michael@0 5491 at = Math.min(end, i_end);
michael@0 5492 }
michael@0 5493 if (!style) return;
michael@0 5494 if (overlay.opaque) {
michael@0 5495 st.splice(start, i - start, end, style);
michael@0 5496 i = start + 2;
michael@0 5497 } else {
michael@0 5498 for (; start < i; start += 2) {
michael@0 5499 var cur = st[start+1];
michael@0 5500 st[start+1] = cur ? cur + " " + style : style;
michael@0 5501 }
michael@0 5502 }
michael@0 5503 });
michael@0 5504 }
michael@0 5505
michael@0 5506 return st;
michael@0 5507 }
michael@0 5508
michael@0 5509 function getLineStyles(cm, line) {
michael@0 5510 if (!line.styles || line.styles[0] != cm.state.modeGen)
michael@0 5511 line.styles = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
michael@0 5512 return line.styles;
michael@0 5513 }
michael@0 5514
michael@0 5515 // Lightweight form of highlight -- proceed over this line and
michael@0 5516 // update state, but don't save a style array. Used for lines that
michael@0 5517 // aren't currently visible.
michael@0 5518 function processLine(cm, text, state, startAt) {
michael@0 5519 var mode = cm.doc.mode;
michael@0 5520 var stream = new StringStream(text, cm.options.tabSize);
michael@0 5521 stream.start = stream.pos = startAt || 0;
michael@0 5522 if (text == "" && mode.blankLine) mode.blankLine(state);
michael@0 5523 while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) {
michael@0 5524 mode.token(stream, state);
michael@0 5525 stream.start = stream.pos;
michael@0 5526 }
michael@0 5527 }
michael@0 5528
michael@0 5529 // Convert a style as returned by a mode (either null, or a string
michael@0 5530 // containing one or more styles) to a CSS style. This is cached,
michael@0 5531 // and also looks for line-wide styles.
michael@0 5532 var styleToClassCache = {}, styleToClassCacheWithMode = {};
michael@0 5533 function interpretTokenStyle(style, builder) {
michael@0 5534 if (!style) return null;
michael@0 5535 for (;;) {
michael@0 5536 var lineClass = style.match(/(?:^|\s+)line-(background-)?(\S+)/);
michael@0 5537 if (!lineClass) break;
michael@0 5538 style = style.slice(0, lineClass.index) + style.slice(lineClass.index + lineClass[0].length);
michael@0 5539 var prop = lineClass[1] ? "bgClass" : "textClass";
michael@0 5540 if (builder[prop] == null)
michael@0 5541 builder[prop] = lineClass[2];
michael@0 5542 else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(builder[prop]))
michael@0 5543 builder[prop] += " " + lineClass[2];
michael@0 5544 }
michael@0 5545 if (/^\s*$/.test(style)) return null;
michael@0 5546 var cache = builder.cm.options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
michael@0 5547 return cache[style] ||
michael@0 5548 (cache[style] = style.replace(/\S+/g, "cm-$&"));
michael@0 5549 }
michael@0 5550
michael@0 5551 // Render the DOM representation of the text of a line. Also builds
michael@0 5552 // up a 'line map', which points at the DOM nodes that represent
michael@0 5553 // specific stretches of text, and is used by the measuring code.
michael@0 5554 // The returned object contains the DOM node, this map, and
michael@0 5555 // information about line-wide styles that were set by the mode.
michael@0 5556 function buildLineContent(cm, lineView) {
michael@0 5557 // The padding-right forces the element to have a 'border', which
michael@0 5558 // is needed on Webkit to be able to get line-level bounding
michael@0 5559 // rectangles for it (in measureChar).
michael@0 5560 var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
michael@0 5561 var builder = {pre: elt("pre", [content]), content: content, col: 0, pos: 0, cm: cm};
michael@0 5562 lineView.measure = {};
michael@0 5563
michael@0 5564 // Iterate over the logical lines that make up this visual line.
michael@0 5565 for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
michael@0 5566 var line = i ? lineView.rest[i - 1] : lineView.line, order;
michael@0 5567 builder.pos = 0;
michael@0 5568 builder.addToken = buildToken;
michael@0 5569 // Optionally wire in some hacks into the token-rendering
michael@0 5570 // algorithm, to deal with browser quirks.
michael@0 5571 if ((ie || webkit) && cm.getOption("lineWrapping"))
michael@0 5572 builder.addToken = buildTokenSplitSpaces(builder.addToken);
michael@0 5573 if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
michael@0 5574 builder.addToken = buildTokenBadBidi(builder.addToken, order);
michael@0 5575 builder.map = [];
michael@0 5576 insertLineContent(line, builder, getLineStyles(cm, line));
michael@0 5577
michael@0 5578 // Ensure at least a single node is present, for measuring.
michael@0 5579 if (builder.map.length == 0)
michael@0 5580 builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
michael@0 5581
michael@0 5582 // Store the map and a cache object for the current logical line
michael@0 5583 if (i == 0) {
michael@0 5584 lineView.measure.map = builder.map;
michael@0 5585 lineView.measure.cache = {};
michael@0 5586 } else {
michael@0 5587 (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
michael@0 5588 (lineView.measure.caches || (lineView.measure.caches = [])).push({});
michael@0 5589 }
michael@0 5590 }
michael@0 5591
michael@0 5592 signal(cm, "renderLine", cm, lineView.line, builder.pre);
michael@0 5593 return builder;
michael@0 5594 }
michael@0 5595
michael@0 5596 function defaultSpecialCharPlaceholder(ch) {
michael@0 5597 var token = elt("span", "\u2022", "cm-invalidchar");
michael@0 5598 token.title = "\\u" + ch.charCodeAt(0).toString(16);
michael@0 5599 return token;
michael@0 5600 }
michael@0 5601
michael@0 5602 // Build up the DOM representation for a single token, and add it to
michael@0 5603 // the line map. Takes care to render special characters separately.
michael@0 5604 function buildToken(builder, text, style, startStyle, endStyle, title) {
michael@0 5605 if (!text) return;
michael@0 5606 var special = builder.cm.options.specialChars, mustWrap = false;
michael@0 5607 if (!special.test(text)) {
michael@0 5608 builder.col += text.length;
michael@0 5609 var content = document.createTextNode(text);
michael@0 5610 builder.map.push(builder.pos, builder.pos + text.length, content);
michael@0 5611 if (ie_upto8) mustWrap = true;
michael@0 5612 builder.pos += text.length;
michael@0 5613 } else {
michael@0 5614 var content = document.createDocumentFragment(), pos = 0;
michael@0 5615 while (true) {
michael@0 5616 special.lastIndex = pos;
michael@0 5617 var m = special.exec(text);
michael@0 5618 var skipped = m ? m.index - pos : text.length - pos;
michael@0 5619 if (skipped) {
michael@0 5620 var txt = document.createTextNode(text.slice(pos, pos + skipped));
michael@0 5621 if (ie_upto8) content.appendChild(elt("span", [txt]));
michael@0 5622 else content.appendChild(txt);
michael@0 5623 builder.map.push(builder.pos, builder.pos + skipped, txt);
michael@0 5624 builder.col += skipped;
michael@0 5625 builder.pos += skipped;
michael@0 5626 }
michael@0 5627 if (!m) break;
michael@0 5628 pos += skipped + 1;
michael@0 5629 if (m[0] == "\t") {
michael@0 5630 var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
michael@0 5631 var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
michael@0 5632 builder.col += tabWidth;
michael@0 5633 } else {
michael@0 5634 var txt = builder.cm.options.specialCharPlaceholder(m[0]);
michael@0 5635 if (ie_upto8) content.appendChild(elt("span", [txt]));
michael@0 5636 else content.appendChild(txt);
michael@0 5637 builder.col += 1;
michael@0 5638 }
michael@0 5639 builder.map.push(builder.pos, builder.pos + 1, txt);
michael@0 5640 builder.pos++;
michael@0 5641 }
michael@0 5642 }
michael@0 5643 if (style || startStyle || endStyle || mustWrap) {
michael@0 5644 var fullStyle = style || "";
michael@0 5645 if (startStyle) fullStyle += startStyle;
michael@0 5646 if (endStyle) fullStyle += endStyle;
michael@0 5647 var token = elt("span", [content], fullStyle);
michael@0 5648 if (title) token.title = title;
michael@0 5649 return builder.content.appendChild(token);
michael@0 5650 }
michael@0 5651 builder.content.appendChild(content);
michael@0 5652 }
michael@0 5653
michael@0 5654 function buildTokenSplitSpaces(inner) {
michael@0 5655 function split(old) {
michael@0 5656 var out = " ";
michael@0 5657 for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
michael@0 5658 out += " ";
michael@0 5659 return out;
michael@0 5660 }
michael@0 5661 return function(builder, text, style, startStyle, endStyle, title) {
michael@0 5662 inner(builder, text.replace(/ {3,}/g, split), style, startStyle, endStyle, title);
michael@0 5663 };
michael@0 5664 }
michael@0 5665
michael@0 5666 // Work around nonsense dimensions being reported for stretches of
michael@0 5667 // right-to-left text.
michael@0 5668 function buildTokenBadBidi(inner, order) {
michael@0 5669 return function(builder, text, style, startStyle, endStyle, title) {
michael@0 5670 style = style ? style + " cm-force-border" : "cm-force-border";
michael@0 5671 var start = builder.pos, end = start + text.length;
michael@0 5672 for (;;) {
michael@0 5673 // Find the part that overlaps with the start of this text
michael@0 5674 for (var i = 0; i < order.length; i++) {
michael@0 5675 var part = order[i];
michael@0 5676 if (part.to > start && part.from <= start) break;
michael@0 5677 }
michael@0 5678 if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title);
michael@0 5679 inner(builder, text.slice(0, part.to - start), style, startStyle, null, title);
michael@0 5680 startStyle = null;
michael@0 5681 text = text.slice(part.to - start);
michael@0 5682 start = part.to;
michael@0 5683 }
michael@0 5684 };
michael@0 5685 }
michael@0 5686
michael@0 5687 function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
michael@0 5688 var widget = !ignoreWidget && marker.widgetNode;
michael@0 5689 if (widget) {
michael@0 5690 builder.map.push(builder.pos, builder.pos + size, widget);
michael@0 5691 builder.content.appendChild(widget);
michael@0 5692 }
michael@0 5693 builder.pos += size;
michael@0 5694 }
michael@0 5695
michael@0 5696 // Outputs a number of spans to make up a line, taking highlighting
michael@0 5697 // and marked text into account.
michael@0 5698 function insertLineContent(line, builder, styles) {
michael@0 5699 var spans = line.markedSpans, allText = line.text, at = 0;
michael@0 5700 if (!spans) {
michael@0 5701 for (var i = 1; i < styles.length; i+=2)
michael@0 5702 builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder));
michael@0 5703 return;
michael@0 5704 }
michael@0 5705
michael@0 5706 var len = allText.length, pos = 0, i = 1, text = "", style;
michael@0 5707 var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
michael@0 5708 for (;;) {
michael@0 5709 if (nextChange == pos) { // Update current marker set
michael@0 5710 spanStyle = spanEndStyle = spanStartStyle = title = "";
michael@0 5711 collapsed = null; nextChange = Infinity;
michael@0 5712 var foundBookmarks = [];
michael@0 5713 for (var j = 0; j < spans.length; ++j) {
michael@0 5714 var sp = spans[j], m = sp.marker;
michael@0 5715 if (sp.from <= pos && (sp.to == null || sp.to > pos)) {
michael@0 5716 if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }
michael@0 5717 if (m.className) spanStyle += " " + m.className;
michael@0 5718 if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
michael@0 5719 if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
michael@0 5720 if (m.title && !title) title = m.title;
michael@0 5721 if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
michael@0 5722 collapsed = sp;
michael@0 5723 } else if (sp.from > pos && nextChange > sp.from) {
michael@0 5724 nextChange = sp.from;
michael@0 5725 }
michael@0 5726 if (m.type == "bookmark" && sp.from == pos && m.widgetNode) foundBookmarks.push(m);
michael@0 5727 }
michael@0 5728 if (collapsed && (collapsed.from || 0) == pos) {
michael@0 5729 buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
michael@0 5730 collapsed.marker, collapsed.from == null);
michael@0 5731 if (collapsed.to == null) return;
michael@0 5732 }
michael@0 5733 if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)
michael@0 5734 buildCollapsedSpan(builder, 0, foundBookmarks[j]);
michael@0 5735 }
michael@0 5736 if (pos >= len) break;
michael@0 5737
michael@0 5738 var upto = Math.min(len, nextChange);
michael@0 5739 while (true) {
michael@0 5740 if (text) {
michael@0 5741 var end = pos + text.length;
michael@0 5742 if (!collapsed) {
michael@0 5743 var tokenText = end > upto ? text.slice(0, upto - pos) : text;
michael@0 5744 builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
michael@0 5745 spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title);
michael@0 5746 }
michael@0 5747 if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
michael@0 5748 pos = end;
michael@0 5749 spanStartStyle = "";
michael@0 5750 }
michael@0 5751 text = allText.slice(at, at = styles[i++]);
michael@0 5752 style = interpretTokenStyle(styles[i++], builder);
michael@0 5753 }
michael@0 5754 }
michael@0 5755 }
michael@0 5756
michael@0 5757 // DOCUMENT DATA STRUCTURE
michael@0 5758
michael@0 5759 // By default, updates that start and end at the beginning of a line
michael@0 5760 // are treated specially, in order to make the association of line
michael@0 5761 // widgets and marker elements with the text behave more intuitive.
michael@0 5762 function isWholeLineUpdate(doc, change) {
michael@0 5763 return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
michael@0 5764 (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
michael@0 5765 }
michael@0 5766
michael@0 5767 // Perform a change on the document data structure.
michael@0 5768 function updateDoc(doc, change, markedSpans, estimateHeight) {
michael@0 5769 function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
michael@0 5770 function update(line, text, spans) {
michael@0 5771 updateLine(line, text, spans, estimateHeight);
michael@0 5772 signalLater(line, "change", line, change);
michael@0 5773 }
michael@0 5774
michael@0 5775 var from = change.from, to = change.to, text = change.text;
michael@0 5776 var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
michael@0 5777 var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
michael@0 5778
michael@0 5779 // Adjust the line structure
michael@0 5780 if (isWholeLineUpdate(doc, change)) {
michael@0 5781 // This is a whole-line replace. Treated specially to make
michael@0 5782 // sure line objects move the way they are supposed to.
michael@0 5783 for (var i = 0, added = []; i < text.length - 1; ++i)
michael@0 5784 added.push(new Line(text[i], spansFor(i), estimateHeight));
michael@0 5785 update(lastLine, lastLine.text, lastSpans);
michael@0 5786 if (nlines) doc.remove(from.line, nlines);
michael@0 5787 if (added.length) doc.insert(from.line, added);
michael@0 5788 } else if (firstLine == lastLine) {
michael@0 5789 if (text.length == 1) {
michael@0 5790 update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
michael@0 5791 } else {
michael@0 5792 for (var added = [], i = 1; i < text.length - 1; ++i)
michael@0 5793 added.push(new Line(text[i], spansFor(i), estimateHeight));
michael@0 5794 added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
michael@0 5795 update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
michael@0 5796 doc.insert(from.line + 1, added);
michael@0 5797 }
michael@0 5798 } else if (text.length == 1) {
michael@0 5799 update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
michael@0 5800 doc.remove(from.line + 1, nlines);
michael@0 5801 } else {
michael@0 5802 update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
michael@0 5803 update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
michael@0 5804 for (var i = 1, added = []; i < text.length - 1; ++i)
michael@0 5805 added.push(new Line(text[i], spansFor(i), estimateHeight));
michael@0 5806 if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
michael@0 5807 doc.insert(from.line + 1, added);
michael@0 5808 }
michael@0 5809
michael@0 5810 signalLater(doc, "change", doc, change);
michael@0 5811 }
michael@0 5812
michael@0 5813 // The document is represented as a BTree consisting of leaves, with
michael@0 5814 // chunk of lines in them, and branches, with up to ten leaves or
michael@0 5815 // other branch nodes below them. The top node is always a branch
michael@0 5816 // node, and is the document object itself (meaning it has
michael@0 5817 // additional methods and properties).
michael@0 5818 //
michael@0 5819 // All nodes have parent links. The tree is used both to go from
michael@0 5820 // line numbers to line objects, and to go from objects to numbers.
michael@0 5821 // It also indexes by height, and is used to convert between height
michael@0 5822 // and line object, and to find the total height of the document.
michael@0 5823 //
michael@0 5824 // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
michael@0 5825
michael@0 5826 function LeafChunk(lines) {
michael@0 5827 this.lines = lines;
michael@0 5828 this.parent = null;
michael@0 5829 for (var i = 0, height = 0; i < lines.length; ++i) {
michael@0 5830 lines[i].parent = this;
michael@0 5831 height += lines[i].height;
michael@0 5832 }
michael@0 5833 this.height = height;
michael@0 5834 }
michael@0 5835
michael@0 5836 LeafChunk.prototype = {
michael@0 5837 chunkSize: function() { return this.lines.length; },
michael@0 5838 // Remove the n lines at offset 'at'.
michael@0 5839 removeInner: function(at, n) {
michael@0 5840 for (var i = at, e = at + n; i < e; ++i) {
michael@0 5841 var line = this.lines[i];
michael@0 5842 this.height -= line.height;
michael@0 5843 cleanUpLine(line);
michael@0 5844 signalLater(line, "delete");
michael@0 5845 }
michael@0 5846 this.lines.splice(at, n);
michael@0 5847 },
michael@0 5848 // Helper used to collapse a small branch into a single leaf.
michael@0 5849 collapse: function(lines) {
michael@0 5850 lines.push.apply(lines, this.lines);
michael@0 5851 },
michael@0 5852 // Insert the given array of lines at offset 'at', count them as
michael@0 5853 // having the given height.
michael@0 5854 insertInner: function(at, lines, height) {
michael@0 5855 this.height += height;
michael@0 5856 this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
michael@0 5857 for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
michael@0 5858 },
michael@0 5859 // Used to iterate over a part of the tree.
michael@0 5860 iterN: function(at, n, op) {
michael@0 5861 for (var e = at + n; at < e; ++at)
michael@0 5862 if (op(this.lines[at])) return true;
michael@0 5863 }
michael@0 5864 };
michael@0 5865
michael@0 5866 function BranchChunk(children) {
michael@0 5867 this.children = children;
michael@0 5868 var size = 0, height = 0;
michael@0 5869 for (var i = 0; i < children.length; ++i) {
michael@0 5870 var ch = children[i];
michael@0 5871 size += ch.chunkSize(); height += ch.height;
michael@0 5872 ch.parent = this;
michael@0 5873 }
michael@0 5874 this.size = size;
michael@0 5875 this.height = height;
michael@0 5876 this.parent = null;
michael@0 5877 }
michael@0 5878
michael@0 5879 BranchChunk.prototype = {
michael@0 5880 chunkSize: function() { return this.size; },
michael@0 5881 removeInner: function(at, n) {
michael@0 5882 this.size -= n;
michael@0 5883 for (var i = 0; i < this.children.length; ++i) {
michael@0 5884 var child = this.children[i], sz = child.chunkSize();
michael@0 5885 if (at < sz) {
michael@0 5886 var rm = Math.min(n, sz - at), oldHeight = child.height;
michael@0 5887 child.removeInner(at, rm);
michael@0 5888 this.height -= oldHeight - child.height;
michael@0 5889 if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
michael@0 5890 if ((n -= rm) == 0) break;
michael@0 5891 at = 0;
michael@0 5892 } else at -= sz;
michael@0 5893 }
michael@0 5894 // If the result is smaller than 25 lines, ensure that it is a
michael@0 5895 // single leaf node.
michael@0 5896 if (this.size - n < 25 &&
michael@0 5897 (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
michael@0 5898 var lines = [];
michael@0 5899 this.collapse(lines);
michael@0 5900 this.children = [new LeafChunk(lines)];
michael@0 5901 this.children[0].parent = this;
michael@0 5902 }
michael@0 5903 },
michael@0 5904 collapse: function(lines) {
michael@0 5905 for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
michael@0 5906 },
michael@0 5907 insertInner: function(at, lines, height) {
michael@0 5908 this.size += lines.length;
michael@0 5909 this.height += height;
michael@0 5910 for (var i = 0; i < this.children.length; ++i) {
michael@0 5911 var child = this.children[i], sz = child.chunkSize();
michael@0 5912 if (at <= sz) {
michael@0 5913 child.insertInner(at, lines, height);
michael@0 5914 if (child.lines && child.lines.length > 50) {
michael@0 5915 while (child.lines.length > 50) {
michael@0 5916 var spilled = child.lines.splice(child.lines.length - 25, 25);
michael@0 5917 var newleaf = new LeafChunk(spilled);
michael@0 5918 child.height -= newleaf.height;
michael@0 5919 this.children.splice(i + 1, 0, newleaf);
michael@0 5920 newleaf.parent = this;
michael@0 5921 }
michael@0 5922 this.maybeSpill();
michael@0 5923 }
michael@0 5924 break;
michael@0 5925 }
michael@0 5926 at -= sz;
michael@0 5927 }
michael@0 5928 },
michael@0 5929 // When a node has grown, check whether it should be split.
michael@0 5930 maybeSpill: function() {
michael@0 5931 if (this.children.length <= 10) return;
michael@0 5932 var me = this;
michael@0 5933 do {
michael@0 5934 var spilled = me.children.splice(me.children.length - 5, 5);
michael@0 5935 var sibling = new BranchChunk(spilled);
michael@0 5936 if (!me.parent) { // Become the parent node
michael@0 5937 var copy = new BranchChunk(me.children);
michael@0 5938 copy.parent = me;
michael@0 5939 me.children = [copy, sibling];
michael@0 5940 me = copy;
michael@0 5941 } else {
michael@0 5942 me.size -= sibling.size;
michael@0 5943 me.height -= sibling.height;
michael@0 5944 var myIndex = indexOf(me.parent.children, me);
michael@0 5945 me.parent.children.splice(myIndex + 1, 0, sibling);
michael@0 5946 }
michael@0 5947 sibling.parent = me.parent;
michael@0 5948 } while (me.children.length > 10);
michael@0 5949 me.parent.maybeSpill();
michael@0 5950 },
michael@0 5951 iterN: function(at, n, op) {
michael@0 5952 for (var i = 0; i < this.children.length; ++i) {
michael@0 5953 var child = this.children[i], sz = child.chunkSize();
michael@0 5954 if (at < sz) {
michael@0 5955 var used = Math.min(n, sz - at);
michael@0 5956 if (child.iterN(at, used, op)) return true;
michael@0 5957 if ((n -= used) == 0) break;
michael@0 5958 at = 0;
michael@0 5959 } else at -= sz;
michael@0 5960 }
michael@0 5961 }
michael@0 5962 };
michael@0 5963
michael@0 5964 var nextDocId = 0;
michael@0 5965 var Doc = CodeMirror.Doc = function(text, mode, firstLine) {
michael@0 5966 if (!(this instanceof Doc)) return new Doc(text, mode, firstLine);
michael@0 5967 if (firstLine == null) firstLine = 0;
michael@0 5968
michael@0 5969 BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
michael@0 5970 this.first = firstLine;
michael@0 5971 this.scrollTop = this.scrollLeft = 0;
michael@0 5972 this.cantEdit = false;
michael@0 5973 this.cleanGeneration = 1;
michael@0 5974 this.frontier = firstLine;
michael@0 5975 var start = Pos(firstLine, 0);
michael@0 5976 this.sel = simpleSelection(start);
michael@0 5977 this.history = new History(null);
michael@0 5978 this.id = ++nextDocId;
michael@0 5979 this.modeOption = mode;
michael@0 5980
michael@0 5981 if (typeof text == "string") text = splitLines(text);
michael@0 5982 updateDoc(this, {from: start, to: start, text: text});
michael@0 5983 setSelection(this, simpleSelection(start), sel_dontScroll);
michael@0 5984 };
michael@0 5985
michael@0 5986 Doc.prototype = createObj(BranchChunk.prototype, {
michael@0 5987 constructor: Doc,
michael@0 5988 // Iterate over the document. Supports two forms -- with only one
michael@0 5989 // argument, it calls that for each line in the document. With
michael@0 5990 // three, it iterates over the range given by the first two (with
michael@0 5991 // the second being non-inclusive).
michael@0 5992 iter: function(from, to, op) {
michael@0 5993 if (op) this.iterN(from - this.first, to - from, op);
michael@0 5994 else this.iterN(this.first, this.first + this.size, from);
michael@0 5995 },
michael@0 5996
michael@0 5997 // Non-public interface for adding and removing lines.
michael@0 5998 insert: function(at, lines) {
michael@0 5999 var height = 0;
michael@0 6000 for (var i = 0; i < lines.length; ++i) height += lines[i].height;
michael@0 6001 this.insertInner(at - this.first, lines, height);
michael@0 6002 },
michael@0 6003 remove: function(at, n) { this.removeInner(at - this.first, n); },
michael@0 6004
michael@0 6005 // From here, the methods are part of the public interface. Most
michael@0 6006 // are also available from CodeMirror (editor) instances.
michael@0 6007
michael@0 6008 getValue: function(lineSep) {
michael@0 6009 var lines = getLines(this, this.first, this.first + this.size);
michael@0 6010 if (lineSep === false) return lines;
michael@0 6011 return lines.join(lineSep || "\n");
michael@0 6012 },
michael@0 6013 setValue: docMethodOp(function(code) {
michael@0 6014 var top = Pos(this.first, 0), last = this.first + this.size - 1;
michael@0 6015 makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
michael@0 6016 text: splitLines(code), origin: "setValue"}, true);
michael@0 6017 setSelection(this, simpleSelection(top));
michael@0 6018 }),
michael@0 6019 replaceRange: function(code, from, to, origin) {
michael@0 6020 from = clipPos(this, from);
michael@0 6021 to = to ? clipPos(this, to) : from;
michael@0 6022 replaceRange(this, code, from, to, origin);
michael@0 6023 },
michael@0 6024 getRange: function(from, to, lineSep) {
michael@0 6025 var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
michael@0 6026 if (lineSep === false) return lines;
michael@0 6027 return lines.join(lineSep || "\n");
michael@0 6028 },
michael@0 6029
michael@0 6030 getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
michael@0 6031
michael@0 6032 getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
michael@0 6033 getLineNumber: function(line) {return lineNo(line);},
michael@0 6034
michael@0 6035 getLineHandleVisualStart: function(line) {
michael@0 6036 if (typeof line == "number") line = getLine(this, line);
michael@0 6037 return visualLine(line);
michael@0 6038 },
michael@0 6039
michael@0 6040 lineCount: function() {return this.size;},
michael@0 6041 firstLine: function() {return this.first;},
michael@0 6042 lastLine: function() {return this.first + this.size - 1;},
michael@0 6043
michael@0 6044 clipPos: function(pos) {return clipPos(this, pos);},
michael@0 6045
michael@0 6046 getCursor: function(start) {
michael@0 6047 var range = this.sel.primary(), pos;
michael@0 6048 if (start == null || start == "head") pos = range.head;
michael@0 6049 else if (start == "anchor") pos = range.anchor;
michael@0 6050 else if (start == "end" || start == "to" || start === false) pos = range.to();
michael@0 6051 else pos = range.from();
michael@0 6052 return pos;
michael@0 6053 },
michael@0 6054 listSelections: function() { return this.sel.ranges; },
michael@0 6055 somethingSelected: function() {return this.sel.somethingSelected();},
michael@0 6056
michael@0 6057 setCursor: docMethodOp(function(line, ch, options) {
michael@0 6058 setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
michael@0 6059 }),
michael@0 6060 setSelection: docMethodOp(function(anchor, head, options) {
michael@0 6061 setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
michael@0 6062 }),
michael@0 6063 extendSelection: docMethodOp(function(head, other, options) {
michael@0 6064 extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
michael@0 6065 }),
michael@0 6066 extendSelections: docMethodOp(function(heads, options) {
michael@0 6067 extendSelections(this, clipPosArray(this, heads, options));
michael@0 6068 }),
michael@0 6069 extendSelectionsBy: docMethodOp(function(f, options) {
michael@0 6070 extendSelections(this, map(this.sel.ranges, f), options);
michael@0 6071 }),
michael@0 6072 setSelections: docMethodOp(function(ranges, primary, options) {
michael@0 6073 if (!ranges.length) return;
michael@0 6074 for (var i = 0, out = []; i < ranges.length; i++)
michael@0 6075 out[i] = new Range(clipPos(this, ranges[i].anchor),
michael@0 6076 clipPos(this, ranges[i].head));
michael@0 6077 if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
michael@0 6078 setSelection(this, normalizeSelection(out, primary), options);
michael@0 6079 }),
michael@0 6080 addSelection: docMethodOp(function(anchor, head, options) {
michael@0 6081 var ranges = this.sel.ranges.slice(0);
michael@0 6082 ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
michael@0 6083 setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
michael@0 6084 }),
michael@0 6085
michael@0 6086 getSelection: function(lineSep) {
michael@0 6087 var ranges = this.sel.ranges, lines;
michael@0 6088 for (var i = 0; i < ranges.length; i++) {
michael@0 6089 var sel = getBetween(this, ranges[i].from(), ranges[i].to());
michael@0 6090 lines = lines ? lines.concat(sel) : sel;
michael@0 6091 }
michael@0 6092 if (lineSep === false) return lines;
michael@0 6093 else return lines.join(lineSep || "\n");
michael@0 6094 },
michael@0 6095 getSelections: function(lineSep) {
michael@0 6096 var parts = [], ranges = this.sel.ranges;
michael@0 6097 for (var i = 0; i < ranges.length; i++) {
michael@0 6098 var sel = getBetween(this, ranges[i].from(), ranges[i].to());
michael@0 6099 if (lineSep !== false) sel = sel.join(lineSep || "\n");
michael@0 6100 parts[i] = sel;
michael@0 6101 }
michael@0 6102 return parts;
michael@0 6103 },
michael@0 6104 replaceSelection: docMethodOp(function(code, collapse, origin) {
michael@0 6105 var dup = [];
michael@0 6106 for (var i = 0; i < this.sel.ranges.length; i++)
michael@0 6107 dup[i] = code;
michael@0 6108 this.replaceSelections(dup, collapse, origin || "+input");
michael@0 6109 }),
michael@0 6110 replaceSelections: function(code, collapse, origin) {
michael@0 6111 var changes = [], sel = this.sel;
michael@0 6112 for (var i = 0; i < sel.ranges.length; i++) {
michael@0 6113 var range = sel.ranges[i];
michael@0 6114 changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin};
michael@0 6115 }
michael@0 6116 var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
michael@0 6117 for (var i = changes.length - 1; i >= 0; i--)
michael@0 6118 makeChange(this, changes[i]);
michael@0 6119 if (newSel) setSelectionReplaceHistory(this, newSel);
michael@0 6120 else if (this.cm) ensureCursorVisible(this.cm);
michael@0 6121 },
michael@0 6122 undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
michael@0 6123 redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
michael@0 6124 undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
michael@0 6125 redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
michael@0 6126
michael@0 6127 setExtending: function(val) {this.extend = val;},
michael@0 6128 getExtending: function() {return this.extend;},
michael@0 6129
michael@0 6130 historySize: function() {
michael@0 6131 var hist = this.history, done = 0, undone = 0;
michael@0 6132 for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
michael@0 6133 for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
michael@0 6134 return {undo: done, redo: undone};
michael@0 6135 },
michael@0 6136 clearHistory: function() {this.history = new History(this.history.maxGeneration);},
michael@0 6137
michael@0 6138 markClean: function() {
michael@0 6139 this.cleanGeneration = this.changeGeneration(true);
michael@0 6140 },
michael@0 6141 changeGeneration: function(forceSplit) {
michael@0 6142 if (forceSplit)
michael@0 6143 this.history.lastOp = this.history.lastOrigin = null;
michael@0 6144 return this.history.generation;
michael@0 6145 },
michael@0 6146 isClean: function (gen) {
michael@0 6147 return this.history.generation == (gen || this.cleanGeneration);
michael@0 6148 },
michael@0 6149
michael@0 6150 getHistory: function() {
michael@0 6151 return {done: copyHistoryArray(this.history.done),
michael@0 6152 undone: copyHistoryArray(this.history.undone)};
michael@0 6153 },
michael@0 6154 setHistory: function(histData) {
michael@0 6155 var hist = this.history = new History(this.history.maxGeneration);
michael@0 6156 hist.done = copyHistoryArray(histData.done.slice(0), null, true);
michael@0 6157 hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
michael@0 6158 },
michael@0 6159
michael@0 6160 markText: function(from, to, options) {
michael@0 6161 return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
michael@0 6162 },
michael@0 6163 setBookmark: function(pos, options) {
michael@0 6164 var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
michael@0 6165 insertLeft: options && options.insertLeft,
michael@0 6166 clearWhenEmpty: false, shared: options && options.shared};
michael@0 6167 pos = clipPos(this, pos);
michael@0 6168 return markText(this, pos, pos, realOpts, "bookmark");
michael@0 6169 },
michael@0 6170 findMarksAt: function(pos) {
michael@0 6171 pos = clipPos(this, pos);
michael@0 6172 var markers = [], spans = getLine(this, pos.line).markedSpans;
michael@0 6173 if (spans) for (var i = 0; i < spans.length; ++i) {
michael@0 6174 var span = spans[i];
michael@0 6175 if ((span.from == null || span.from <= pos.ch) &&
michael@0 6176 (span.to == null || span.to >= pos.ch))
michael@0 6177 markers.push(span.marker.parent || span.marker);
michael@0 6178 }
michael@0 6179 return markers;
michael@0 6180 },
michael@0 6181 findMarks: function(from, to) {
michael@0 6182 from = clipPos(this, from); to = clipPos(this, to);
michael@0 6183 var found = [], lineNo = from.line;
michael@0 6184 this.iter(from.line, to.line + 1, function(line) {
michael@0 6185 var spans = line.markedSpans;
michael@0 6186 if (spans) for (var i = 0; i < spans.length; i++) {
michael@0 6187 var span = spans[i];
michael@0 6188 if (!(lineNo == from.line && from.ch > span.to ||
michael@0 6189 span.from == null && lineNo != from.line||
michael@0 6190 lineNo == to.line && span.from > to.ch))
michael@0 6191 found.push(span.marker.parent || span.marker);
michael@0 6192 }
michael@0 6193 ++lineNo;
michael@0 6194 });
michael@0 6195 return found;
michael@0 6196 },
michael@0 6197 getAllMarks: function() {
michael@0 6198 var markers = [];
michael@0 6199 this.iter(function(line) {
michael@0 6200 var sps = line.markedSpans;
michael@0 6201 if (sps) for (var i = 0; i < sps.length; ++i)
michael@0 6202 if (sps[i].from != null) markers.push(sps[i].marker);
michael@0 6203 });
michael@0 6204 return markers;
michael@0 6205 },
michael@0 6206
michael@0 6207 posFromIndex: function(off) {
michael@0 6208 var ch, lineNo = this.first;
michael@0 6209 this.iter(function(line) {
michael@0 6210 var sz = line.text.length + 1;
michael@0 6211 if (sz > off) { ch = off; return true; }
michael@0 6212 off -= sz;
michael@0 6213 ++lineNo;
michael@0 6214 });
michael@0 6215 return clipPos(this, Pos(lineNo, ch));
michael@0 6216 },
michael@0 6217 indexFromPos: function (coords) {
michael@0 6218 coords = clipPos(this, coords);
michael@0 6219 var index = coords.ch;
michael@0 6220 if (coords.line < this.first || coords.ch < 0) return 0;
michael@0 6221 this.iter(this.first, coords.line, function (line) {
michael@0 6222 index += line.text.length + 1;
michael@0 6223 });
michael@0 6224 return index;
michael@0 6225 },
michael@0 6226
michael@0 6227 copy: function(copyHistory) {
michael@0 6228 var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first);
michael@0 6229 doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
michael@0 6230 doc.sel = this.sel;
michael@0 6231 doc.extend = false;
michael@0 6232 if (copyHistory) {
michael@0 6233 doc.history.undoDepth = this.history.undoDepth;
michael@0 6234 doc.setHistory(this.getHistory());
michael@0 6235 }
michael@0 6236 return doc;
michael@0 6237 },
michael@0 6238
michael@0 6239 linkedDoc: function(options) {
michael@0 6240 if (!options) options = {};
michael@0 6241 var from = this.first, to = this.first + this.size;
michael@0 6242 if (options.from != null && options.from > from) from = options.from;
michael@0 6243 if (options.to != null && options.to < to) to = options.to;
michael@0 6244 var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from);
michael@0 6245 if (options.sharedHist) copy.history = this.history;
michael@0 6246 (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
michael@0 6247 copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
michael@0 6248 return copy;
michael@0 6249 },
michael@0 6250 unlinkDoc: function(other) {
michael@0 6251 if (other instanceof CodeMirror) other = other.doc;
michael@0 6252 if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
michael@0 6253 var link = this.linked[i];
michael@0 6254 if (link.doc != other) continue;
michael@0 6255 this.linked.splice(i, 1);
michael@0 6256 other.unlinkDoc(this);
michael@0 6257 break;
michael@0 6258 }
michael@0 6259 // If the histories were shared, split them again
michael@0 6260 if (other.history == this.history) {
michael@0 6261 var splitIds = [other.id];
michael@0 6262 linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
michael@0 6263 other.history = new History(null);
michael@0 6264 other.history.done = copyHistoryArray(this.history.done, splitIds);
michael@0 6265 other.history.undone = copyHistoryArray(this.history.undone, splitIds);
michael@0 6266 }
michael@0 6267 },
michael@0 6268 iterLinkedDocs: function(f) {linkedDocs(this, f);},
michael@0 6269
michael@0 6270 getMode: function() {return this.mode;},
michael@0 6271 getEditor: function() {return this.cm;}
michael@0 6272 });
michael@0 6273
michael@0 6274 // Public alias.
michael@0 6275 Doc.prototype.eachLine = Doc.prototype.iter;
michael@0 6276
michael@0 6277 // Set up methods on CodeMirror's prototype to redirect to the editor's document.
michael@0 6278 var dontDelegate = "iter insert remove copy getEditor".split(" ");
michael@0 6279 for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
michael@0 6280 CodeMirror.prototype[prop] = (function(method) {
michael@0 6281 return function() {return method.apply(this.doc, arguments);};
michael@0 6282 })(Doc.prototype[prop]);
michael@0 6283
michael@0 6284 eventMixin(Doc);
michael@0 6285
michael@0 6286 // Call f for all linked documents.
michael@0 6287 function linkedDocs(doc, f, sharedHistOnly) {
michael@0 6288 function propagate(doc, skip, sharedHist) {
michael@0 6289 if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
michael@0 6290 var rel = doc.linked[i];
michael@0 6291 if (rel.doc == skip) continue;
michael@0 6292 var shared = sharedHist && rel.sharedHist;
michael@0 6293 if (sharedHistOnly && !shared) continue;
michael@0 6294 f(rel.doc, shared);
michael@0 6295 propagate(rel.doc, doc, shared);
michael@0 6296 }
michael@0 6297 }
michael@0 6298 propagate(doc, null, true);
michael@0 6299 }
michael@0 6300
michael@0 6301 // Attach a document to an editor.
michael@0 6302 function attachDoc(cm, doc) {
michael@0 6303 if (doc.cm) throw new Error("This document is already in use.");
michael@0 6304 cm.doc = doc;
michael@0 6305 doc.cm = cm;
michael@0 6306 estimateLineHeights(cm);
michael@0 6307 loadMode(cm);
michael@0 6308 if (!cm.options.lineWrapping) findMaxLine(cm);
michael@0 6309 cm.options.mode = doc.modeOption;
michael@0 6310 regChange(cm);
michael@0 6311 }
michael@0 6312
michael@0 6313 // LINE UTILITIES
michael@0 6314
michael@0 6315 // Find the line object corresponding to the given line number.
michael@0 6316 function getLine(doc, n) {
michael@0 6317 n -= doc.first;
michael@0 6318 if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
michael@0 6319 for (var chunk = doc; !chunk.lines;) {
michael@0 6320 for (var i = 0;; ++i) {
michael@0 6321 var child = chunk.children[i], sz = child.chunkSize();
michael@0 6322 if (n < sz) { chunk = child; break; }
michael@0 6323 n -= sz;
michael@0 6324 }
michael@0 6325 }
michael@0 6326 return chunk.lines[n];
michael@0 6327 }
michael@0 6328
michael@0 6329 // Get the part of a document between two positions, as an array of
michael@0 6330 // strings.
michael@0 6331 function getBetween(doc, start, end) {
michael@0 6332 var out = [], n = start.line;
michael@0 6333 doc.iter(start.line, end.line + 1, function(line) {
michael@0 6334 var text = line.text;
michael@0 6335 if (n == end.line) text = text.slice(0, end.ch);
michael@0 6336 if (n == start.line) text = text.slice(start.ch);
michael@0 6337 out.push(text);
michael@0 6338 ++n;
michael@0 6339 });
michael@0 6340 return out;
michael@0 6341 }
michael@0 6342 // Get the lines between from and to, as array of strings.
michael@0 6343 function getLines(doc, from, to) {
michael@0 6344 var out = [];
michael@0 6345 doc.iter(from, to, function(line) { out.push(line.text); });
michael@0 6346 return out;
michael@0 6347 }
michael@0 6348
michael@0 6349 // Update the height of a line, propagating the height change
michael@0 6350 // upwards to parent nodes.
michael@0 6351 function updateLineHeight(line, height) {
michael@0 6352 var diff = height - line.height;
michael@0 6353 if (diff) for (var n = line; n; n = n.parent) n.height += diff;
michael@0 6354 }
michael@0 6355
michael@0 6356 // Given a line object, find its line number by walking up through
michael@0 6357 // its parent links.
michael@0 6358 function lineNo(line) {
michael@0 6359 if (line.parent == null) return null;
michael@0 6360 var cur = line.parent, no = indexOf(cur.lines, line);
michael@0 6361 for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
michael@0 6362 for (var i = 0;; ++i) {
michael@0 6363 if (chunk.children[i] == cur) break;
michael@0 6364 no += chunk.children[i].chunkSize();
michael@0 6365 }
michael@0 6366 }
michael@0 6367 return no + cur.first;
michael@0 6368 }
michael@0 6369
michael@0 6370 // Find the line at the given vertical position, using the height
michael@0 6371 // information in the document tree.
michael@0 6372 function lineAtHeight(chunk, h) {
michael@0 6373 var n = chunk.first;
michael@0 6374 outer: do {
michael@0 6375 for (var i = 0; i < chunk.children.length; ++i) {
michael@0 6376 var child = chunk.children[i], ch = child.height;
michael@0 6377 if (h < ch) { chunk = child; continue outer; }
michael@0 6378 h -= ch;
michael@0 6379 n += child.chunkSize();
michael@0 6380 }
michael@0 6381 return n;
michael@0 6382 } while (!chunk.lines);
michael@0 6383 for (var i = 0; i < chunk.lines.length; ++i) {
michael@0 6384 var line = chunk.lines[i], lh = line.height;
michael@0 6385 if (h < lh) break;
michael@0 6386 h -= lh;
michael@0 6387 }
michael@0 6388 return n + i;
michael@0 6389 }
michael@0 6390
michael@0 6391
michael@0 6392 // Find the height above the given line.
michael@0 6393 function heightAtLine(lineObj) {
michael@0 6394 lineObj = visualLine(lineObj);
michael@0 6395
michael@0 6396 var h = 0, chunk = lineObj.parent;
michael@0 6397 for (var i = 0; i < chunk.lines.length; ++i) {
michael@0 6398 var line = chunk.lines[i];
michael@0 6399 if (line == lineObj) break;
michael@0 6400 else h += line.height;
michael@0 6401 }
michael@0 6402 for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
michael@0 6403 for (var i = 0; i < p.children.length; ++i) {
michael@0 6404 var cur = p.children[i];
michael@0 6405 if (cur == chunk) break;
michael@0 6406 else h += cur.height;
michael@0 6407 }
michael@0 6408 }
michael@0 6409 return h;
michael@0 6410 }
michael@0 6411
michael@0 6412 // Get the bidi ordering for the given line (and cache it). Returns
michael@0 6413 // false for lines that are fully left-to-right, and an array of
michael@0 6414 // BidiSpan objects otherwise.
michael@0 6415 function getOrder(line) {
michael@0 6416 var order = line.order;
michael@0 6417 if (order == null) order = line.order = bidiOrdering(line.text);
michael@0 6418 return order;
michael@0 6419 }
michael@0 6420
michael@0 6421 // HISTORY
michael@0 6422
michael@0 6423 function History(startGen) {
michael@0 6424 // Arrays of change events and selections. Doing something adds an
michael@0 6425 // event to done and clears undo. Undoing moves events from done
michael@0 6426 // to undone, redoing moves them in the other direction.
michael@0 6427 this.done = []; this.undone = [];
michael@0 6428 this.undoDepth = Infinity;
michael@0 6429 // Used to track when changes can be merged into a single undo
michael@0 6430 // event
michael@0 6431 this.lastModTime = this.lastSelTime = 0;
michael@0 6432 this.lastOp = null;
michael@0 6433 this.lastOrigin = this.lastSelOrigin = null;
michael@0 6434 // Used by the isClean() method
michael@0 6435 this.generation = this.maxGeneration = startGen || 1;
michael@0 6436 }
michael@0 6437
michael@0 6438 // Create a history change event from an updateDoc-style change
michael@0 6439 // object.
michael@0 6440 function historyChangeFromChange(doc, change) {
michael@0 6441 var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
michael@0 6442 attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
michael@0 6443 linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
michael@0 6444 return histChange;
michael@0 6445 }
michael@0 6446
michael@0 6447 // Pop all selection events off the end of a history array. Stop at
michael@0 6448 // a change event.
michael@0 6449 function clearSelectionEvents(array) {
michael@0 6450 while (array.length) {
michael@0 6451 var last = lst(array);
michael@0 6452 if (last.ranges) array.pop();
michael@0 6453 else break;
michael@0 6454 }
michael@0 6455 }
michael@0 6456
michael@0 6457 // Find the top change event in the history. Pop off selection
michael@0 6458 // events that are in the way.
michael@0 6459 function lastChangeEvent(hist, force) {
michael@0 6460 if (force) {
michael@0 6461 clearSelectionEvents(hist.done);
michael@0 6462 return lst(hist.done);
michael@0 6463 } else if (hist.done.length && !lst(hist.done).ranges) {
michael@0 6464 return lst(hist.done);
michael@0 6465 } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
michael@0 6466 hist.done.pop();
michael@0 6467 return lst(hist.done);
michael@0 6468 }
michael@0 6469 }
michael@0 6470
michael@0 6471 // Register a change in the history. Merges changes that are within
michael@0 6472 // a single operation, ore are close together with an origin that
michael@0 6473 // allows merging (starting with "+") into a single event.
michael@0 6474 function addChangeToHistory(doc, change, selAfter, opId) {
michael@0 6475 var hist = doc.history;
michael@0 6476 hist.undone.length = 0;
michael@0 6477 var time = +new Date, cur;
michael@0 6478
michael@0 6479 if ((hist.lastOp == opId ||
michael@0 6480 hist.lastOrigin == change.origin && change.origin &&
michael@0 6481 ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
michael@0 6482 change.origin.charAt(0) == "*")) &&
michael@0 6483 (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
michael@0 6484 // Merge this change into the last event
michael@0 6485 var last = lst(cur.changes);
michael@0 6486 if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
michael@0 6487 // Optimized case for simple insertion -- don't want to add
michael@0 6488 // new changesets for every character typed
michael@0 6489 last.to = changeEnd(change);
michael@0 6490 } else {
michael@0 6491 // Add new sub-event
michael@0 6492 cur.changes.push(historyChangeFromChange(doc, change));
michael@0 6493 }
michael@0 6494 } else {
michael@0 6495 // Can not be merged, start a new event.
michael@0 6496 var before = lst(hist.done);
michael@0 6497 if (!before || !before.ranges)
michael@0 6498 pushSelectionToHistory(doc.sel, hist.done);
michael@0 6499 cur = {changes: [historyChangeFromChange(doc, change)],
michael@0 6500 generation: hist.generation};
michael@0 6501 hist.done.push(cur);
michael@0 6502 while (hist.done.length > hist.undoDepth) {
michael@0 6503 hist.done.shift();
michael@0 6504 if (!hist.done[0].ranges) hist.done.shift();
michael@0 6505 }
michael@0 6506 }
michael@0 6507 hist.done.push(selAfter);
michael@0 6508 hist.generation = ++hist.maxGeneration;
michael@0 6509 hist.lastModTime = hist.lastSelTime = time;
michael@0 6510 hist.lastOp = opId;
michael@0 6511 hist.lastOrigin = hist.lastSelOrigin = change.origin;
michael@0 6512
michael@0 6513 if (!last) signal(doc, "historyAdded");
michael@0 6514 }
michael@0 6515
michael@0 6516 function selectionEventCanBeMerged(doc, origin, prev, sel) {
michael@0 6517 var ch = origin.charAt(0);
michael@0 6518 return ch == "*" ||
michael@0 6519 ch == "+" &&
michael@0 6520 prev.ranges.length == sel.ranges.length &&
michael@0 6521 prev.somethingSelected() == sel.somethingSelected() &&
michael@0 6522 new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
michael@0 6523 }
michael@0 6524
michael@0 6525 // Called whenever the selection changes, sets the new selection as
michael@0 6526 // the pending selection in the history, and pushes the old pending
michael@0 6527 // selection into the 'done' array when it was significantly
michael@0 6528 // different (in number of selected ranges, emptiness, or time).
michael@0 6529 function addSelectionToHistory(doc, sel, opId, options) {
michael@0 6530 var hist = doc.history, origin = options && options.origin;
michael@0 6531
michael@0 6532 // A new event is started when the previous origin does not match
michael@0 6533 // the current, or the origins don't allow matching. Origins
michael@0 6534 // starting with * are always merged, those starting with + are
michael@0 6535 // merged when similar and close together in time.
michael@0 6536 if (opId == hist.lastOp ||
michael@0 6537 (origin && hist.lastSelOrigin == origin &&
michael@0 6538 (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
michael@0 6539 selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
michael@0 6540 hist.done[hist.done.length - 1] = sel;
michael@0 6541 else
michael@0 6542 pushSelectionToHistory(sel, hist.done);
michael@0 6543
michael@0 6544 hist.lastSelTime = +new Date;
michael@0 6545 hist.lastSelOrigin = origin;
michael@0 6546 hist.lastOp = opId;
michael@0 6547 if (options && options.clearRedo !== false)
michael@0 6548 clearSelectionEvents(hist.undone);
michael@0 6549 }
michael@0 6550
michael@0 6551 function pushSelectionToHistory(sel, dest) {
michael@0 6552 var top = lst(dest);
michael@0 6553 if (!(top && top.ranges && top.equals(sel)))
michael@0 6554 dest.push(sel);
michael@0 6555 }
michael@0 6556
michael@0 6557 // Used to store marked span information in the history.
michael@0 6558 function attachLocalSpans(doc, change, from, to) {
michael@0 6559 var existing = change["spans_" + doc.id], n = 0;
michael@0 6560 doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
michael@0 6561 if (line.markedSpans)
michael@0 6562 (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
michael@0 6563 ++n;
michael@0 6564 });
michael@0 6565 }
michael@0 6566
michael@0 6567 // When un/re-doing restores text containing marked spans, those
michael@0 6568 // that have been explicitly cleared should not be restored.
michael@0 6569 function removeClearedSpans(spans) {
michael@0 6570 if (!spans) return null;
michael@0 6571 for (var i = 0, out; i < spans.length; ++i) {
michael@0 6572 if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
michael@0 6573 else if (out) out.push(spans[i]);
michael@0 6574 }
michael@0 6575 return !out ? spans : out.length ? out : null;
michael@0 6576 }
michael@0 6577
michael@0 6578 // Retrieve and filter the old marked spans stored in a change event.
michael@0 6579 function getOldSpans(doc, change) {
michael@0 6580 var found = change["spans_" + doc.id];
michael@0 6581 if (!found) return null;
michael@0 6582 for (var i = 0, nw = []; i < change.text.length; ++i)
michael@0 6583 nw.push(removeClearedSpans(found[i]));
michael@0 6584 return nw;
michael@0 6585 }
michael@0 6586
michael@0 6587 // Used both to provide a JSON-safe object in .getHistory, and, when
michael@0 6588 // detaching a document, to split the history in two
michael@0 6589 function copyHistoryArray(events, newGroup, instantiateSel) {
michael@0 6590 for (var i = 0, copy = []; i < events.length; ++i) {
michael@0 6591 var event = events[i];
michael@0 6592 if (event.ranges) {
michael@0 6593 copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
michael@0 6594 continue;
michael@0 6595 }
michael@0 6596 var changes = event.changes, newChanges = [];
michael@0 6597 copy.push({changes: newChanges});
michael@0 6598 for (var j = 0; j < changes.length; ++j) {
michael@0 6599 var change = changes[j], m;
michael@0 6600 newChanges.push({from: change.from, to: change.to, text: change.text});
michael@0 6601 if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
michael@0 6602 if (indexOf(newGroup, Number(m[1])) > -1) {
michael@0 6603 lst(newChanges)[prop] = change[prop];
michael@0 6604 delete change[prop];
michael@0 6605 }
michael@0 6606 }
michael@0 6607 }
michael@0 6608 }
michael@0 6609 return copy;
michael@0 6610 }
michael@0 6611
michael@0 6612 // Rebasing/resetting history to deal with externally-sourced changes
michael@0 6613
michael@0 6614 function rebaseHistSelSingle(pos, from, to, diff) {
michael@0 6615 if (to < pos.line) {
michael@0 6616 pos.line += diff;
michael@0 6617 } else if (from < pos.line) {
michael@0 6618 pos.line = from;
michael@0 6619 pos.ch = 0;
michael@0 6620 }
michael@0 6621 }
michael@0 6622
michael@0 6623 // Tries to rebase an array of history events given a change in the
michael@0 6624 // document. If the change touches the same lines as the event, the
michael@0 6625 // event, and everything 'behind' it, is discarded. If the change is
michael@0 6626 // before the event, the event's positions are updated. Uses a
michael@0 6627 // copy-on-write scheme for the positions, to avoid having to
michael@0 6628 // reallocate them all on every rebase, but also avoid problems with
michael@0 6629 // shared position objects being unsafely updated.
michael@0 6630 function rebaseHistArray(array, from, to, diff) {
michael@0 6631 for (var i = 0; i < array.length; ++i) {
michael@0 6632 var sub = array[i], ok = true;
michael@0 6633 if (sub.ranges) {
michael@0 6634 if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
michael@0 6635 for (var j = 0; j < sub.ranges.length; j++) {
michael@0 6636 rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
michael@0 6637 rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
michael@0 6638 }
michael@0 6639 continue;
michael@0 6640 }
michael@0 6641 for (var j = 0; j < sub.changes.length; ++j) {
michael@0 6642 var cur = sub.changes[j];
michael@0 6643 if (to < cur.from.line) {
michael@0 6644 cur.from = Pos(cur.from.line + diff, cur.from.ch);
michael@0 6645 cur.to = Pos(cur.to.line + diff, cur.to.ch);
michael@0 6646 } else if (from <= cur.to.line) {
michael@0 6647 ok = false;
michael@0 6648 break;
michael@0 6649 }
michael@0 6650 }
michael@0 6651 if (!ok) {
michael@0 6652 array.splice(0, i + 1);
michael@0 6653 i = 0;
michael@0 6654 }
michael@0 6655 }
michael@0 6656 }
michael@0 6657
michael@0 6658 function rebaseHist(hist, change) {
michael@0 6659 var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
michael@0 6660 rebaseHistArray(hist.done, from, to, diff);
michael@0 6661 rebaseHistArray(hist.undone, from, to, diff);
michael@0 6662 }
michael@0 6663
michael@0 6664 // EVENT UTILITIES
michael@0 6665
michael@0 6666 // Due to the fact that we still support jurassic IE versions, some
michael@0 6667 // compatibility wrappers are needed.
michael@0 6668
michael@0 6669 var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
michael@0 6670 if (e.preventDefault) e.preventDefault();
michael@0 6671 else e.returnValue = false;
michael@0 6672 };
michael@0 6673 var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
michael@0 6674 if (e.stopPropagation) e.stopPropagation();
michael@0 6675 else e.cancelBubble = true;
michael@0 6676 };
michael@0 6677 function e_defaultPrevented(e) {
michael@0 6678 return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
michael@0 6679 }
michael@0 6680 var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
michael@0 6681
michael@0 6682 function e_target(e) {return e.target || e.srcElement;}
michael@0 6683 function e_button(e) {
michael@0 6684 var b = e.which;
michael@0 6685 if (b == null) {
michael@0 6686 if (e.button & 1) b = 1;
michael@0 6687 else if (e.button & 2) b = 3;
michael@0 6688 else if (e.button & 4) b = 2;
michael@0 6689 }
michael@0 6690 if (mac && e.ctrlKey && b == 1) b = 3;
michael@0 6691 return b;
michael@0 6692 }
michael@0 6693
michael@0 6694 // EVENT HANDLING
michael@0 6695
michael@0 6696 // Lightweight event framework. on/off also work on DOM nodes,
michael@0 6697 // registering native DOM handlers.
michael@0 6698
michael@0 6699 var on = CodeMirror.on = function(emitter, type, f) {
michael@0 6700 if (emitter.addEventListener)
michael@0 6701 emitter.addEventListener(type, f, false);
michael@0 6702 else if (emitter.attachEvent)
michael@0 6703 emitter.attachEvent("on" + type, f);
michael@0 6704 else {
michael@0 6705 var map = emitter._handlers || (emitter._handlers = {});
michael@0 6706 var arr = map[type] || (map[type] = []);
michael@0 6707 arr.push(f);
michael@0 6708 }
michael@0 6709 };
michael@0 6710
michael@0 6711 var off = CodeMirror.off = function(emitter, type, f) {
michael@0 6712 if (emitter.removeEventListener)
michael@0 6713 emitter.removeEventListener(type, f, false);
michael@0 6714 else if (emitter.detachEvent)
michael@0 6715 emitter.detachEvent("on" + type, f);
michael@0 6716 else {
michael@0 6717 var arr = emitter._handlers && emitter._handlers[type];
michael@0 6718 if (!arr) return;
michael@0 6719 for (var i = 0; i < arr.length; ++i)
michael@0 6720 if (arr[i] == f) { arr.splice(i, 1); break; }
michael@0 6721 }
michael@0 6722 };
michael@0 6723
michael@0 6724 var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
michael@0 6725 var arr = emitter._handlers && emitter._handlers[type];
michael@0 6726 if (!arr) return;
michael@0 6727 var args = Array.prototype.slice.call(arguments, 2);
michael@0 6728 for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
michael@0 6729 };
michael@0 6730
michael@0 6731 // Often, we want to signal events at a point where we are in the
michael@0 6732 // middle of some work, but don't want the handler to start calling
michael@0 6733 // other methods on the editor, which might be in an inconsistent
michael@0 6734 // state or simply not expect any other events to happen.
michael@0 6735 // signalLater looks whether there are any handlers, and schedules
michael@0 6736 // them to be executed when the last operation ends, or, if no
michael@0 6737 // operation is active, when a timeout fires.
michael@0 6738 var delayedCallbacks, delayedCallbackDepth = 0;
michael@0 6739 function signalLater(emitter, type /*, values...*/) {
michael@0 6740 var arr = emitter._handlers && emitter._handlers[type];
michael@0 6741 if (!arr) return;
michael@0 6742 var args = Array.prototype.slice.call(arguments, 2);
michael@0 6743 if (!delayedCallbacks) {
michael@0 6744 ++delayedCallbackDepth;
michael@0 6745 delayedCallbacks = [];
michael@0 6746 setTimeout(fireDelayed, 0);
michael@0 6747 }
michael@0 6748 function bnd(f) {return function(){f.apply(null, args);};};
michael@0 6749 for (var i = 0; i < arr.length; ++i)
michael@0 6750 delayedCallbacks.push(bnd(arr[i]));
michael@0 6751 }
michael@0 6752
michael@0 6753 function fireDelayed() {
michael@0 6754 --delayedCallbackDepth;
michael@0 6755 var delayed = delayedCallbacks;
michael@0 6756 delayedCallbacks = null;
michael@0 6757 for (var i = 0; i < delayed.length; ++i) delayed[i]();
michael@0 6758 }
michael@0 6759
michael@0 6760 // The DOM events that CodeMirror handles can be overridden by
michael@0 6761 // registering a (non-DOM) handler on the editor for the event name,
michael@0 6762 // and preventDefault-ing the event in that handler.
michael@0 6763 function signalDOMEvent(cm, e, override) {
michael@0 6764 signal(cm, override || e.type, cm, e);
michael@0 6765 return e_defaultPrevented(e) || e.codemirrorIgnore;
michael@0 6766 }
michael@0 6767
michael@0 6768 function hasHandler(emitter, type) {
michael@0 6769 var arr = emitter._handlers && emitter._handlers[type];
michael@0 6770 return arr && arr.length > 0;
michael@0 6771 }
michael@0 6772
michael@0 6773 // Add on and off methods to a constructor's prototype, to make
michael@0 6774 // registering events on such objects more convenient.
michael@0 6775 function eventMixin(ctor) {
michael@0 6776 ctor.prototype.on = function(type, f) {on(this, type, f);};
michael@0 6777 ctor.prototype.off = function(type, f) {off(this, type, f);};
michael@0 6778 }
michael@0 6779
michael@0 6780 // MISC UTILITIES
michael@0 6781
michael@0 6782 // Number of pixels added to scroller and sizer to hide scrollbar
michael@0 6783 var scrollerCutOff = 30;
michael@0 6784
michael@0 6785 // Returned or thrown by various protocols to signal 'I'm not
michael@0 6786 // handling this'.
michael@0 6787 var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
michael@0 6788
michael@0 6789 // Reused option objects for setSelection & friends
michael@0 6790 var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
michael@0 6791
michael@0 6792 function Delayed() {this.id = null;}
michael@0 6793 Delayed.prototype.set = function(ms, f) {
michael@0 6794 clearTimeout(this.id);
michael@0 6795 this.id = setTimeout(f, ms);
michael@0 6796 };
michael@0 6797
michael@0 6798 // Counts the column offset in a string, taking tabs into account.
michael@0 6799 // Used mostly to find indentation.
michael@0 6800 var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
michael@0 6801 if (end == null) {
michael@0 6802 end = string.search(/[^\s\u00a0]/);
michael@0 6803 if (end == -1) end = string.length;
michael@0 6804 }
michael@0 6805 for (var i = startIndex || 0, n = startValue || 0;;) {
michael@0 6806 var nextTab = string.indexOf("\t", i);
michael@0 6807 if (nextTab < 0 || nextTab >= end)
michael@0 6808 return n + (end - i);
michael@0 6809 n += nextTab - i;
michael@0 6810 n += tabSize - (n % tabSize);
michael@0 6811 i = nextTab + 1;
michael@0 6812 }
michael@0 6813 };
michael@0 6814
michael@0 6815 // The inverse of countColumn -- find the offset that corresponds to
michael@0 6816 // a particular column.
michael@0 6817 function findColumn(string, goal, tabSize) {
michael@0 6818 for (var pos = 0, col = 0;;) {
michael@0 6819 var nextTab = string.indexOf("\t", pos);
michael@0 6820 if (nextTab == -1) nextTab = string.length;
michael@0 6821 var skipped = nextTab - pos;
michael@0 6822 if (nextTab == string.length || col + skipped >= goal)
michael@0 6823 return pos + Math.min(skipped, goal - col);
michael@0 6824 col += nextTab - pos;
michael@0 6825 col += tabSize - (col % tabSize);
michael@0 6826 pos = nextTab + 1;
michael@0 6827 if (col >= goal) return pos;
michael@0 6828 }
michael@0 6829 }
michael@0 6830
michael@0 6831 var spaceStrs = [""];
michael@0 6832 function spaceStr(n) {
michael@0 6833 while (spaceStrs.length <= n)
michael@0 6834 spaceStrs.push(lst(spaceStrs) + " ");
michael@0 6835 return spaceStrs[n];
michael@0 6836 }
michael@0 6837
michael@0 6838 function lst(arr) { return arr[arr.length-1]; }
michael@0 6839
michael@0 6840 var selectInput = function(node) { node.select(); };
michael@0 6841 if (ios) // Mobile Safari apparently has a bug where select() is broken.
michael@0 6842 selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
michael@0 6843 else if (ie) // Suppress mysterious IE10 errors
michael@0 6844 selectInput = function(node) { try { node.select(); } catch(_e) {} };
michael@0 6845
michael@0 6846 function indexOf(array, elt) {
michael@0 6847 for (var i = 0; i < array.length; ++i)
michael@0 6848 if (array[i] == elt) return i;
michael@0 6849 return -1;
michael@0 6850 }
michael@0 6851 if ([].indexOf) indexOf = function(array, elt) { return array.indexOf(elt); };
michael@0 6852 function map(array, f) {
michael@0 6853 var out = [];
michael@0 6854 for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
michael@0 6855 return out;
michael@0 6856 }
michael@0 6857 if ([].map) map = function(array, f) { return array.map(f); };
michael@0 6858
michael@0 6859 function createObj(base, props) {
michael@0 6860 var inst;
michael@0 6861 if (Object.create) {
michael@0 6862 inst = Object.create(base);
michael@0 6863 } else {
michael@0 6864 var ctor = function() {};
michael@0 6865 ctor.prototype = base;
michael@0 6866 inst = new ctor();
michael@0 6867 }
michael@0 6868 if (props) copyObj(props, inst);
michael@0 6869 return inst;
michael@0 6870 };
michael@0 6871
michael@0 6872 function copyObj(obj, target) {
michael@0 6873 if (!target) target = {};
michael@0 6874 for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop];
michael@0 6875 return target;
michael@0 6876 }
michael@0 6877
michael@0 6878 function bind(f) {
michael@0 6879 var args = Array.prototype.slice.call(arguments, 1);
michael@0 6880 return function(){return f.apply(null, args);};
michael@0 6881 }
michael@0 6882
michael@0 6883 var nonASCIISingleCaseWordChar = /[\u00df\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
michael@0 6884 var isWordChar = CodeMirror.isWordChar = function(ch) {
michael@0 6885 return /\w/.test(ch) || ch > "\x80" &&
michael@0 6886 (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
michael@0 6887 };
michael@0 6888
michael@0 6889 function isEmpty(obj) {
michael@0 6890 for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
michael@0 6891 return true;
michael@0 6892 }
michael@0 6893
michael@0 6894 // Extending unicode characters. A series of a non-extending char +
michael@0 6895 // any number of extending chars is treated as a single unit as far
michael@0 6896 // as editing and measuring is concerned. This is not fully correct,
michael@0 6897 // since some scripts/fonts/browsers also treat other configurations
michael@0 6898 // of code points as a group.
michael@0 6899 var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
michael@0 6900 function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
michael@0 6901
michael@0 6902 // DOM UTILITIES
michael@0 6903
michael@0 6904 function elt(tag, content, className, style) {
michael@0 6905 var e = document.createElement(tag);
michael@0 6906 if (className) e.className = className;
michael@0 6907 if (style) e.style.cssText = style;
michael@0 6908 if (typeof content == "string") e.appendChild(document.createTextNode(content));
michael@0 6909 else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
michael@0 6910 return e;
michael@0 6911 }
michael@0 6912
michael@0 6913 var range;
michael@0 6914 if (document.createRange) range = function(node, start, end) {
michael@0 6915 var r = document.createRange();
michael@0 6916 r.setEnd(node, end);
michael@0 6917 r.setStart(node, start);
michael@0 6918 return r;
michael@0 6919 };
michael@0 6920 else range = function(node, start, end) {
michael@0 6921 var r = document.body.createTextRange();
michael@0 6922 r.moveToElementText(node.parentNode);
michael@0 6923 r.collapse(true);
michael@0 6924 r.moveEnd("character", end);
michael@0 6925 r.moveStart("character", start);
michael@0 6926 return r;
michael@0 6927 };
michael@0 6928
michael@0 6929 function removeChildren(e) {
michael@0 6930 for (var count = e.childNodes.length; count > 0; --count)
michael@0 6931 e.removeChild(e.firstChild);
michael@0 6932 return e;
michael@0 6933 }
michael@0 6934
michael@0 6935 function removeChildrenAndAdd(parent, e) {
michael@0 6936 return removeChildren(parent).appendChild(e);
michael@0 6937 }
michael@0 6938
michael@0 6939 function contains(parent, child) {
michael@0 6940 if (parent.contains)
michael@0 6941 return parent.contains(child);
michael@0 6942 while (child = child.parentNode)
michael@0 6943 if (child == parent) return true;
michael@0 6944 }
michael@0 6945
michael@0 6946 function activeElt() { return document.activeElement; }
michael@0 6947 // Older versions of IE throws unspecified error when touching
michael@0 6948 // document.activeElement in some cases (during loading, in iframe)
michael@0 6949 if (ie_upto10) activeElt = function() {
michael@0 6950 try { return document.activeElement; }
michael@0 6951 catch(e) { return document.body; }
michael@0 6952 };
michael@0 6953
michael@0 6954 // FEATURE DETECTION
michael@0 6955
michael@0 6956 // Detect drag-and-drop
michael@0 6957 var dragAndDrop = function() {
michael@0 6958 // There is *some* kind of drag-and-drop support in IE6-8, but I
michael@0 6959 // couldn't get it to work yet.
michael@0 6960 if (ie_upto8) return false;
michael@0 6961 var div = elt('div');
michael@0 6962 return "draggable" in div || "dragDrop" in div;
michael@0 6963 }();
michael@0 6964
michael@0 6965 var knownScrollbarWidth;
michael@0 6966 function scrollbarWidth(measure) {
michael@0 6967 if (knownScrollbarWidth != null) return knownScrollbarWidth;
michael@0 6968 var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll");
michael@0 6969 removeChildrenAndAdd(measure, test);
michael@0 6970 if (test.offsetWidth)
michael@0 6971 knownScrollbarWidth = test.offsetHeight - test.clientHeight;
michael@0 6972 return knownScrollbarWidth || 0;
michael@0 6973 }
michael@0 6974
michael@0 6975 var zwspSupported;
michael@0 6976 function zeroWidthElement(measure) {
michael@0 6977 if (zwspSupported == null) {
michael@0 6978 var test = elt("span", "\u200b");
michael@0 6979 removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
michael@0 6980 if (measure.firstChild.offsetHeight != 0)
michael@0 6981 zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_upto7;
michael@0 6982 }
michael@0 6983 if (zwspSupported) return elt("span", "\u200b");
michael@0 6984 else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
michael@0 6985 }
michael@0 6986
michael@0 6987 // Feature-detect IE's crummy client rect reporting for bidi text
michael@0 6988 var badBidiRects;
michael@0 6989 function hasBadBidiRects(measure) {
michael@0 6990 if (badBidiRects != null) return badBidiRects;
michael@0 6991 var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
michael@0 6992 var r0 = range(txt, 0, 1).getBoundingClientRect();
michael@0 6993 if (r0.left == r0.right) return false;
michael@0 6994 var r1 = range(txt, 1, 2).getBoundingClientRect();
michael@0 6995 return badBidiRects = (r1.right - r0.right < 3);
michael@0 6996 }
michael@0 6997
michael@0 6998 // See if "".split is the broken IE version, if so, provide an
michael@0 6999 // alternative way to split lines.
michael@0 7000 var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
michael@0 7001 var pos = 0, result = [], l = string.length;
michael@0 7002 while (pos <= l) {
michael@0 7003 var nl = string.indexOf("\n", pos);
michael@0 7004 if (nl == -1) nl = string.length;
michael@0 7005 var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
michael@0 7006 var rt = line.indexOf("\r");
michael@0 7007 if (rt != -1) {
michael@0 7008 result.push(line.slice(0, rt));
michael@0 7009 pos += rt + 1;
michael@0 7010 } else {
michael@0 7011 result.push(line);
michael@0 7012 pos = nl + 1;
michael@0 7013 }
michael@0 7014 }
michael@0 7015 return result;
michael@0 7016 } : function(string){return string.split(/\r\n?|\n/);};
michael@0 7017
michael@0 7018 var hasSelection = window.getSelection ? function(te) {
michael@0 7019 try { return te.selectionStart != te.selectionEnd; }
michael@0 7020 catch(e) { return false; }
michael@0 7021 } : function(te) {
michael@0 7022 try {var range = te.ownerDocument.selection.createRange();}
michael@0 7023 catch(e) {}
michael@0 7024 if (!range || range.parentElement() != te) return false;
michael@0 7025 return range.compareEndPoints("StartToEnd", range) != 0;
michael@0 7026 };
michael@0 7027
michael@0 7028 var hasCopyEvent = (function() {
michael@0 7029 var e = elt("div");
michael@0 7030 if ("oncopy" in e) return true;
michael@0 7031 e.setAttribute("oncopy", "return;");
michael@0 7032 return typeof e.oncopy == "function";
michael@0 7033 })();
michael@0 7034
michael@0 7035 // KEY NAMES
michael@0 7036
michael@0 7037 var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
michael@0 7038 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
michael@0 7039 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
michael@0 7040 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete",
michael@0 7041 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
michael@0 7042 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
michael@0 7043 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"};
michael@0 7044 CodeMirror.keyNames = keyNames;
michael@0 7045 (function() {
michael@0 7046 // Number keys
michael@0 7047 for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
michael@0 7048 // Alphabetic keys
michael@0 7049 for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
michael@0 7050 // Function keys
michael@0 7051 for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
michael@0 7052 })();
michael@0 7053
michael@0 7054 // BIDI HELPERS
michael@0 7055
michael@0 7056 function iterateBidiSections(order, from, to, f) {
michael@0 7057 if (!order) return f(from, to, "ltr");
michael@0 7058 var found = false;
michael@0 7059 for (var i = 0; i < order.length; ++i) {
michael@0 7060 var part = order[i];
michael@0 7061 if (part.from < to && part.to > from || from == to && part.to == from) {
michael@0 7062 f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
michael@0 7063 found = true;
michael@0 7064 }
michael@0 7065 }
michael@0 7066 if (!found) f(from, to, "ltr");
michael@0 7067 }
michael@0 7068
michael@0 7069 function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
michael@0 7070 function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
michael@0 7071
michael@0 7072 function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
michael@0 7073 function lineRight(line) {
michael@0 7074 var order = getOrder(line);
michael@0 7075 if (!order) return line.text.length;
michael@0 7076 return bidiRight(lst(order));
michael@0 7077 }
michael@0 7078
michael@0 7079 function lineStart(cm, lineN) {
michael@0 7080 var line = getLine(cm.doc, lineN);
michael@0 7081 var visual = visualLine(line);
michael@0 7082 if (visual != line) lineN = lineNo(visual);
michael@0 7083 var order = getOrder(visual);
michael@0 7084 var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
michael@0 7085 return Pos(lineN, ch);
michael@0 7086 }
michael@0 7087 function lineEnd(cm, lineN) {
michael@0 7088 var merged, line = getLine(cm.doc, lineN);
michael@0 7089 while (merged = collapsedSpanAtEnd(line)) {
michael@0 7090 line = merged.find(1, true).line;
michael@0 7091 lineN = null;
michael@0 7092 }
michael@0 7093 var order = getOrder(line);
michael@0 7094 var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
michael@0 7095 return Pos(lineN == null ? lineNo(line) : lineN, ch);
michael@0 7096 }
michael@0 7097
michael@0 7098 function compareBidiLevel(order, a, b) {
michael@0 7099 var linedir = order[0].level;
michael@0 7100 if (a == linedir) return true;
michael@0 7101 if (b == linedir) return false;
michael@0 7102 return a < b;
michael@0 7103 }
michael@0 7104 var bidiOther;
michael@0 7105 function getBidiPartAt(order, pos) {
michael@0 7106 bidiOther = null;
michael@0 7107 for (var i = 0, found; i < order.length; ++i) {
michael@0 7108 var cur = order[i];
michael@0 7109 if (cur.from < pos && cur.to > pos) return i;
michael@0 7110 if ((cur.from == pos || cur.to == pos)) {
michael@0 7111 if (found == null) {
michael@0 7112 found = i;
michael@0 7113 } else if (compareBidiLevel(order, cur.level, order[found].level)) {
michael@0 7114 if (cur.from != cur.to) bidiOther = found;
michael@0 7115 return i;
michael@0 7116 } else {
michael@0 7117 if (cur.from != cur.to) bidiOther = i;
michael@0 7118 return found;
michael@0 7119 }
michael@0 7120 }
michael@0 7121 }
michael@0 7122 return found;
michael@0 7123 }
michael@0 7124
michael@0 7125 function moveInLine(line, pos, dir, byUnit) {
michael@0 7126 if (!byUnit) return pos + dir;
michael@0 7127 do pos += dir;
michael@0 7128 while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
michael@0 7129 return pos;
michael@0 7130 }
michael@0 7131
michael@0 7132 // This is needed in order to move 'visually' through bi-directional
michael@0 7133 // text -- i.e., pressing left should make the cursor go left, even
michael@0 7134 // when in RTL text. The tricky part is the 'jumps', where RTL and
michael@0 7135 // LTR text touch each other. This often requires the cursor offset
michael@0 7136 // to move more than one unit, in order to visually move one unit.
michael@0 7137 function moveVisually(line, start, dir, byUnit) {
michael@0 7138 var bidi = getOrder(line);
michael@0 7139 if (!bidi) return moveLogically(line, start, dir, byUnit);
michael@0 7140 var pos = getBidiPartAt(bidi, start), part = bidi[pos];
michael@0 7141 var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
michael@0 7142
michael@0 7143 for (;;) {
michael@0 7144 if (target > part.from && target < part.to) return target;
michael@0 7145 if (target == part.from || target == part.to) {
michael@0 7146 if (getBidiPartAt(bidi, target) == pos) return target;
michael@0 7147 part = bidi[pos += dir];
michael@0 7148 return (dir > 0) == part.level % 2 ? part.to : part.from;
michael@0 7149 } else {
michael@0 7150 part = bidi[pos += dir];
michael@0 7151 if (!part) return null;
michael@0 7152 if ((dir > 0) == part.level % 2)
michael@0 7153 target = moveInLine(line, part.to, -1, byUnit);
michael@0 7154 else
michael@0 7155 target = moveInLine(line, part.from, 1, byUnit);
michael@0 7156 }
michael@0 7157 }
michael@0 7158 }
michael@0 7159
michael@0 7160 function moveLogically(line, start, dir, byUnit) {
michael@0 7161 var target = start + dir;
michael@0 7162 if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
michael@0 7163 return target < 0 || target > line.text.length ? null : target;
michael@0 7164 }
michael@0 7165
michael@0 7166 // Bidirectional ordering algorithm
michael@0 7167 // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
michael@0 7168 // that this (partially) implements.
michael@0 7169
michael@0 7170 // One-char codes used for character types:
michael@0 7171 // L (L): Left-to-Right
michael@0 7172 // R (R): Right-to-Left
michael@0 7173 // r (AL): Right-to-Left Arabic
michael@0 7174 // 1 (EN): European Number
michael@0 7175 // + (ES): European Number Separator
michael@0 7176 // % (ET): European Number Terminator
michael@0 7177 // n (AN): Arabic Number
michael@0 7178 // , (CS): Common Number Separator
michael@0 7179 // m (NSM): Non-Spacing Mark
michael@0 7180 // b (BN): Boundary Neutral
michael@0 7181 // s (B): Paragraph Separator
michael@0 7182 // t (S): Segment Separator
michael@0 7183 // w (WS): Whitespace
michael@0 7184 // N (ON): Other Neutrals
michael@0 7185
michael@0 7186 // Returns null if characters are ordered as they appear
michael@0 7187 // (left-to-right), or an array of sections ({from, to, level}
michael@0 7188 // objects) in the order in which they occur visually.
michael@0 7189 var bidiOrdering = (function() {
michael@0 7190 // Character types for codepoints 0 to 0xff
michael@0 7191 var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
michael@0 7192 // Character types for codepoints 0x600 to 0x6ff
michael@0 7193 var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
michael@0 7194 function charType(code) {
michael@0 7195 if (code <= 0xf7) return lowTypes.charAt(code);
michael@0 7196 else if (0x590 <= code && code <= 0x5f4) return "R";
michael@0 7197 else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
michael@0 7198 else if (0x6ee <= code && code <= 0x8ac) return "r";
michael@0 7199 else if (0x2000 <= code && code <= 0x200b) return "w";
michael@0 7200 else if (code == 0x200c) return "b";
michael@0 7201 else return "L";
michael@0 7202 }
michael@0 7203
michael@0 7204 var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
michael@0 7205 var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
michael@0 7206 // Browsers seem to always treat the boundaries of block elements as being L.
michael@0 7207 var outerType = "L";
michael@0 7208
michael@0 7209 function BidiSpan(level, from, to) {
michael@0 7210 this.level = level;
michael@0 7211 this.from = from; this.to = to;
michael@0 7212 }
michael@0 7213
michael@0 7214 return function(str) {
michael@0 7215 if (!bidiRE.test(str)) return false;
michael@0 7216 var len = str.length, types = [];
michael@0 7217 for (var i = 0, type; i < len; ++i)
michael@0 7218 types.push(type = charType(str.charCodeAt(i)));
michael@0 7219
michael@0 7220 // W1. Examine each non-spacing mark (NSM) in the level run, and
michael@0 7221 // change the type of the NSM to the type of the previous
michael@0 7222 // character. If the NSM is at the start of the level run, it will
michael@0 7223 // get the type of sor.
michael@0 7224 for (var i = 0, prev = outerType; i < len; ++i) {
michael@0 7225 var type = types[i];
michael@0 7226 if (type == "m") types[i] = prev;
michael@0 7227 else prev = type;
michael@0 7228 }
michael@0 7229
michael@0 7230 // W2. Search backwards from each instance of a European number
michael@0 7231 // until the first strong type (R, L, AL, or sor) is found. If an
michael@0 7232 // AL is found, change the type of the European number to Arabic
michael@0 7233 // number.
michael@0 7234 // W3. Change all ALs to R.
michael@0 7235 for (var i = 0, cur = outerType; i < len; ++i) {
michael@0 7236 var type = types[i];
michael@0 7237 if (type == "1" && cur == "r") types[i] = "n";
michael@0 7238 else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
michael@0 7239 }
michael@0 7240
michael@0 7241 // W4. A single European separator between two European numbers
michael@0 7242 // changes to a European number. A single common separator between
michael@0 7243 // two numbers of the same type changes to that type.
michael@0 7244 for (var i = 1, prev = types[0]; i < len - 1; ++i) {
michael@0 7245 var type = types[i];
michael@0 7246 if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
michael@0 7247 else if (type == "," && prev == types[i+1] &&
michael@0 7248 (prev == "1" || prev == "n")) types[i] = prev;
michael@0 7249 prev = type;
michael@0 7250 }
michael@0 7251
michael@0 7252 // W5. A sequence of European terminators adjacent to European
michael@0 7253 // numbers changes to all European numbers.
michael@0 7254 // W6. Otherwise, separators and terminators change to Other
michael@0 7255 // Neutral.
michael@0 7256 for (var i = 0; i < len; ++i) {
michael@0 7257 var type = types[i];
michael@0 7258 if (type == ",") types[i] = "N";
michael@0 7259 else if (type == "%") {
michael@0 7260 for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
michael@0 7261 var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
michael@0 7262 for (var j = i; j < end; ++j) types[j] = replace;
michael@0 7263 i = end - 1;
michael@0 7264 }
michael@0 7265 }
michael@0 7266
michael@0 7267 // W7. Search backwards from each instance of a European number
michael@0 7268 // until the first strong type (R, L, or sor) is found. If an L is
michael@0 7269 // found, then change the type of the European number to L.
michael@0 7270 for (var i = 0, cur = outerType; i < len; ++i) {
michael@0 7271 var type = types[i];
michael@0 7272 if (cur == "L" && type == "1") types[i] = "L";
michael@0 7273 else if (isStrong.test(type)) cur = type;
michael@0 7274 }
michael@0 7275
michael@0 7276 // N1. A sequence of neutrals takes the direction of the
michael@0 7277 // surrounding strong text if the text on both sides has the same
michael@0 7278 // direction. European and Arabic numbers act as if they were R in
michael@0 7279 // terms of their influence on neutrals. Start-of-level-run (sor)
michael@0 7280 // and end-of-level-run (eor) are used at level run boundaries.
michael@0 7281 // N2. Any remaining neutrals take the embedding direction.
michael@0 7282 for (var i = 0; i < len; ++i) {
michael@0 7283 if (isNeutral.test(types[i])) {
michael@0 7284 for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
michael@0 7285 var before = (i ? types[i-1] : outerType) == "L";
michael@0 7286 var after = (end < len ? types[end] : outerType) == "L";
michael@0 7287 var replace = before || after ? "L" : "R";
michael@0 7288 for (var j = i; j < end; ++j) types[j] = replace;
michael@0 7289 i = end - 1;
michael@0 7290 }
michael@0 7291 }
michael@0 7292
michael@0 7293 // Here we depart from the documented algorithm, in order to avoid
michael@0 7294 // building up an actual levels array. Since there are only three
michael@0 7295 // levels (0, 1, 2) in an implementation that doesn't take
michael@0 7296 // explicit embedding into account, we can build up the order on
michael@0 7297 // the fly, without following the level-based algorithm.
michael@0 7298 var order = [], m;
michael@0 7299 for (var i = 0; i < len;) {
michael@0 7300 if (countsAsLeft.test(types[i])) {
michael@0 7301 var start = i;
michael@0 7302 for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
michael@0 7303 order.push(new BidiSpan(0, start, i));
michael@0 7304 } else {
michael@0 7305 var pos = i, at = order.length;
michael@0 7306 for (++i; i < len && types[i] != "L"; ++i) {}
michael@0 7307 for (var j = pos; j < i;) {
michael@0 7308 if (countsAsNum.test(types[j])) {
michael@0 7309 if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
michael@0 7310 var nstart = j;
michael@0 7311 for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
michael@0 7312 order.splice(at, 0, new BidiSpan(2, nstart, j));
michael@0 7313 pos = j;
michael@0 7314 } else ++j;
michael@0 7315 }
michael@0 7316 if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
michael@0 7317 }
michael@0 7318 }
michael@0 7319 if (order[0].level == 1 && (m = str.match(/^\s+/))) {
michael@0 7320 order[0].from = m[0].length;
michael@0 7321 order.unshift(new BidiSpan(0, 0, m[0].length));
michael@0 7322 }
michael@0 7323 if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
michael@0 7324 lst(order).to -= m[0].length;
michael@0 7325 order.push(new BidiSpan(0, len - m[0].length, len));
michael@0 7326 }
michael@0 7327 if (order[0].level != lst(order).level)
michael@0 7328 order.push(new BidiSpan(order[0].level, len, len));
michael@0 7329
michael@0 7330 return order;
michael@0 7331 };
michael@0 7332 })();
michael@0 7333
michael@0 7334 // THE END
michael@0 7335
michael@0 7336 CodeMirror.version = "4.0.3";
michael@0 7337
michael@0 7338 return CodeMirror;
michael@0 7339 });

mercurial