| OLD | NEW |
| 1 // CodeMirror is the only global var we claim | 1 // This is CodeMirror (http://codemirror.net), a code editor |
| 2 window.CodeMirror = (function() { | 2 // implemented in JavaScript on top of the browser's DOM. |
| 3 // |
| 4 // You can find some technical background for some of the code below |
| 5 // at http://marijnhaverbeke.nl/blog/#cm-internals . |
| 6 |
| 7 (function(mod) { |
| 8 if (typeof exports == "object" && typeof module == "object") // CommonJS |
| 9 module.exports = mod(); |
| 10 else if (typeof define == "function" && define.amd) // AMD |
| 11 return define([], mod); |
| 12 else // Plain browser env |
| 13 this.CodeMirror = mod(); |
| 14 })(function() { |
| 3 "use strict"; | 15 "use strict"; |
| 4 | 16 |
| 5 // BROWSER SNIFFING | 17 // BROWSER SNIFFING |
| 6 | 18 |
| 7 // Crude, but necessary to handle a number of hard-to-feature-detect | 19 // Kludges for bugs and behavior differences that can't be feature |
| 8 // bugs and behavior differences. | 20 // detected are enabled based on userAgent etc sniffing. |
| 21 |
| 9 var gecko = /gecko\/\d/i.test(navigator.userAgent); | 22 var gecko = /gecko\/\d/i.test(navigator.userAgent); |
| 10 // IE11 currently doesn't count as 'ie', since it has almost none of | 23 // ie_uptoN means Internet Explorer version N or lower |
| 11 // the same bugs as earlier versions. Use ie_gt10 to handle | 24 var ie_upto10 = /MSIE \d/.test(navigator.userAgent); |
| 12 // incompatibilities in that version. | 25 var ie_upto7 = ie_upto10 && (document.documentMode == null || document.documen
tMode < 8); |
| 13 var old_ie = /MSIE \d/.test(navigator.userAgent); | 26 var ie_upto8 = ie_upto10 && (document.documentMode == null || document.documen
tMode < 9); |
| 14 var ie_lt8 = old_ie && (document.documentMode == null || document.documentMode
< 8); | 27 var ie_upto9 = ie_upto10 && (document.documentMode == null || document.documen
tMode < 10); |
| 15 var ie_lt9 = old_ie && (document.documentMode == null || document.documentMode
< 9); | 28 var ie_11up = /Trident\/([7-9]|\d{2,})\./.test(navigator.userAgent); |
| 16 var ie_gt10 = /Trident\/([7-9]|\d{2,})\./.test(navigator.userAgent); | 29 var ie = ie_upto10 || ie_11up; |
| 17 var ie = old_ie || ie_gt10; | |
| 18 var webkit = /WebKit\//.test(navigator.userAgent); | 30 var webkit = /WebKit\//.test(navigator.userAgent); |
| 19 var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent); | 31 var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent); |
| 20 var chrome = /Chrome\//.test(navigator.userAgent); | 32 var chrome = /Chrome\//.test(navigator.userAgent); |
| 21 var opera = /Opera\//.test(navigator.userAgent); | 33 var presto = /Opera\//.test(navigator.userAgent); |
| 22 var safari = /Apple Computer/.test(navigator.vendor); | 34 var safari = /Apple Computer/.test(navigator.vendor); |
| 23 var khtml = /KHTML\//.test(navigator.userAgent); | 35 var khtml = /KHTML\//.test(navigator.userAgent); |
| 24 var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent); | 36 var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent); |
| 25 var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAge
nt); | 37 var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAge
nt); |
| 26 var phantom = /PhantomJS/.test(navigator.userAgent); | 38 var phantom = /PhantomJS/.test(navigator.userAgent); |
| 27 | 39 |
| 28 var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(naviga
tor.userAgent); | 40 var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(naviga
tor.userAgent); |
| 29 // This is woefully incomplete. Suggestions for alternative methods welcome. | 41 // This is woefully incomplete. Suggestions for alternative methods welcome. |
| 30 var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i
.test(navigator.userAgent); | 42 var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i
.test(navigator.userAgent); |
| 31 var mac = ios || /Mac/.test(navigator.platform); | 43 var mac = ios || /Mac/.test(navigator.platform); |
| 32 var windows = /win/i.test(navigator.platform); | 44 var windows = /win/i.test(navigator.platform); |
| 33 | 45 |
| 34 var opera_version = opera && navigator.userAgent.match(/Version\/(\d*\.\d*)/); | 46 var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/
); |
| 35 if (opera_version) opera_version = Number(opera_version[1]); | 47 if (presto_version) presto_version = Number(presto_version[1]); |
| 36 if (opera_version && opera_version >= 15) { opera = false; webkit = true; } | 48 if (presto_version && presto_version >= 15) { presto = false; webkit = true; } |
| 37 // Some browsers use the wrong event properties to signal cmd/ctrl on OS X | 49 // Some browsers use the wrong event properties to signal cmd/ctrl on OS X |
| 38 var flipCtrlCmd = mac && (qtwebkit || opera && (opera_version == null || opera
_version < 12.11)); | 50 var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || pre
sto_version < 12.11)); |
| 39 var captureMiddleClick = gecko || (old_ie && !ie_lt9); | 51 var captureRightClick = gecko || (ie && !ie_upto8); |
| 40 | 52 |
| 41 // Optimize some code when these features are not used | 53 // Optimize some code when these features are not used. |
| 42 var sawReadOnlySpans = false, sawCollapsedSpans = false; | 54 var sawReadOnlySpans = false, sawCollapsedSpans = false; |
| 43 | 55 |
| 44 // CONSTRUCTOR | 56 // EDITOR CONSTRUCTOR |
| 57 |
| 58 // A CodeMirror instance represents an editor. This is the object |
| 59 // that user code is usually dealing with. |
| 45 | 60 |
| 46 function CodeMirror(place, options) { | 61 function CodeMirror(place, options) { |
| 47 if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); | 62 if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); |
| 48 | 63 |
| 49 this.options = options = options || {}; | 64 this.options = options = options || {}; |
| 50 // Determine effective options based on given values and defaults. | 65 // Determine effective options based on given values and defaults. |
| 51 for (var opt in defaults) if (!options.hasOwnProperty(opt) && defaults.hasOw
nProperty(opt)) | 66 for (var opt in defaults) if (!options.hasOwnProperty(opt)) |
| 52 options[opt] = defaults[opt]; | 67 options[opt] = defaults[opt]; |
| 53 setGuttersForLineNumbers(options); | 68 setGuttersForLineNumbers(options); |
| 54 | 69 |
| 55 var docStart = typeof options.value == "string" ? 0 : options.value.first; | 70 var doc = options.value; |
| 56 var display = this.display = makeDisplay(place, docStart); | 71 if (typeof doc == "string") doc = new Doc(doc, options.mode); |
| 72 this.doc = doc; |
| 73 |
| 74 var display = this.display = new Display(place, doc); |
| 57 display.wrapper.CodeMirror = this; | 75 display.wrapper.CodeMirror = this; |
| 58 updateGutters(this); | 76 updateGutters(this); |
| 59 if (options.autofocus && !mobile) focusInput(this); | |
| 60 | |
| 61 this.state = {keyMaps: [], | |
| 62 overlays: [], | |
| 63 modeGen: 0, | |
| 64 overwrite: false, focused: false, | |
| 65 suppressEdits: false, | |
| 66 pasteIncoming: false, cutIncoming: false, | |
| 67 draggingText: false, | |
| 68 highlight: new Delayed()}; | |
| 69 | |
| 70 themeChanged(this); | 77 themeChanged(this); |
| 71 if (options.lineWrapping) | 78 if (options.lineWrapping) |
| 72 this.display.wrapper.className += " CodeMirror-wrap"; | 79 this.display.wrapper.className += " CodeMirror-wrap"; |
| 80 if (options.autofocus && !mobile) focusInput(this); |
| 73 | 81 |
| 74 var doc = options.value; | 82 this.state = { |
| 75 if (typeof doc == "string") doc = new Doc(options.value, options.mode); | 83 keyMaps: [], // stores maps added by addKeyMap |
| 76 operation(this, attachDoc)(this, doc); | 84 overlays: [], // highlighting overlays, as added by addOverlay |
| 85 modeGen: 0, // bumped when mode/overlay changes, used to invalidate high
lighting info |
| 86 overwrite: false, focused: false, |
| 87 suppressEdits: false, // used to disable editing during key handlers when
in readOnly mode |
| 88 pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edit
s in readInput |
| 89 draggingText: false, |
| 90 highlight: new Delayed() // stores highlight worker timeout |
| 91 }; |
| 77 | 92 |
| 78 // Override magic textarea content restore that IE sometimes does | 93 // Override magic textarea content restore that IE sometimes does |
| 79 // on our hidden textarea on reload | 94 // on our hidden textarea on reload |
| 80 if (old_ie) setTimeout(bind(resetInput, this, true), 20); | 95 if (ie_upto10) setTimeout(bind(resetInput, this, true), 20); |
| 81 | 96 |
| 82 registerEventHandlers(this); | 97 registerEventHandlers(this); |
| 83 // IE throws unspecified error in certain cases, when | |
| 84 // trying to access activeElement before onload | |
| 85 var hasFocus; try { hasFocus = (document.activeElement == display.input); }
catch(e) { } | |
| 86 if (hasFocus || (options.autofocus && !mobile)) setTimeout(bind(onFocus, thi
s), 20); | |
| 87 else onBlur(this); | |
| 88 | 98 |
| 89 operation(this, function() { | 99 var cm = this; |
| 90 for (var opt in optionHandlers) | 100 runInOp(this, function() { |
| 91 if (optionHandlers.propertyIsEnumerable(opt)) | 101 cm.curOp.forceUpdate = true; |
| 92 optionHandlers[opt](this, options[opt], Init); | 102 attachDoc(cm, doc); |
| 93 for (var i = 0; i < initHooks.length; ++i) initHooks[i](this); | 103 |
| 94 })(); | 104 if ((options.autofocus && !mobile) || activeElt() == display.input) |
| 105 setTimeout(bind(onFocus, cm), 20); |
| 106 else |
| 107 onBlur(cm); |
| 108 |
| 109 for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt)) |
| 110 optionHandlers[opt](cm, options[opt], Init); |
| 111 for (var i = 0; i < initHooks.length; ++i) initHooks[i](cm); |
| 112 }); |
| 95 } | 113 } |
| 96 | 114 |
| 97 // DISPLAY CONSTRUCTOR | 115 // DISPLAY CONSTRUCTOR |
| 98 | 116 |
| 99 function makeDisplay(place, docStart) { | 117 // The display handles the DOM integration, both for input reading |
| 100 var d = {}; | 118 // and content drawing. It holds references to DOM nodes and |
| 119 // display-related state. |
| 101 | 120 |
| 102 var input = d.input = elt("textarea", null, null, "position: absolute; paddi
ng: 0; width: 1px; height: 1em; outline: none; font-size: 4px;"); | 121 function Display(place, doc) { |
| 122 var d = this; |
| 123 |
| 124 // The semihidden textarea that is focused when the editor is |
| 125 // focused, and receives input. |
| 126 var input = d.input = elt("textarea", null, null, "position: absolute; paddi
ng: 0; width: 1px; height: 1em; outline: none"); |
| 127 // The textarea is kept positioned near the cursor to prevent the |
| 128 // fact that it'll be scrolled into view on input from scrolling |
| 129 // our fake cursor out of view. On webkit, when wrap=off, paste is |
| 130 // very slow. So make the area wide instead. |
| 103 if (webkit) input.style.width = "1000px"; | 131 if (webkit) input.style.width = "1000px"; |
| 104 else input.setAttribute("wrap", "off"); | 132 else input.setAttribute("wrap", "off"); |
| 105 // if border: 0; -- iOS fails to open keyboard (issue #1287) | 133 // If border: 0; -- iOS fails to open keyboard (issue #1287) |
| 106 if (ios) input.style.border = "1px solid black"; | 134 if (ios) input.style.border = "1px solid black"; |
| 107 input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize
", "off"); input.setAttribute("spellcheck", "false"); | 135 input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize
", "off"); input.setAttribute("spellcheck", "false"); |
| 108 | 136 |
| 109 // Wraps and hides input textarea | 137 // Wraps and hides input textarea |
| 110 d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative
; width: 3px; height: 0px;"); | 138 d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative
; width: 3px; height: 0px;"); |
| 111 // The actual fake scrollbars. | 139 // The fake scrollbar elements. |
| 112 d.scrollbarH = elt("div", [elt("div", null, null, "height: 1px")], "CodeMirr
or-hscrollbar"); | 140 d.scrollbarH = elt("div", [elt("div", null, null, "height: 100%; min-height:
1px")], "CodeMirror-hscrollbar"); |
| 113 d.scrollbarV = elt("div", [elt("div", null, null, "width: 1px")], "CodeMirro
r-vscrollbar"); | 141 d.scrollbarV = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeM
irror-vscrollbar"); |
| 142 // Covers bottom-right square when both scrollbars are present. |
| 114 d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); | 143 d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); |
| 144 // Covers bottom of gutter when coverGutterNextToScrollbar is on |
| 145 // and h scrollbar is present. |
| 115 d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); | 146 d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); |
| 116 // DIVs containing the selection and the actual code | 147 // Will contain the actual code, positioned to cover the viewport. |
| 117 d.lineDiv = elt("div", null, "CodeMirror-code"); | 148 d.lineDiv = elt("div", null, "CodeMirror-code"); |
| 149 // Elements are added to these to represent selection and cursors. |
| 118 d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); | 150 d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); |
| 119 // Blinky cursor, and element used to ensure cursor fits at the end of a lin
e | 151 d.cursorDiv = elt("div", null, "CodeMirror-cursors"); |
| 120 d.cursor = elt("div", "\u00a0", "CodeMirror-cursor"); | 152 // A visibility: hidden element used to find the size of things. |
| 121 // Secondary cursor, shown when on a 'jump' in bi-directional text | |
| 122 d.otherCursor = elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondary
cursor"); | |
| 123 // Used to measure text size | |
| 124 d.measure = elt("div", null, "CodeMirror-measure"); | 153 d.measure = elt("div", null, "CodeMirror-measure"); |
| 154 // When lines outside of the viewport are measured, they are drawn in this. |
| 155 d.lineMeasure = elt("div", null, "CodeMirror-measure"); |
| 125 // Wraps everything that needs to exist inside the vertically-padded coordin
ate system | 156 // Wraps everything that needs to exist inside the vertically-padded coordin
ate system |
| 126 d.lineSpace = elt("div", [d.measure, d.selectionDiv, d.lineDiv, d.cursor, d.
otherCursor], | 157 d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursor
Div, d.lineDiv], |
| 127 null, "position: relative; outline: none"); | 158 null, "position: relative; outline: none"); |
| 128 // Moved around its parent to cover visible view | 159 // Moved around its parent to cover visible view. |
| 129 d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null,
"position: relative"); | 160 d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null,
"position: relative"); |
| 130 // Set to the height of the text, causes scrolling | 161 // Set to the height of the document, allowing scrolling. |
| 131 d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); | 162 d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); |
| 132 // D is needed because behavior of elts with overflow: auto and padding is i
nconsistent across browsers | 163 // Behavior of elts with overflow: auto and padding is |
| 164 // inconsistent across browsers. This is used to ensure the |
| 165 // scrollable area is big enough. |
| 133 d.heightForcer = elt("div", null, null, "position: absolute; height: " + scr
ollerCutOff + "px; width: 1px;"); | 166 d.heightForcer = elt("div", null, null, "position: absolute; height: " + scr
ollerCutOff + "px; width: 1px;"); |
| 134 // Will contain the gutters, if any | 167 // Will contain the gutters, if any. |
| 135 d.gutters = elt("div", null, "CodeMirror-gutters"); | 168 d.gutters = elt("div", null, "CodeMirror-gutters"); |
| 136 d.lineGutter = null; | 169 d.lineGutter = null; |
| 137 // Provides scrolling | 170 // Actual scrollable element. |
| 138 d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-sc
roll"); | 171 d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-sc
roll"); |
| 139 d.scroller.setAttribute("tabIndex", "-1"); | 172 d.scroller.setAttribute("tabIndex", "-1"); |
| 140 // The element in which the editor lives. | 173 // The element in which the editor lives. |
| 141 d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV, | 174 d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV, |
| 142 d.scrollbarFiller, d.gutterFiller, d.scroller], "Cod
eMirror"); | 175 d.scrollbarFiller, d.gutterFiller, d.scroller], "Cod
eMirror"); |
| 143 // Work around IE7 z-index bug | |
| 144 if (ie_lt8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0
; } | |
| 145 if (place.appendChild) place.appendChild(d.wrapper); else place(d.wrapper); | |
| 146 | 176 |
| 177 // Work around IE7 z-index bug (not perfect, hence IE7 not really being supp
orted) |
| 178 if (ie_upto7) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight =
0; } |
| 147 // Needed to hide big blue blinking cursor on Mobile Safari | 179 // Needed to hide big blue blinking cursor on Mobile Safari |
| 148 if (ios) input.style.width = "0px"; | 180 if (ios) input.style.width = "0px"; |
| 149 if (!webkit) d.scroller.draggable = true; | 181 if (!webkit) d.scroller.draggable = true; |
| 150 // Needed to handle Tab key in KHTML | 182 // Needed to handle Tab key in KHTML |
| 151 if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "a
bsolute"; } | 183 if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "a
bsolute"; } |
| 152 // Need to set a minimum width to see the scrollbar on IE7 (but must not set
it on IE8). | 184 // Need to set a minimum width to see the scrollbar on IE7 (but must not set
it on IE8). |
| 153 else if (ie_lt8) d.scrollbarH.style.minWidth = d.scrollbarV.style.minWidth =
"18px"; | 185 if (ie_upto7) d.scrollbarH.style.minHeight = d.scrollbarV.style.minWidth = "
18px"; |
| 154 | 186 |
| 155 // Current visible range (may be bigger than the view window). | 187 if (place.appendChild) place.appendChild(d.wrapper); |
| 156 d.viewOffset = d.lastSizeC = 0; | 188 else place(d.wrapper); |
| 157 d.showingFrom = d.showingTo = docStart; | 189 |
| 190 // Current rendered range (may be bigger than the view window). |
| 191 d.viewFrom = d.viewTo = doc.first; |
| 192 // Information about the rendered lines. |
| 193 d.view = []; |
| 194 // Holds info about a single rendered line when it was rendered |
| 195 // for measurement, while not in view. |
| 196 d.externalMeasured = null; |
| 197 // Empty space (in pixels) above the view |
| 198 d.viewOffset = 0; |
| 199 d.lastSizeC = 0; |
| 200 d.updateLineNumbers = null; |
| 158 | 201 |
| 159 // Used to only resize the line number gutter when necessary (when | 202 // Used to only resize the line number gutter when necessary (when |
| 160 // the amount of lines crosses a boundary that makes its width change) | 203 // the amount of lines crosses a boundary that makes its width change) |
| 161 d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; | 204 d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; |
| 162 // See readInput and resetInput | 205 // See readInput and resetInput |
| 163 d.prevInput = ""; | 206 d.prevInput = ""; |
| 164 // Set to true when a non-horizontal-scrolling widget is added. As | 207 // Set to true when a non-horizontal-scrolling line widget is |
| 165 // an optimization, widget aligning is skipped when d is false. | 208 // added. As an optimization, line widget aligning is skipped when |
| 209 // this is false. |
| 166 d.alignWidgets = false; | 210 d.alignWidgets = false; |
| 167 // Flag that indicates whether we currently expect input to appear | 211 // Flag that indicates whether we expect input to appear real soon |
| 168 // (after some event like 'keypress' or 'input') and are polling | 212 // now (after some event like 'keypress' or 'input') and are |
| 169 // intensively. | 213 // polling intensively. |
| 170 d.pollingFast = false; | 214 d.pollingFast = false; |
| 171 // Self-resetting timeout for the poller | 215 // Self-resetting timeout for the poller |
| 172 d.poll = new Delayed(); | 216 d.poll = new Delayed(); |
| 173 | 217 |
| 174 d.cachedCharWidth = d.cachedTextHeight = null; | 218 d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; |
| 175 d.measureLineCache = []; | |
| 176 d.measureLineCachePos = 0; | |
| 177 | 219 |
| 178 // Tracks when resetInput has punted to just putting a short | 220 // Tracks when resetInput has punted to just putting a short |
| 179 // string instead of the (large) selection. | 221 // string into the textarea instead of the full selection. |
| 180 d.inaccurateSelection = false; | 222 d.inaccurateSelection = false; |
| 181 | 223 |
| 182 // Tracks the maximum line length so that the horizontal scrollbar | 224 // Tracks the maximum line length so that the horizontal scrollbar |
| 183 // can be kept static when scrolling. | 225 // can be kept static when scrolling. |
| 184 d.maxLine = null; | 226 d.maxLine = null; |
| 185 d.maxLineLength = 0; | 227 d.maxLineLength = 0; |
| 186 d.maxLineChanged = false; | 228 d.maxLineChanged = false; |
| 187 | 229 |
| 188 // Used for measuring wheel scrolling granularity | 230 // Used for measuring wheel scrolling granularity |
| 189 d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; | 231 d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; |
| 190 | 232 |
| 191 return d; | 233 // True when shift is held down. |
| 234 d.shift = false; |
| 192 } | 235 } |
| 193 | 236 |
| 194 // STATE UPDATES | 237 // STATE UPDATES |
| 195 | 238 |
| 196 // Used to get the editor into a consistent state again when options change. | 239 // Used to get the editor into a consistent state again when options change. |
| 197 | 240 |
| 198 function loadMode(cm) { | 241 function loadMode(cm) { |
| 199 cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); | 242 cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); |
| 200 resetModeState(cm); | 243 resetModeState(cm); |
| 201 } | 244 } |
| 202 | 245 |
| 203 function resetModeState(cm) { | 246 function resetModeState(cm) { |
| 204 cm.doc.iter(function(line) { | 247 cm.doc.iter(function(line) { |
| 205 if (line.stateAfter) line.stateAfter = null; | 248 if (line.stateAfter) line.stateAfter = null; |
| 206 if (line.styles) line.styles = null; | 249 if (line.styles) line.styles = null; |
| 207 }); | 250 }); |
| 208 cm.doc.frontier = cm.doc.first; | 251 cm.doc.frontier = cm.doc.first; |
| 209 startWorker(cm, 100); | 252 startWorker(cm, 100); |
| 210 cm.state.modeGen++; | 253 cm.state.modeGen++; |
| 211 if (cm.curOp) regChange(cm); | 254 if (cm.curOp) regChange(cm); |
| 212 } | 255 } |
| 213 | 256 |
| 214 function wrappingChanged(cm) { | 257 function wrappingChanged(cm) { |
| 215 if (cm.options.lineWrapping) { | 258 if (cm.options.lineWrapping) { |
| 216 cm.display.wrapper.className += " CodeMirror-wrap"; | 259 cm.display.wrapper.className += " CodeMirror-wrap"; |
| 217 cm.display.sizer.style.minWidth = ""; | 260 cm.display.sizer.style.minWidth = ""; |
| 218 } else { | 261 } else { |
| 219 cm.display.wrapper.className = cm.display.wrapper.className.replace(" Code
Mirror-wrap", ""); | 262 cm.display.wrapper.className = cm.display.wrapper.className.replace(" Code
Mirror-wrap", ""); |
| 220 computeMaxLength(cm); | 263 findMaxLine(cm); |
| 221 } | 264 } |
| 222 estimateLineHeights(cm); | 265 estimateLineHeights(cm); |
| 223 regChange(cm); | 266 regChange(cm); |
| 224 clearCaches(cm); | 267 clearCaches(cm); |
| 225 setTimeout(function(){updateScrollbars(cm);}, 100); | 268 setTimeout(function(){updateScrollbars(cm);}, 100); |
| 226 } | 269 } |
| 227 | 270 |
| 271 // Returns a function that estimates the height of a line, to use as |
| 272 // first approximation until the line becomes visible (and is thus |
| 273 // properly measurable). |
| 228 function estimateHeight(cm) { | 274 function estimateHeight(cm) { |
| 229 var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; | 275 var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; |
| 230 var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / char
Width(cm.display) - 3); | 276 var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / char
Width(cm.display) - 3); |
| 231 return function(line) { | 277 return function(line) { |
| 232 if (lineIsHidden(cm.doc, line)) | 278 if (lineIsHidden(cm.doc, line)) return 0; |
| 233 return 0; | 279 |
| 234 else if (wrapping) | 280 var widgetsHeight = 0; |
| 235 return (Math.ceil(line.text.length / perLine) || 1) * th; | 281 if (line.widgets) for (var i = 0; i < line.widgets.length; i++) { |
| 282 if (line.widgets[i].height) widgetsHeight += line.widgets[i].height; |
| 283 } |
| 284 |
| 285 if (wrapping) |
| 286 return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th
; |
| 236 else | 287 else |
| 237 return th; | 288 return widgetsHeight + th; |
| 238 }; | 289 }; |
| 239 } | 290 } |
| 240 | 291 |
| 241 function estimateLineHeights(cm) { | 292 function estimateLineHeights(cm) { |
| 242 var doc = cm.doc, est = estimateHeight(cm); | 293 var doc = cm.doc, est = estimateHeight(cm); |
| 243 doc.iter(function(line) { | 294 doc.iter(function(line) { |
| 244 var estHeight = est(line); | 295 var estHeight = est(line); |
| 245 if (estHeight != line.height) updateLineHeight(line, estHeight); | 296 if (estHeight != line.height) updateLineHeight(line, estHeight); |
| 246 }); | 297 }); |
| 247 } | 298 } |
| 248 | 299 |
| 249 function keyMapChanged(cm) { | 300 function keyMapChanged(cm) { |
| 250 var map = keyMap[cm.options.keyMap], style = map.style; | 301 var map = keyMap[cm.options.keyMap], style = map.style; |
| 251 cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-k
eymap-\S+/g, "") + | 302 cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-k
eymap-\S+/g, "") + |
| 252 (style ? " cm-keymap-" + style : ""); | 303 (style ? " cm-keymap-" + style : ""); |
| 253 } | 304 } |
| 254 | 305 |
| 255 function themeChanged(cm) { | 306 function themeChanged(cm) { |
| 256 cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s
-\S+/g, "") + | 307 cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s
-\S+/g, "") + |
| 257 cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); | 308 cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); |
| 258 clearCaches(cm); | 309 clearCaches(cm); |
| 259 } | 310 } |
| 260 | 311 |
| 261 function guttersChanged(cm) { | 312 function guttersChanged(cm) { |
| 262 updateGutters(cm); | 313 updateGutters(cm); |
| 263 regChange(cm); | 314 regChange(cm); |
| 264 setTimeout(function(){alignHorizontally(cm);}, 20); | 315 setTimeout(function(){alignHorizontally(cm);}, 20); |
| 265 } | 316 } |
| 266 | 317 |
| 318 // Rebuild the gutter elements, ensure the margin to the left of the |
| 319 // code matches their width. |
| 267 function updateGutters(cm) { | 320 function updateGutters(cm) { |
| 268 var gutters = cm.display.gutters, specs = cm.options.gutters; | 321 var gutters = cm.display.gutters, specs = cm.options.gutters; |
| 269 removeChildren(gutters); | 322 removeChildren(gutters); |
| 270 for (var i = 0; i < specs.length; ++i) { | 323 for (var i = 0; i < specs.length; ++i) { |
| 271 var gutterClass = specs[i]; | 324 var gutterClass = specs[i]; |
| 272 var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gut
terClass)); | 325 var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gut
terClass)); |
| 273 if (gutterClass == "CodeMirror-linenumbers") { | 326 if (gutterClass == "CodeMirror-linenumbers") { |
| 274 cm.display.lineGutter = gElt; | 327 cm.display.lineGutter = gElt; |
| 275 gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; | 328 gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; |
| 276 } | 329 } |
| 277 } | 330 } |
| 278 gutters.style.display = i ? "" : "none"; | 331 gutters.style.display = i ? "" : "none"; |
| 332 var width = gutters.offsetWidth; |
| 333 cm.display.sizer.style.marginLeft = width + "px"; |
| 334 if (i) cm.display.scrollbarH.style.left = cm.options.fixedGutter ? width + "
px" : 0; |
| 279 } | 335 } |
| 280 | 336 |
| 281 function lineLength(doc, line) { | 337 // Compute the character length of a line, taking into account |
| 338 // collapsed ranges (see markText) that might hide parts, and join |
| 339 // other lines onto it. |
| 340 function lineLength(line) { |
| 282 if (line.height == 0) return 0; | 341 if (line.height == 0) return 0; |
| 283 var len = line.text.length, merged, cur = line; | 342 var len = line.text.length, merged, cur = line; |
| 284 while (merged = collapsedSpanAtStart(cur)) { | 343 while (merged = collapsedSpanAtStart(cur)) { |
| 285 var found = merged.find(); | 344 var found = merged.find(0, true); |
| 286 cur = getLine(doc, found.from.line); | 345 cur = found.from.line; |
| 287 len += found.from.ch - found.to.ch; | 346 len += found.from.ch - found.to.ch; |
| 288 } | 347 } |
| 289 cur = line; | 348 cur = line; |
| 290 while (merged = collapsedSpanAtEnd(cur)) { | 349 while (merged = collapsedSpanAtEnd(cur)) { |
| 291 var found = merged.find(); | 350 var found = merged.find(0, true); |
| 292 len -= cur.text.length - found.from.ch; | 351 len -= cur.text.length - found.from.ch; |
| 293 cur = getLine(doc, found.to.line); | 352 cur = found.to.line; |
| 294 len += cur.text.length - found.to.ch; | 353 len += cur.text.length - found.to.ch; |
| 295 } | 354 } |
| 296 return len; | 355 return len; |
| 297 } | 356 } |
| 298 | 357 |
| 299 function computeMaxLength(cm) { | 358 // Find the longest line in the document. |
| 359 function findMaxLine(cm) { |
| 300 var d = cm.display, doc = cm.doc; | 360 var d = cm.display, doc = cm.doc; |
| 301 d.maxLine = getLine(doc, doc.first); | 361 d.maxLine = getLine(doc, doc.first); |
| 302 d.maxLineLength = lineLength(doc, d.maxLine); | 362 d.maxLineLength = lineLength(d.maxLine); |
| 303 d.maxLineChanged = true; | 363 d.maxLineChanged = true; |
| 304 doc.iter(function(line) { | 364 doc.iter(function(line) { |
| 305 var len = lineLength(doc, line); | 365 var len = lineLength(line); |
| 306 if (len > d.maxLineLength) { | 366 if (len > d.maxLineLength) { |
| 307 d.maxLineLength = len; | 367 d.maxLineLength = len; |
| 308 d.maxLine = line; | 368 d.maxLine = line; |
| 309 } | 369 } |
| 310 }); | 370 }); |
| 311 } | 371 } |
| 312 | 372 |
| 313 // Make sure the gutters options contains the element | 373 // Make sure the gutters options contains the element |
| 314 // "CodeMirror-linenumbers" when the lineNumbers option is true. | 374 // "CodeMirror-linenumbers" when the lineNumbers option is true. |
| 315 function setGuttersForLineNumbers(options) { | 375 function setGuttersForLineNumbers(options) { |
| 316 var found = indexOf(options.gutters, "CodeMirror-linenumbers"); | 376 var found = indexOf(options.gutters, "CodeMirror-linenumbers"); |
| 317 if (found == -1 && options.lineNumbers) { | 377 if (found == -1 && options.lineNumbers) { |
| 318 options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]); | 378 options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]); |
| 319 } else if (found > -1 && !options.lineNumbers) { | 379 } else if (found > -1 && !options.lineNumbers) { |
| 320 options.gutters = options.gutters.slice(0); | 380 options.gutters = options.gutters.slice(0); |
| 321 options.gutters.splice(found, 1); | 381 options.gutters.splice(found, 1); |
| 322 } | 382 } |
| 323 } | 383 } |
| 324 | 384 |
| 325 // SCROLLBARS | 385 // SCROLLBARS |
| 326 | 386 |
| 387 // Prepare DOM reads needed to update the scrollbars. Done in one |
| 388 // shot to minimize update/measure roundtrips. |
| 389 function measureForScrollbars(cm) { |
| 390 var scroll = cm.display.scroller; |
| 391 return { |
| 392 clientHeight: scroll.clientHeight, |
| 393 barHeight: cm.display.scrollbarV.clientHeight, |
| 394 scrollWidth: scroll.scrollWidth, clientWidth: scroll.clientWidth, |
| 395 barWidth: cm.display.scrollbarH.clientWidth, |
| 396 docHeight: Math.round(cm.doc.height + paddingVert(cm.display)) |
| 397 }; |
| 398 } |
| 399 |
| 327 // Re-synchronize the fake scrollbars with the actual size of the | 400 // Re-synchronize the fake scrollbars with the actual size of the |
| 328 // content. Optionally force a scrollTop. | 401 // content. |
| 329 function updateScrollbars(cm) { | 402 function updateScrollbars(cm, measure) { |
| 330 var d = cm.display, docHeight = cm.doc.height; | 403 if (!measure) measure = measureForScrollbars(cm); |
| 331 var totalHeight = docHeight + paddingVert(d); | 404 var d = cm.display; |
| 332 d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px"; | 405 var scrollHeight = measure.docHeight + scrollerCutOff; |
| 333 d.gutters.style.height = Math.max(totalHeight, d.scroller.clientHeight - scr
ollerCutOff) + "px"; | 406 var needsH = measure.scrollWidth > measure.clientWidth; |
| 334 var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight); | 407 var needsV = scrollHeight > measure.clientHeight; |
| 335 var needsH = d.scroller.scrollWidth > (d.scroller.clientWidth + 1); | |
| 336 var needsV = scrollHeight > (d.scroller.clientHeight + 1); | |
| 337 if (needsV) { | 408 if (needsV) { |
| 338 d.scrollbarV.style.display = "block"; | 409 d.scrollbarV.style.display = "block"; |
| 339 d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0
"; | 410 d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0
"; |
| 340 // A bug in IE8 can cause this value to be negative, so guard it. | 411 // A bug in IE8 can cause this value to be negative, so guard it. |
| 341 d.scrollbarV.firstChild.style.height = | 412 d.scrollbarV.firstChild.style.height = |
| 342 Math.max(0, scrollHeight - d.scroller.clientHeight + d.scrollbarV.client
Height) + "px"; | 413 Math.max(0, scrollHeight - measure.clientHeight + (measure.barHeight ||
d.scrollbarV.clientHeight)) + "px"; |
| 343 } else { | 414 } else { |
| 344 d.scrollbarV.style.display = ""; | 415 d.scrollbarV.style.display = ""; |
| 345 d.scrollbarV.firstChild.style.height = "0"; | 416 d.scrollbarV.firstChild.style.height = "0"; |
| 346 } | 417 } |
| 347 if (needsH) { | 418 if (needsH) { |
| 348 d.scrollbarH.style.display = "block"; | 419 d.scrollbarH.style.display = "block"; |
| 349 d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0"
; | 420 d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0"
; |
| 350 d.scrollbarH.firstChild.style.width = | 421 d.scrollbarH.firstChild.style.width = |
| 351 (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWi
dth) + "px"; | 422 (measure.scrollWidth - measure.clientWidth + (measure.barWidth || d.scro
llbarH.clientWidth)) + "px"; |
| 352 } else { | 423 } else { |
| 353 d.scrollbarH.style.display = ""; | 424 d.scrollbarH.style.display = ""; |
| 354 d.scrollbarH.firstChild.style.width = "0"; | 425 d.scrollbarH.firstChild.style.width = "0"; |
| 355 } | 426 } |
| 356 if (needsH && needsV) { | 427 if (needsH && needsV) { |
| 357 d.scrollbarFiller.style.display = "block"; | 428 d.scrollbarFiller.style.display = "block"; |
| 358 d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbar
Width(d.measure) + "px"; | 429 d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbar
Width(d.measure) + "px"; |
| 359 } else d.scrollbarFiller.style.display = ""; | 430 } else d.scrollbarFiller.style.display = ""; |
| 360 if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutte
r) { | 431 if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutte
r) { |
| 361 d.gutterFiller.style.display = "block"; | 432 d.gutterFiller.style.display = "block"; |
| 362 d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px"; | 433 d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px"; |
| 363 d.gutterFiller.style.width = d.gutters.offsetWidth + "px"; | 434 d.gutterFiller.style.width = d.gutters.offsetWidth + "px"; |
| 364 } else d.gutterFiller.style.display = ""; | 435 } else d.gutterFiller.style.display = ""; |
| 365 | 436 |
| 366 if (mac_geLion && scrollbarWidth(d.measure) === 0) { | 437 if (mac_geLion && scrollbarWidth(d.measure) === 0) { |
| 367 d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountai
nLion ? "18px" : "12px"; | 438 d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountai
nLion ? "18px" : "12px"; |
| 368 d.scrollbarV.style.pointerEvents = d.scrollbarH.style.pointerEvents = "non
e"; | 439 var barMouseDown = function(e) { |
| 440 if (e_target(e) != d.scrollbarV && e_target(e) != d.scrollbarH) |
| 441 operation(cm, onMouseDown)(e); |
| 442 }; |
| 443 on(d.scrollbarV, "mousedown", barMouseDown); |
| 444 on(d.scrollbarH, "mousedown", barMouseDown); |
| 369 } | 445 } |
| 370 } | 446 } |
| 371 | 447 |
| 448 // Compute the lines that are visible in a given viewport (defaults |
| 449 // the the current scroll position). viewPort may contain top, |
| 450 // height, and ensure (see op.scrollToPos) properties. |
| 372 function visibleLines(display, doc, viewPort) { | 451 function visibleLines(display, doc, viewPort) { |
| 373 var top = display.scroller.scrollTop, height = display.wrapper.clientHeight; | 452 var top = viewPort && viewPort.top != null ? viewPort.top : display.scroller
.scrollTop; |
| 374 if (typeof viewPort == "number") top = viewPort; | |
| 375 else if (viewPort) {top = viewPort.top; height = viewPort.bottom - viewPort.
top;} | |
| 376 top = Math.floor(top - paddingTop(display)); | 453 top = Math.floor(top - paddingTop(display)); |
| 377 var bottom = Math.ceil(top + height); | 454 var bottom = viewPort && viewPort.bottom != null ? viewPort.bottom : top + d
isplay.wrapper.clientHeight; |
| 378 return {from: lineAtHeight(doc, top), to: lineAtHeight(doc, bottom)}; | 455 |
| 456 var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); |
| 457 // Ensure is a {from: {line, ch}, to: {line, ch}} object, and |
| 458 // forces those lines into the viewport (if possible). |
| 459 if (viewPort && viewPort.ensure) { |
| 460 var ensureFrom = viewPort.ensure.from.line, ensureTo = viewPort.ensure.to.
line; |
| 461 if (ensureFrom < from) |
| 462 return {from: ensureFrom, |
| 463 to: lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + d
isplay.wrapper.clientHeight)}; |
| 464 if (Math.min(ensureTo, doc.lastLine()) >= to) |
| 465 return {from: lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - d
isplay.wrapper.clientHeight), |
| 466 to: ensureTo}; |
| 467 } |
| 468 return {from: from, to: to}; |
| 379 } | 469 } |
| 380 | 470 |
| 381 // LINE NUMBERS | 471 // LINE NUMBERS |
| 382 | 472 |
| 473 // Re-align line numbers and gutter marks to compensate for |
| 474 // horizontal scrolling. |
| 383 function alignHorizontally(cm) { | 475 function alignHorizontally(cm) { |
| 384 var display = cm.display; | 476 var display = cm.display, view = display.view; |
| 385 if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fix
edGutter)) return; | 477 if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fix
edGutter)) return; |
| 386 var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.
doc.scrollLeft; | 478 var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.
doc.scrollLeft; |
| 387 var gutterW = display.gutters.offsetWidth, l = comp + "px"; | 479 var gutterW = display.gutters.offsetWidth, left = comp + "px"; |
| 388 for (var n = display.lineDiv.firstChild; n; n = n.nextSibling) if (n.alignab
le) { | 480 for (var i = 0; i < view.length; i++) if (!view[i].hidden) { |
| 389 for (var i = 0, a = n.alignable; i < a.length; ++i) a[i].style.left = l; | 481 if (cm.options.fixedGutter && view[i].gutter) |
| 482 view[i].gutter.style.left = left; |
| 483 var align = view[i].alignable; |
| 484 if (align) for (var j = 0; j < align.length; j++) |
| 485 align[j].style.left = left; |
| 390 } | 486 } |
| 391 if (cm.options.fixedGutter) | 487 if (cm.options.fixedGutter) |
| 392 display.gutters.style.left = (comp + gutterW) + "px"; | 488 display.gutters.style.left = (comp + gutterW) + "px"; |
| 393 } | 489 } |
| 394 | 490 |
| 491 // Used to ensure that the line number gutter is still the right |
| 492 // size for the current document size. Returns true when an update |
| 493 // is needed. |
| 395 function maybeUpdateLineNumberWidth(cm) { | 494 function maybeUpdateLineNumberWidth(cm) { |
| 396 if (!cm.options.lineNumbers) return false; | 495 if (!cm.options.lineNumbers) return false; |
| 397 var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1)
, display = cm.display; | 496 var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1)
, display = cm.display; |
| 398 if (last.length != display.lineNumChars) { | 497 if (last.length != display.lineNumChars) { |
| 399 var test = display.measure.appendChild(elt("div", [elt("div", last)], | 498 var test = display.measure.appendChild(elt("div", [elt("div", last)], |
| 400 "CodeMirror-linenumber CodeMirr
or-gutter-elt")); | 499 "CodeMirror-linenumber CodeMirr
or-gutter-elt")); |
| 401 var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - inn
erW; | 500 var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - inn
erW; |
| 402 display.lineGutter.style.width = ""; | 501 display.lineGutter.style.width = ""; |
| 403 display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidt
h - padding); | 502 display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidt
h - padding); |
| 404 display.lineNumWidth = display.lineNumInnerWidth + padding; | 503 display.lineNumWidth = display.lineNumInnerWidth + padding; |
| 405 display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; | 504 display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; |
| 406 display.lineGutter.style.width = display.lineNumWidth + "px"; | 505 display.lineGutter.style.width = display.lineNumWidth + "px"; |
| 506 var width = display.gutters.offsetWidth; |
| 507 display.scrollbarH.style.left = cm.options.fixedGutter ? width + "px" : 0; |
| 508 display.sizer.style.marginLeft = width + "px"; |
| 407 return true; | 509 return true; |
| 408 } | 510 } |
| 409 return false; | 511 return false; |
| 410 } | 512 } |
| 411 | 513 |
| 412 function lineNumberFor(options, i) { | 514 function lineNumberFor(options, i) { |
| 413 return String(options.lineNumberFormatter(i + options.firstLineNumber)); | 515 return String(options.lineNumberFormatter(i + options.firstLineNumber)); |
| 414 } | 516 } |
| 517 |
| 518 // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, |
| 519 // but using getBoundingClientRect to get a sub-pixel-accurate |
| 520 // result. |
| 415 function compensateForHScroll(display) { | 521 function compensateForHScroll(display) { |
| 416 return getRect(display.scroller).left - getRect(display.sizer).left; | 522 return display.scroller.getBoundingClientRect().left - display.sizer.getBoun
dingClientRect().left; |
| 417 } | 523 } |
| 418 | 524 |
| 419 // DISPLAY DRAWING | 525 // DISPLAY DRAWING |
| 420 | 526 |
| 421 function updateDisplay(cm, changes, viewPort, forced) { | 527 // Updates the display, selection, and scrollbars, using the |
| 422 var oldFrom = cm.display.showingFrom, oldTo = cm.display.showingTo, updated; | 528 // information in display.view to find out which nodes are no longer |
| 529 // up-to-date. Tries to bail out early when no changes are needed, |
| 530 // unless forced is true. |
| 531 // Returns true if an actual update happened, false otherwise. |
| 532 function updateDisplay(cm, viewPort, forced) { |
| 533 var oldFrom = cm.display.viewFrom, oldTo = cm.display.viewTo, updated; |
| 423 var visible = visibleLines(cm.display, cm.doc, viewPort); | 534 var visible = visibleLines(cm.display, cm.doc, viewPort); |
| 424 for (var first = true;; first = false) { | 535 for (var first = true;; first = false) { |
| 425 var oldWidth = cm.display.scroller.clientWidth; | 536 var oldWidth = cm.display.scroller.clientWidth; |
| 426 if (!updateDisplayInner(cm, changes, visible, forced)) break; | 537 if (!updateDisplayInner(cm, visible, forced)) break; |
| 427 updated = true; | 538 updated = true; |
| 428 changes = []; | 539 |
| 540 // If the max line changed since it was last measured, measure it, |
| 541 // and ensure the document's width matches it. |
| 542 if (cm.display.maxLineChanged && !cm.options.lineWrapping) |
| 543 adjustContentWidth(cm); |
| 544 |
| 545 var barMeasure = measureForScrollbars(cm); |
| 429 updateSelection(cm); | 546 updateSelection(cm); |
| 430 updateScrollbars(cm); | 547 setDocumentHeight(cm, barMeasure); |
| 548 updateScrollbars(cm, barMeasure); |
| 431 if (first && cm.options.lineWrapping && oldWidth != cm.display.scroller.cl
ientWidth) { | 549 if (first && cm.options.lineWrapping && oldWidth != cm.display.scroller.cl
ientWidth) { |
| 432 forced = true; | 550 forced = true; |
| 433 continue; | 551 continue; |
| 434 } | 552 } |
| 435 forced = false; | 553 forced = false; |
| 436 | 554 |
| 437 // Clip forced viewport to actual scrollable area | 555 // Clip forced viewport to actual scrollable area. |
| 438 if (viewPort) | 556 if (viewPort && viewPort.top != null) |
| 439 viewPort = Math.min(cm.display.scroller.scrollHeight - cm.display.scroll
er.clientHeight, | 557 viewPort = {top: Math.min(barMeasure.docHeight - scrollerCutOff - barMea
sure.clientHeight, viewPort.top)}; |
| 440 typeof viewPort == "number" ? viewPort : viewPort.to
p); | 558 // Updated line heights might result in the drawn area not |
| 559 // actually covering the viewport. Keep looping until it does. |
| 441 visible = visibleLines(cm.display, cm.doc, viewPort); | 560 visible = visibleLines(cm.display, cm.doc, viewPort); |
| 442 if (visible.from >= cm.display.showingFrom && visible.to <= cm.display.sho
wingTo) | 561 if (visible.from >= cm.display.viewFrom && visible.to <= cm.display.viewTo
) |
| 443 break; | 562 break; |
| 444 } | 563 } |
| 445 | 564 |
| 565 cm.display.updateLineNumbers = null; |
| 446 if (updated) { | 566 if (updated) { |
| 447 signalLater(cm, "update", cm); | 567 signalLater(cm, "update", cm); |
| 448 if (cm.display.showingFrom != oldFrom || cm.display.showingTo != oldTo) | 568 if (cm.display.viewFrom != oldFrom || cm.display.viewTo != oldTo) |
| 449 signalLater(cm, "viewportChange", cm, cm.display.showingFrom, cm.display
.showingTo); | 569 signalLater(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.vi
ewTo); |
| 450 } | 570 } |
| 451 return updated; | 571 return updated; |
| 452 } | 572 } |
| 453 | 573 |
| 454 // Uses a set of changes plus the current scroll position to | 574 // Does the actual updating of the line display. Bails out |
| 455 // determine which DOM updates have to be made, and makes the | 575 // (returning false) when there is nothing to be done and forced is |
| 456 // updates. | 576 // false. |
| 457 function updateDisplayInner(cm, changes, visible, forced) { | 577 function updateDisplayInner(cm, visible, forced) { |
| 458 var display = cm.display, doc = cm.doc; | 578 var display = cm.display, doc = cm.doc; |
| 459 if (!display.wrapper.offsetWidth) { | 579 if (!display.wrapper.offsetWidth) { |
| 460 display.showingFrom = display.showingTo = doc.first; | 580 resetView(cm); |
| 461 display.viewOffset = 0; | |
| 462 return; | 581 return; |
| 463 } | 582 } |
| 464 | 583 |
| 465 // Bail out if the visible area is already rendered and nothing changed. | 584 // Bail out if the visible area is already rendered and nothing changed. |
| 466 if (!forced && changes.length == 0 && | 585 if (!forced && visible.from >= display.viewFrom && visible.to <= display.vie
wTo && |
| 467 visible.from > display.showingFrom && visible.to < display.showingTo) | 586 countDirtyView(cm) == 0) |
| 468 return; | 587 return; |
| 469 | 588 |
| 470 if (maybeUpdateLineNumberWidth(cm)) | 589 if (maybeUpdateLineNumberWidth(cm)) |
| 471 changes = [{from: doc.first, to: doc.first + doc.size}]; | 590 resetView(cm); |
| 472 var gutterW = display.sizer.style.marginLeft = display.gutters.offsetWidth +
"px"; | 591 var dims = getDimensions(cm); |
| 473 display.scrollbarH.style.left = cm.options.fixedGutter ? gutterW : "0"; | |
| 474 | 592 |
| 475 // Used to determine which lines need their line numbers updated | 593 // Compute a suitable new viewport (from & to) |
| 476 var positionsChangedFrom = Infinity; | |
| 477 if (cm.options.lineNumbers) | |
| 478 for (var i = 0; i < changes.length; ++i) | |
| 479 if (changes[i].diff && changes[i].from < positionsChangedFrom) { positio
nsChangedFrom = changes[i].from; } | |
| 480 | |
| 481 var end = doc.first + doc.size; | 594 var end = doc.first + doc.size; |
| 482 var from = Math.max(visible.from - cm.options.viewportMargin, doc.first); | 595 var from = Math.max(visible.from - cm.options.viewportMargin, doc.first); |
| 483 var to = Math.min(end, visible.to + cm.options.viewportMargin); | 596 var to = Math.min(end, visible.to + cm.options.viewportMargin); |
| 484 if (display.showingFrom < from && from - display.showingFrom < 20) from = Ma
th.max(doc.first, display.showingFrom); | 597 if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max
(doc.first, display.viewFrom); |
| 485 if (display.showingTo > to && display.showingTo - to < 20) to = Math.min(end
, display.showingTo); | 598 if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, disp
lay.viewTo); |
| 486 if (sawCollapsedSpans) { | 599 if (sawCollapsedSpans) { |
| 487 from = lineNo(visualLine(doc, getLine(doc, from))); | 600 from = visualLineNo(cm.doc, from); |
| 488 while (to < end && lineIsHidden(doc, getLine(doc, to))) ++to; | 601 to = visualLineEndNo(cm.doc, to); |
| 489 } | 602 } |
| 490 | 603 |
| 491 // Create a range of theoretically intact lines, and punch holes | 604 var different = from != display.viewFrom || to != display.viewTo || |
| 492 // in that using the change info. | 605 display.lastSizeC != display.wrapper.clientHeight; |
| 493 var intact = [{from: Math.max(display.showingFrom, doc.first), | 606 adjustView(cm, from, to); |
| 494 to: Math.min(display.showingTo, end)}]; | |
| 495 if (intact[0].from >= intact[0].to) intact = []; | |
| 496 else intact = computeIntact(intact, changes); | |
| 497 // When merged lines are present, we might have to reduce the | |
| 498 // intact ranges because changes in continued fragments of the | |
| 499 // intact lines do require the lines to be redrawn. | |
| 500 if (sawCollapsedSpans) | |
| 501 for (var i = 0; i < intact.length; ++i) { | |
| 502 var range = intact[i], merged; | |
| 503 while (merged = collapsedSpanAtEnd(getLine(doc, range.to - 1))) { | |
| 504 var newTo = merged.find().from.line; | |
| 505 if (newTo > range.from) range.to = newTo; | |
| 506 else { intact.splice(i--, 1); break; } | |
| 507 } | |
| 508 } | |
| 509 | 607 |
| 510 // Clip off the parts that won't be visible | 608 display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); |
| 511 var intactLines = 0; | 609 // Position the mover div to align with the current scroll position |
| 512 for (var i = 0; i < intact.length; ++i) { | 610 cm.display.mover.style.top = display.viewOffset + "px"; |
| 513 var range = intact[i]; | |
| 514 if (range.from < from) range.from = from; | |
| 515 if (range.to > to) range.to = to; | |
| 516 if (range.from >= range.to) intact.splice(i--, 1); | |
| 517 else intactLines += range.to - range.from; | |
| 518 } | |
| 519 if (!forced && intactLines == to - from && from == display.showingFrom && to
== display.showingTo) { | |
| 520 updateViewOffset(cm); | |
| 521 return; | |
| 522 } | |
| 523 intact.sort(function(a, b) {return a.from - b.from;}); | |
| 524 | 611 |
| 525 // Avoid crashing on IE's "unspecified error" when in iframes | 612 var toUpdate = countDirtyView(cm); |
| 526 try { | 613 if (!different && toUpdate == 0 && !forced) return; |
| 527 var focused = document.activeElement; | |
| 528 } catch(e) {} | |
| 529 if (intactLines < (to - from) * .7) display.lineDiv.style.display = "none"; | |
| 530 patchDisplay(cm, from, to, intact, positionsChangedFrom); | |
| 531 display.lineDiv.style.display = ""; | |
| 532 if (focused && document.activeElement != focused && focused.offsetHeight) fo
cused.focus(); | |
| 533 | 614 |
| 534 var different = from != display.showingFrom || to != display.showingTo || | 615 // For big changes, we hide the enclosing element during the |
| 535 display.lastSizeC != display.wrapper.clientHeight; | 616 // update, since that speeds up the operations on most browsers. |
| 536 // This is just a bogus formula that detects when the editor is | 617 var focused = activeElt(); |
| 537 // resized or the font size changes. | 618 if (toUpdate > 4) display.lineDiv.style.display = "none"; |
| 619 patchDisplay(cm, display.updateLineNumbers, dims); |
| 620 if (toUpdate > 4) display.lineDiv.style.display = ""; |
| 621 // There might have been a widget with a focused element that got |
| 622 // hidden or updated, if so re-focus it. |
| 623 if (focused && activeElt() != focused && focused.offsetHeight) focused.focus
(); |
| 624 |
| 625 // Prevent selection and cursors from interfering with the scroll |
| 626 // width. |
| 627 removeChildren(display.cursorDiv); |
| 628 removeChildren(display.selectionDiv); |
| 629 |
| 538 if (different) { | 630 if (different) { |
| 539 display.lastSizeC = display.wrapper.clientHeight; | 631 display.lastSizeC = display.wrapper.clientHeight; |
| 540 startWorker(cm, 400); | 632 startWorker(cm, 400); |
| 541 } | 633 } |
| 542 display.showingFrom = from; display.showingTo = to; | |
| 543 | 634 |
| 544 display.gutters.style.height = ""; | |
| 545 updateHeightsInViewport(cm); | 635 updateHeightsInViewport(cm); |
| 546 updateViewOffset(cm); | |
| 547 | 636 |
| 548 return true; | 637 return true; |
| 549 } | 638 } |
| 550 | 639 |
| 640 function adjustContentWidth(cm) { |
| 641 var display = cm.display; |
| 642 var width = measureChar(cm, display.maxLine, display.maxLine.text.length).le
ft; |
| 643 display.maxLineChanged = false; |
| 644 var minWidth = Math.max(0, width + 3); |
| 645 var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + minWidth + scroll
erCutOff - display.scroller.clientWidth); |
| 646 display.sizer.style.minWidth = minWidth + "px"; |
| 647 if (maxScrollLeft < cm.doc.scrollLeft) |
| 648 setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft), tr
ue); |
| 649 } |
| 650 |
| 651 function setDocumentHeight(cm, measure) { |
| 652 cm.display.sizer.style.minHeight = cm.display.heightForcer.style.top = measu
re.docHeight + "px"; |
| 653 cm.display.gutters.style.height = Math.max(measure.docHeight, measure.client
Height - scrollerCutOff) + "px"; |
| 654 } |
| 655 |
| 656 // Read the actual heights of the rendered lines, and update their |
| 657 // stored heights to match. |
| 551 function updateHeightsInViewport(cm) { | 658 function updateHeightsInViewport(cm) { |
| 552 var display = cm.display; | 659 var display = cm.display; |
| 553 var prevBottom = display.lineDiv.offsetTop; | 660 var prevBottom = display.lineDiv.offsetTop; |
| 554 for (var node = display.lineDiv.firstChild, height; node; node = node.nextSi
bling) if (node.lineObj) { | 661 for (var i = 0; i < display.view.length; i++) { |
| 555 if (ie_lt8) { | 662 var cur = display.view[i], height; |
| 556 var bot = node.offsetTop + node.offsetHeight; | 663 if (cur.hidden) continue; |
| 664 if (ie_upto7) { |
| 665 var bot = cur.node.offsetTop + cur.node.offsetHeight; |
| 557 height = bot - prevBottom; | 666 height = bot - prevBottom; |
| 558 prevBottom = bot; | 667 prevBottom = bot; |
| 559 } else { | 668 } else { |
| 560 var box = getRect(node); | 669 var box = cur.node.getBoundingClientRect(); |
| 561 height = box.bottom - box.top; | 670 height = box.bottom - box.top; |
| 562 } | 671 } |
| 563 var diff = node.lineObj.height - height; | 672 var diff = cur.line.height - height; |
| 564 if (height < 2) height = textHeight(display); | 673 if (height < 2) height = textHeight(display); |
| 565 if (diff > .001 || diff < -.001) { | 674 if (diff > .001 || diff < -.001) { |
| 566 updateLineHeight(node.lineObj, height); | 675 updateLineHeight(cur.line, height); |
| 567 var widgets = node.lineObj.widgets; | 676 updateWidgetHeight(cur.line); |
| 568 if (widgets) for (var i = 0; i < widgets.length; ++i) | 677 if (cur.rest) for (var j = 0; j < cur.rest.length; j++) |
| 569 widgets[i].height = widgets[i].node.offsetHeight; | 678 updateWidgetHeight(cur.rest[j]); |
| 570 } | 679 } |
| 571 } | 680 } |
| 572 } | 681 } |
| 573 | 682 |
| 574 function updateViewOffset(cm) { | 683 // Read and store the height of line widgets associated with the |
| 575 var off = cm.display.viewOffset = heightAtLine(cm, getLine(cm.doc, cm.displa
y.showingFrom)); | 684 // given line. |
| 576 // Position the mover div to align with the current virtual scroll position | 685 function updateWidgetHeight(line) { |
| 577 cm.display.mover.style.top = off + "px"; | 686 if (line.widgets) for (var i = 0; i < line.widgets.length; ++i) |
| 687 line.widgets[i].height = line.widgets[i].node.offsetHeight; |
| 578 } | 688 } |
| 579 | 689 |
| 580 function computeIntact(intact, changes) { | 690 // Do a bulk-read of the DOM positions and sizes needed to draw the |
| 581 for (var i = 0, l = changes.length || 0; i < l; ++i) { | 691 // view, so that we don't interleave reading and writing to the DOM. |
| 582 var change = changes[i], intact2 = [], diff = change.diff || 0; | |
| 583 for (var j = 0, l2 = intact.length; j < l2; ++j) { | |
| 584 var range = intact[j]; | |
| 585 if (change.to <= range.from && change.diff) { | |
| 586 intact2.push({from: range.from + diff, to: range.to + diff}); | |
| 587 } else if (change.to <= range.from || change.from >= range.to) { | |
| 588 intact2.push(range); | |
| 589 } else { | |
| 590 if (change.from > range.from) | |
| 591 intact2.push({from: range.from, to: change.from}); | |
| 592 if (change.to < range.to) | |
| 593 intact2.push({from: change.to + diff, to: range.to + diff}); | |
| 594 } | |
| 595 } | |
| 596 intact = intact2; | |
| 597 } | |
| 598 return intact; | |
| 599 } | |
| 600 | |
| 601 function getDimensions(cm) { | 692 function getDimensions(cm) { |
| 602 var d = cm.display, left = {}, width = {}; | 693 var d = cm.display, left = {}, width = {}; |
| 603 for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { | 694 for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { |
| 604 left[cm.options.gutters[i]] = n.offsetLeft; | 695 left[cm.options.gutters[i]] = n.offsetLeft; |
| 605 width[cm.options.gutters[i]] = n.offsetWidth; | 696 width[cm.options.gutters[i]] = n.offsetWidth; |
| 606 } | 697 } |
| 607 return {fixedPos: compensateForHScroll(d), | 698 return {fixedPos: compensateForHScroll(d), |
| 608 gutterTotalWidth: d.gutters.offsetWidth, | 699 gutterTotalWidth: d.gutters.offsetWidth, |
| 609 gutterLeft: left, | 700 gutterLeft: left, |
| 610 gutterWidth: width, | 701 gutterWidth: width, |
| 611 wrapperWidth: d.wrapper.clientWidth}; | 702 wrapperWidth: d.wrapper.clientWidth}; |
| 612 } | 703 } |
| 613 | 704 |
| 614 function patchDisplay(cm, from, to, intact, updateNumbersFrom) { | 705 // Sync the actual display DOM structure with display.view, removing |
| 615 var dims = getDimensions(cm); | 706 // nodes for lines that are no longer in view, and creating the ones |
| 707 // that are not there yet, and updating the ones that are out of |
| 708 // date. |
| 709 function patchDisplay(cm, updateNumbersFrom, dims) { |
| 616 var display = cm.display, lineNumbers = cm.options.lineNumbers; | 710 var display = cm.display, lineNumbers = cm.options.lineNumbers; |
| 617 if (!intact.length && (!webkit || !cm.display.currentWheelTarget)) | |
| 618 removeChildren(display.lineDiv); | |
| 619 var container = display.lineDiv, cur = container.firstChild; | 711 var container = display.lineDiv, cur = container.firstChild; |
| 620 | 712 |
| 621 function rm(node) { | 713 function rm(node) { |
| 622 var next = node.nextSibling; | 714 var next = node.nextSibling; |
| 623 if (webkit && mac && cm.display.currentWheelTarget == node) { | 715 // Works around a throw-scroll bug in OS X Webkit |
| 716 if (webkit && mac && cm.display.currentWheelTarget == node) |
| 624 node.style.display = "none"; | 717 node.style.display = "none"; |
| 625 node.lineObj = null; | 718 else |
| 626 } else { | |
| 627 node.parentNode.removeChild(node); | 719 node.parentNode.removeChild(node); |
| 720 return next; |
| 721 } |
| 722 |
| 723 var view = display.view, lineN = display.viewFrom; |
| 724 // Loop over the elements in the view, syncing cur (the DOM nodes |
| 725 // in display.lineDiv) with the view as we go. |
| 726 for (var i = 0; i < view.length; i++) { |
| 727 var lineView = view[i]; |
| 728 if (lineView.hidden) { |
| 729 } else if (!lineView.node) { // Not drawn yet |
| 730 var node = buildLineElement(cm, lineView, lineN, dims); |
| 731 container.insertBefore(node, cur); |
| 732 } else { // Already drawn |
| 733 while (cur != lineView.node) cur = rm(cur); |
| 734 var updateNumber = lineNumbers && updateNumbersFrom != null && |
| 735 updateNumbersFrom <= lineN && lineView.lineNumber; |
| 736 if (lineView.changes) { |
| 737 if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false; |
| 738 updateLineForChanges(cm, lineView, lineN, dims); |
| 739 } |
| 740 if (updateNumber) { |
| 741 removeChildren(lineView.lineNumber); |
| 742 lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(
cm.options, lineN))); |
| 743 } |
| 744 cur = lineView.node.nextSibling; |
| 628 } | 745 } |
| 629 return next; | 746 lineN += lineView.size; |
| 630 } | 747 } |
| 631 | |
| 632 var nextIntact = intact.shift(), lineN = from; | |
| 633 cm.doc.iter(from, to, function(line) { | |
| 634 if (nextIntact && nextIntact.to == lineN) nextIntact = intact.shift(); | |
| 635 if (lineIsHidden(cm.doc, line)) { | |
| 636 if (line.height != 0) updateLineHeight(line, 0); | |
| 637 if (line.widgets && cur && cur.previousSibling) for (var i = 0; i < line
.widgets.length; ++i) { | |
| 638 var w = line.widgets[i]; | |
| 639 if (w.showIfHidden) { | |
| 640 var prev = cur.previousSibling; | |
| 641 if (/pre/i.test(prev.nodeName)) { | |
| 642 var wrap = elt("div", null, null, "position: relative"); | |
| 643 prev.parentNode.replaceChild(wrap, prev); | |
| 644 wrap.appendChild(prev); | |
| 645 prev = wrap; | |
| 646 } | |
| 647 var wnode = prev.appendChild(elt("div", [w.node], "CodeMirror-linewi
dget")); | |
| 648 if (!w.handleMouseEvents) wnode.ignoreEvents = true; | |
| 649 positionLineWidget(w, wnode, prev, dims); | |
| 650 } | |
| 651 } | |
| 652 } else if (nextIntact && nextIntact.from <= lineN && nextIntact.to > lineN
) { | |
| 653 // This line is intact. Skip to the actual node. Update its | |
| 654 // line number if needed. | |
| 655 while (cur.lineObj != line) cur = rm(cur); | |
| 656 if (lineNumbers && updateNumbersFrom <= lineN && cur.lineNumber) | |
| 657 setTextContent(cur.lineNumber, lineNumberFor(cm.options, lineN)); | |
| 658 cur = cur.nextSibling; | |
| 659 } else { | |
| 660 // For lines with widgets, make an attempt to find and reuse | |
| 661 // the existing element, so that widgets aren't needlessly | |
| 662 // removed and re-inserted into the dom | |
| 663 if (line.widgets) for (var j = 0, search = cur, reuse; search && j < 20;
++j, search = search.nextSibling) | |
| 664 if (search.lineObj == line && /div/i.test(search.nodeName)) { reuse =
search; break; } | |
| 665 // This line needs to be generated. | |
| 666 var lineNode = buildLineElement(cm, line, lineN, dims, reuse); | |
| 667 if (lineNode != reuse) { | |
| 668 container.insertBefore(lineNode, cur); | |
| 669 } else { | |
| 670 while (cur != reuse) cur = rm(cur); | |
| 671 cur = cur.nextSibling; | |
| 672 } | |
| 673 | |
| 674 lineNode.lineObj = line; | |
| 675 } | |
| 676 ++lineN; | |
| 677 }); | |
| 678 while (cur) cur = rm(cur); | 748 while (cur) cur = rm(cur); |
| 679 } | 749 } |
| 680 | 750 |
| 681 function buildLineElement(cm, line, lineNo, dims, reuse) { | 751 // When an aspect of a line changes, a string is added to |
| 682 var built = buildLineContent(cm, line), lineElement = built.pre; | 752 // lineView.changes. This updates the relevant part of the line's |
| 683 var markers = line.gutterMarkers, display = cm.display, wrap; | 753 // DOM structure. |
| 684 | 754 function updateLineForChanges(cm, lineView, lineN, dims) { |
| 685 var bgClass = built.bgClass ? built.bgClass + " " + (line.bgClass || "") : l
ine.bgClass; | 755 for (var j = 0; j < lineView.changes.length; j++) { |
| 686 if (!cm.options.lineNumbers && !markers && !bgClass && !line.wrapClass && !l
ine.widgets) | 756 var type = lineView.changes[j]; |
| 687 return lineElement; | 757 if (type == "text") updateLineText(cm, lineView); |
| 688 | 758 else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims); |
| 689 // Lines with gutter elements, widgets or a background class need | 759 else if (type == "class") updateLineClasses(lineView); |
| 690 // to be wrapped again, and have the extra elements added to the | 760 else if (type == "widget") updateLineWidgets(lineView, dims); |
| 691 // wrapper div | 761 } |
| 692 | 762 lineView.changes = null; |
| 693 if (reuse) { | 763 } |
| 694 reuse.alignable = null; | 764 |
| 695 var isOk = true, widgetsSeen = 0, insertBefore = null; | 765 // Lines with gutter elements, widgets or a background class need to |
| 696 for (var n = reuse.firstChild, next; n; n = next) { | 766 // be wrapped, and have the extra elements added to the wrapper div |
| 697 next = n.nextSibling; | 767 function ensureLineWrapped(lineView) { |
| 698 if (!/\bCodeMirror-linewidget\b/.test(n.className)) { | 768 if (lineView.node == lineView.text) { |
| 699 reuse.removeChild(n); | 769 lineView.node = elt("div", null, null, "position: relative"); |
| 700 } else { | 770 if (lineView.text.parentNode) |
| 701 for (var i = 0; i < line.widgets.length; ++i) { | 771 lineView.text.parentNode.replaceChild(lineView.node, lineView.text); |
| 702 var widget = line.widgets[i]; | 772 lineView.node.appendChild(lineView.text); |
| 703 if (widget.node == n.firstChild) { | 773 if (ie_upto7) lineView.node.style.zIndex = 2; |
| 704 if (!widget.above && !insertBefore) insertBefore = n; | 774 } |
| 705 positionLineWidget(widget, n, reuse, dims); | 775 return lineView.node; |
| 706 ++widgetsSeen; | 776 } |
| 707 break; | 777 |
| 708 } | 778 function updateLineBackground(lineView) { |
| 709 } | 779 var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass
|| "") : lineView.line.bgClass; |
| 710 if (i == line.widgets.length) { isOk = false; break; } | 780 if (cls) cls += " CodeMirror-linebackground"; |
| 711 } | 781 if (lineView.background) { |
| 712 } | 782 if (cls) lineView.background.className = cls; |
| 713 reuse.insertBefore(lineElement, insertBefore); | 783 else { lineView.background.parentNode.removeChild(lineView.background); li
neView.background = null; } |
| 714 if (isOk && widgetsSeen == line.widgets.length) { | 784 } else if (cls) { |
| 715 wrap = reuse; | 785 var wrap = ensureLineWrapped(lineView); |
| 716 reuse.className = line.wrapClass || ""; | 786 lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstC
hild); |
| 717 } | 787 } |
| 718 } | 788 } |
| 719 if (!wrap) { | 789 |
| 720 wrap = elt("div", null, line.wrapClass, "position: relative"); | 790 // Wrapper around buildLineContent which will reuse the structure |
| 721 wrap.appendChild(lineElement); | 791 // in display.externalMeasured when possible. |
| 722 } | 792 function getLineContent(cm, lineView) { |
| 723 // Kludge to make sure the styled element lies behind the selection (by z-in
dex) | 793 var ext = cm.display.externalMeasured; |
| 724 if (bgClass) | 794 if (ext && ext.line == lineView.line) { |
| 725 wrap.insertBefore(elt("div", null, bgClass + " CodeMirror-linebackground")
, wrap.firstChild); | 795 cm.display.externalMeasured = null; |
| 796 lineView.measure = ext.measure; |
| 797 return ext.built; |
| 798 } |
| 799 return buildLineContent(cm, lineView); |
| 800 } |
| 801 |
| 802 // Redraw the line's text. Interacts with the background and text |
| 803 // classes because the mode may output tokens that influence these |
| 804 // classes. |
| 805 function updateLineText(cm, lineView) { |
| 806 var cls = lineView.text.className; |
| 807 var built = getLineContent(cm, lineView); |
| 808 if (lineView.text == lineView.node) lineView.node = built.pre; |
| 809 lineView.text.parentNode.replaceChild(built.pre, lineView.text); |
| 810 lineView.text = built.pre; |
| 811 if (built.bgClass != lineView.bgClass || built.textClass != lineView.textCla
ss) { |
| 812 lineView.bgClass = built.bgClass; |
| 813 lineView.textClass = built.textClass; |
| 814 updateLineClasses(lineView); |
| 815 } else if (cls) { |
| 816 lineView.text.className = cls; |
| 817 } |
| 818 } |
| 819 |
| 820 function updateLineClasses(lineView) { |
| 821 updateLineBackground(lineView); |
| 822 if (lineView.line.wrapClass) |
| 823 ensureLineWrapped(lineView).className = lineView.line.wrapClass; |
| 824 else if (lineView.node != lineView.text) |
| 825 lineView.node.className = ""; |
| 826 var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.li
ne.textClass || "") : lineView.line.textClass; |
| 827 lineView.text.className = textClass || ""; |
| 828 } |
| 829 |
| 830 function updateLineGutter(cm, lineView, lineN, dims) { |
| 831 if (lineView.gutter) { |
| 832 lineView.node.removeChild(lineView.gutter); |
| 833 lineView.gutter = null; |
| 834 } |
| 835 var markers = lineView.line.gutterMarkers; |
| 726 if (cm.options.lineNumbers || markers) { | 836 if (cm.options.lineNumbers || markers) { |
| 727 var gutterWrap = wrap.insertBefore(elt("div", null, "CodeMirror-gutter-wra
pper", "position: absolute; left: " + | 837 var wrap = ensureLineWrapped(lineView); |
| 728 (cm.options.fixedGutter ? dims.fixe
dPos : -dims.gutterTotalWidth) + "px"), | 838 var gutterWrap = lineView.gutter = |
| 729 lineElement); | 839 wrap.insertBefore(elt("div", null, "CodeMirror-gutter-wrapper", "positio
n: absolute; left: " + |
| 730 if (cm.options.fixedGutter) (wrap.alignable || (wrap.alignable = [])).push
(gutterWrap); | 840 (cm.options.fixedGutter ? dims.fixedPos : -dims.gu
tterTotalWidth) + "px"), |
| 841 lineView.text); |
| 731 if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumber
s"])) | 842 if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumber
s"])) |
| 732 wrap.lineNumber = gutterWrap.appendChild( | 843 lineView.lineNumber = gutterWrap.appendChild( |
| 733 elt("div", lineNumberFor(cm.options, lineNo), | 844 elt("div", lineNumberFor(cm.options, lineN), |
| 734 "CodeMirror-linenumber CodeMirror-gutter-elt", | 845 "CodeMirror-linenumber CodeMirror-gutter-elt", |
| 735 "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width:
" | 846 "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width:
" |
| 736 + display.lineNumInnerWidth + "px")); | 847 + cm.display.lineNumInnerWidth + "px")); |
| 737 if (markers) | 848 if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) { |
| 738 for (var k = 0; k < cm.options.gutters.length; ++k) { | 849 var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && ma
rkers[id]; |
| 739 var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) &&
markers[id]; | 850 if (found) |
| 740 if (found) | 851 gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "l
eft: " + |
| 741 gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
"left: " + | 852 dims.gutterLeft[id] + "px; width: " + dims.
gutterWidth[id] + "px")); |
| 742 dims.gutterLeft[id] + "px; width: " + dim
s.gutterWidth[id] + "px")); | 853 } |
| 743 } | 854 } |
| 744 } | 855 } |
| 745 if (ie_lt8) wrap.style.zIndex = 2; | 856 |
| 746 if (line.widgets && wrap != reuse) for (var i = 0, ws = line.widgets; i < ws
.length; ++i) { | 857 function updateLineWidgets(lineView, dims) { |
| 858 if (lineView.alignable) lineView.alignable = null; |
| 859 for (var node = lineView.node.firstChild, next; node; node = next) { |
| 860 var next = node.nextSibling; |
| 861 if (node.className == "CodeMirror-linewidget") |
| 862 lineView.node.removeChild(node); |
| 863 } |
| 864 insertLineWidgets(lineView, dims); |
| 865 } |
| 866 |
| 867 // Build a line's DOM representation from scratch |
| 868 function buildLineElement(cm, lineView, lineN, dims) { |
| 869 var built = getLineContent(cm, lineView); |
| 870 lineView.text = lineView.node = built.pre; |
| 871 if (built.bgClass) lineView.bgClass = built.bgClass; |
| 872 if (built.textClass) lineView.textClass = built.textClass; |
| 873 |
| 874 updateLineClasses(lineView); |
| 875 updateLineGutter(cm, lineView, lineN, dims); |
| 876 insertLineWidgets(lineView, dims); |
| 877 return lineView.node; |
| 878 } |
| 879 |
| 880 // A lineView may contain multiple logical lines (when merged by |
| 881 // collapsed spans). The widgets for all of them need to be drawn. |
| 882 function insertLineWidgets(lineView, dims) { |
| 883 insertLineWidgetsFor(lineView.line, lineView, dims, true); |
| 884 if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) |
| 885 insertLineWidgetsFor(lineView.rest[i], lineView, dims, false); |
| 886 } |
| 887 |
| 888 function insertLineWidgetsFor(line, lineView, dims, allowAbove) { |
| 889 if (!line.widgets) return; |
| 890 var wrap = ensureLineWrapped(lineView); |
| 891 for (var i = 0, ws = line.widgets; i < ws.length; ++i) { |
| 747 var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidge
t"); | 892 var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidge
t"); |
| 748 if (!widget.handleMouseEvents) node.ignoreEvents = true; | 893 if (!widget.handleMouseEvents) node.ignoreEvents = true; |
| 749 positionLineWidget(widget, node, wrap, dims); | 894 positionLineWidget(widget, node, lineView, dims); |
| 750 if (widget.above) | 895 if (allowAbove && widget.above) |
| 751 wrap.insertBefore(node, cm.options.lineNumbers && line.height != 0 ? gut
terWrap : lineElement); | 896 wrap.insertBefore(node, lineView.gutter || lineView.text); |
| 752 else | 897 else |
| 753 wrap.appendChild(node); | 898 wrap.appendChild(node); |
| 754 signalLater(widget, "redraw"); | 899 signalLater(widget, "redraw"); |
| 755 } | 900 } |
| 756 return wrap; | 901 } |
| 757 } | 902 |
| 758 | 903 function positionLineWidget(widget, node, lineView, dims) { |
| 759 function positionLineWidget(widget, node, wrap, dims) { | |
| 760 if (widget.noHScroll) { | 904 if (widget.noHScroll) { |
| 761 (wrap.alignable || (wrap.alignable = [])).push(node); | 905 (lineView.alignable || (lineView.alignable = [])).push(node); |
| 762 var width = dims.wrapperWidth; | 906 var width = dims.wrapperWidth; |
| 763 node.style.left = dims.fixedPos + "px"; | 907 node.style.left = dims.fixedPos + "px"; |
| 764 if (!widget.coverGutter) { | 908 if (!widget.coverGutter) { |
| 765 width -= dims.gutterTotalWidth; | 909 width -= dims.gutterTotalWidth; |
| 766 node.style.paddingLeft = dims.gutterTotalWidth + "px"; | 910 node.style.paddingLeft = dims.gutterTotalWidth + "px"; |
| 767 } | 911 } |
| 768 node.style.width = width + "px"; | 912 node.style.width = width + "px"; |
| 769 } | 913 } |
| 770 if (widget.coverGutter) { | 914 if (widget.coverGutter) { |
| 771 node.style.zIndex = 5; | 915 node.style.zIndex = 5; |
| 772 node.style.position = "relative"; | 916 node.style.position = "relative"; |
| 773 if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "p
x"; | 917 if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "p
x"; |
| 774 } | 918 } |
| 775 } | 919 } |
| 776 | 920 |
| 921 // POSITION OBJECT |
| 922 |
| 923 // A Pos instance represents a position within the text. |
| 924 var Pos = CodeMirror.Pos = function(line, ch) { |
| 925 if (!(this instanceof Pos)) return new Pos(line, ch); |
| 926 this.line = line; this.ch = ch; |
| 927 }; |
| 928 |
| 929 // Compare two positions, return 0 if they are the same, a negative |
| 930 // number when a is less, and a positive number otherwise. |
| 931 var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch
- b.ch; }; |
| 932 |
| 933 function copyPos(x) {return Pos(x.line, x.ch);} |
| 934 function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; } |
| 935 function minPos(a, b) { return cmp(a, b) < 0 ? a : b; } |
| 936 |
| 777 // SELECTION / CURSOR | 937 // SELECTION / CURSOR |
| 778 | 938 |
| 939 // Selection objects are immutable. A new one is created every time |
| 940 // the selection changes. A selection is one or more non-overlapping |
| 941 // (and non-touching) ranges, sorted, and an integer that indicates |
| 942 // which one is the primary selection (the one that's scrolled into |
| 943 // view, that getCursor returns, etc). |
| 944 function Selection(ranges, primIndex) { |
| 945 this.ranges = ranges; |
| 946 this.primIndex = primIndex; |
| 947 } |
| 948 |
| 949 Selection.prototype = { |
| 950 primary: function() { return this.ranges[this.primIndex]; }, |
| 951 equals: function(other) { |
| 952 if (other == this) return true; |
| 953 if (other.primIndex != this.primIndex || other.ranges.length != this.range
s.length) return false; |
| 954 for (var i = 0; i < this.ranges.length; i++) { |
| 955 var here = this.ranges[i], there = other.ranges[i]; |
| 956 if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) !=
0) return false; |
| 957 } |
| 958 return true; |
| 959 }, |
| 960 deepCopy: function() { |
| 961 for (var out = [], i = 0; i < this.ranges.length; i++) |
| 962 out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i
].head)); |
| 963 return new Selection(out, this.primIndex); |
| 964 }, |
| 965 somethingSelected: function() { |
| 966 for (var i = 0; i < this.ranges.length; i++) |
| 967 if (!this.ranges[i].empty()) return true; |
| 968 return false; |
| 969 }, |
| 970 contains: function(pos, end) { |
| 971 if (!end) end = pos; |
| 972 for (var i = 0; i < this.ranges.length; i++) { |
| 973 var range = this.ranges[i]; |
| 974 if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) |
| 975 return i; |
| 976 } |
| 977 return -1; |
| 978 } |
| 979 }; |
| 980 |
| 981 function Range(anchor, head) { |
| 982 this.anchor = anchor; this.head = head; |
| 983 } |
| 984 |
| 985 Range.prototype = { |
| 986 from: function() { return minPos(this.anchor, this.head); }, |
| 987 to: function() { return maxPos(this.anchor, this.head); }, |
| 988 empty: function() { |
| 989 return this.head.line == this.anchor.line && this.head.ch == this.anchor.c
h; |
| 990 } |
| 991 }; |
| 992 |
| 993 // Take an unsorted, potentially overlapping set of ranges, and |
| 994 // build a selection out of it. 'Consumes' ranges array (modifying |
| 995 // it). |
| 996 function normalizeSelection(ranges, primIndex) { |
| 997 var prim = ranges[primIndex]; |
| 998 ranges.sort(function(a, b) { return cmp(a.from(), b.from()); }); |
| 999 primIndex = indexOf(ranges, prim); |
| 1000 for (var i = 1; i < ranges.length; i++) { |
| 1001 var cur = ranges[i], prev = ranges[i - 1]; |
| 1002 if (cmp(prev.to(), cur.from()) >= 0) { |
| 1003 var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.t
o()); |
| 1004 var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.he
ad; |
| 1005 if (i <= primIndex) --primIndex; |
| 1006 ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); |
| 1007 } |
| 1008 } |
| 1009 return new Selection(ranges, primIndex); |
| 1010 } |
| 1011 |
| 1012 function simpleSelection(anchor, head) { |
| 1013 return new Selection([new Range(anchor, head || anchor)], 0); |
| 1014 } |
| 1015 |
| 1016 // Most of the external API clips given positions to make sure they |
| 1017 // actually exist within the document. |
| 1018 function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first +
doc.size - 1));} |
| 1019 function clipPos(doc, pos) { |
| 1020 if (pos.line < doc.first) return Pos(doc.first, 0); |
| 1021 var last = doc.first + doc.size - 1; |
| 1022 if (pos.line > last) return Pos(last, getLine(doc, last).text.length); |
| 1023 return clipToLen(pos, getLine(doc, pos.line).text.length); |
| 1024 } |
| 1025 function clipToLen(pos, linelen) { |
| 1026 var ch = pos.ch; |
| 1027 if (ch == null || ch > linelen) return Pos(pos.line, linelen); |
| 1028 else if (ch < 0) return Pos(pos.line, 0); |
| 1029 else return pos; |
| 1030 } |
| 1031 function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;} |
| 1032 function clipPosArray(doc, array) { |
| 1033 for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array
[i]); |
| 1034 return out; |
| 1035 } |
| 1036 |
| 1037 // SELECTION UPDATES |
| 1038 |
| 1039 // The 'scroll' parameter given to many of these indicated whether |
| 1040 // the new cursor position should be scrolled into view after |
| 1041 // modifying the selection. |
| 1042 |
| 1043 // If shift is held or the extend flag is set, extends a range to |
| 1044 // include a given position (and optionally a second position). |
| 1045 // Otherwise, simply returns the range between the given positions. |
| 1046 // Used for cursor motion and such. |
| 1047 function extendRange(doc, range, head, other) { |
| 1048 if (doc.cm && doc.cm.display.shift || doc.extend) { |
| 1049 var anchor = range.anchor; |
| 1050 if (other) { |
| 1051 var posBefore = cmp(head, anchor) < 0; |
| 1052 if (posBefore != (cmp(other, anchor) < 0)) { |
| 1053 anchor = head; |
| 1054 head = other; |
| 1055 } else if (posBefore != (cmp(head, other) < 0)) { |
| 1056 head = other; |
| 1057 } |
| 1058 } |
| 1059 return new Range(anchor, head); |
| 1060 } else { |
| 1061 return new Range(other || head, head); |
| 1062 } |
| 1063 } |
| 1064 |
| 1065 // Extend the primary selection range, discard the rest. |
| 1066 function extendSelection(doc, head, other, options) { |
| 1067 setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, o
ther)], 0), options); |
| 1068 } |
| 1069 |
| 1070 // Extend all selections (pos is an array of selections with length |
| 1071 // equal the number of selections) |
| 1072 function extendSelections(doc, heads, options) { |
| 1073 for (var out = [], i = 0; i < doc.sel.ranges.length; i++) |
| 1074 out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null); |
| 1075 var newSel = normalizeSelection(out, doc.sel.primIndex); |
| 1076 setSelection(doc, newSel, options); |
| 1077 } |
| 1078 |
| 1079 // Updates a single range in the selection. |
| 1080 function replaceOneSelection(doc, i, range, options) { |
| 1081 var ranges = doc.sel.ranges.slice(0); |
| 1082 ranges[i] = range; |
| 1083 setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options); |
| 1084 } |
| 1085 |
| 1086 // Reset the selection to a single range. |
| 1087 function setSimpleSelection(doc, anchor, head, options) { |
| 1088 setSelection(doc, simpleSelection(anchor, head), options); |
| 1089 } |
| 1090 |
| 1091 // Give beforeSelectionChange handlers a change to influence a |
| 1092 // selection update. |
| 1093 function filterSelectionChange(doc, sel) { |
| 1094 var obj = { |
| 1095 ranges: sel.ranges, |
| 1096 update: function(ranges) { |
| 1097 this.ranges = []; |
| 1098 for (var i = 0; i < ranges.length; i++) |
| 1099 this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), |
| 1100 clipPos(doc, ranges[i].head)); |
| 1101 } |
| 1102 }; |
| 1103 signal(doc, "beforeSelectionChange", doc, obj); |
| 1104 if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); |
| 1105 if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.rang
es.length - 1); |
| 1106 else return sel; |
| 1107 } |
| 1108 |
| 1109 function setSelectionReplaceHistory(doc, sel, options) { |
| 1110 var done = doc.history.done, last = lst(done); |
| 1111 if (last && last.ranges) { |
| 1112 done[done.length - 1] = sel; |
| 1113 setSelectionNoUndo(doc, sel, options); |
| 1114 } else { |
| 1115 setSelection(doc, sel, options); |
| 1116 } |
| 1117 } |
| 1118 |
| 1119 // Set a new selection. |
| 1120 function setSelection(doc, sel, options) { |
| 1121 setSelectionNoUndo(doc, sel, options); |
| 1122 addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options)
; |
| 1123 } |
| 1124 |
| 1125 function setSelectionNoUndo(doc, sel, options) { |
| 1126 if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm,
"beforeSelectionChange")) |
| 1127 sel = filterSelectionChange(doc, sel); |
| 1128 |
| 1129 var bias = cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1; |
| 1130 setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); |
| 1131 |
| 1132 if (!(options && options.scroll === false) && doc.cm) |
| 1133 ensureCursorVisible(doc.cm); |
| 1134 } |
| 1135 |
| 1136 function setSelectionInner(doc, sel) { |
| 1137 if (sel.equals(doc.sel)) return; |
| 1138 |
| 1139 doc.sel = sel; |
| 1140 |
| 1141 if (doc.cm) |
| 1142 doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = |
| 1143 doc.cm.curOp.cursorActivity = true; |
| 1144 signalLater(doc, "cursorActivity", doc); |
| 1145 } |
| 1146 |
| 1147 // Verify that the selection does not partially select any atomic |
| 1148 // marked ranges. |
| 1149 function reCheckSelection(doc) { |
| 1150 setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel
_dontScroll); |
| 1151 } |
| 1152 |
| 1153 // Return a selection that does not partially select any atomic |
| 1154 // ranges. |
| 1155 function skipAtomicInSelection(doc, sel, bias, mayClear) { |
| 1156 var out; |
| 1157 for (var i = 0; i < sel.ranges.length; i++) { |
| 1158 var range = sel.ranges[i]; |
| 1159 var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear); |
| 1160 var newHead = skipAtomic(doc, range.head, bias, mayClear); |
| 1161 if (out || newAnchor != range.anchor || newHead != range.head) { |
| 1162 if (!out) out = sel.ranges.slice(0, i); |
| 1163 out[i] = new Range(newAnchor, newHead); |
| 1164 } |
| 1165 } |
| 1166 return out ? normalizeSelection(out, sel.primIndex) : sel; |
| 1167 } |
| 1168 |
| 1169 // Ensure a given position is not inside an atomic range. |
| 1170 function skipAtomic(doc, pos, bias, mayClear) { |
| 1171 var flipped = false, curPos = pos; |
| 1172 var dir = bias || 1; |
| 1173 doc.cantEdit = false; |
| 1174 search: for (;;) { |
| 1175 var line = getLine(doc, curPos.line); |
| 1176 if (line.markedSpans) { |
| 1177 for (var i = 0; i < line.markedSpans.length; ++i) { |
| 1178 var sp = line.markedSpans[i], m = sp.marker; |
| 1179 if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.f
rom < curPos.ch)) && |
| 1180 (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to >
curPos.ch))) { |
| 1181 if (mayClear) { |
| 1182 signal(m, "beforeCursorEnter"); |
| 1183 if (m.explicitlyCleared) { |
| 1184 if (!line.markedSpans) break; |
| 1185 else {--i; continue;} |
| 1186 } |
| 1187 } |
| 1188 if (!m.atomic) continue; |
| 1189 var newPos = m.find(dir < 0 ? -1 : 1); |
| 1190 if (cmp(newPos, curPos) == 0) { |
| 1191 newPos.ch += dir; |
| 1192 if (newPos.ch < 0) { |
| 1193 if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.li
ne - 1)); |
| 1194 else newPos = null; |
| 1195 } else if (newPos.ch > line.text.length) { |
| 1196 if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.
line + 1, 0); |
| 1197 else newPos = null; |
| 1198 } |
| 1199 if (!newPos) { |
| 1200 if (flipped) { |
| 1201 // Driven in a corner -- no valid cursor position found at all |
| 1202 // -- try again *with* clearing, if we didn't already |
| 1203 if (!mayClear) return skipAtomic(doc, pos, bias, true); |
| 1204 // Otherwise, turn off editing until further notice, and retur
n the start of the doc |
| 1205 doc.cantEdit = true; |
| 1206 return Pos(doc.first, 0); |
| 1207 } |
| 1208 flipped = true; newPos = pos; dir = -dir; |
| 1209 } |
| 1210 } |
| 1211 curPos = newPos; |
| 1212 continue search; |
| 1213 } |
| 1214 } |
| 1215 } |
| 1216 return curPos; |
| 1217 } |
| 1218 } |
| 1219 |
| 1220 // SELECTION DRAWING |
| 1221 |
| 1222 // Redraw the selection and/or cursor |
| 779 function updateSelection(cm) { | 1223 function updateSelection(cm) { |
| 780 var display = cm.display; | 1224 var display = cm.display, doc = cm.doc; |
| 781 var collapsed = posEq(cm.doc.sel.from, cm.doc.sel.to); | 1225 var curFragment = document.createDocumentFragment(); |
| 782 if (collapsed || cm.options.showCursorWhenSelecting) | 1226 var selFragment = document.createDocumentFragment(); |
| 783 updateSelectionCursor(cm); | 1227 |
| 784 else | 1228 for (var i = 0; i < doc.sel.ranges.length; i++) { |
| 785 display.cursor.style.display = display.otherCursor.style.display = "none"; | 1229 var range = doc.sel.ranges[i]; |
| 786 if (!collapsed) | 1230 var collapsed = range.empty(); |
| 787 updateSelectionRange(cm); | 1231 if (collapsed || cm.options.showCursorWhenSelecting) |
| 788 else | 1232 updateSelectionCursor(cm, range, curFragment); |
| 789 display.selectionDiv.style.display = "none"; | 1233 if (!collapsed) |
| 1234 updateSelectionRange(cm, range, selFragment); |
| 1235 } |
| 790 | 1236 |
| 791 // Move the hidden textarea near the cursor to prevent scrolling artifacts | 1237 // Move the hidden textarea near the cursor to prevent scrolling artifacts |
| 792 if (cm.options.moveInputWithCursor) { | 1238 if (cm.options.moveInputWithCursor) { |
| 793 var headPos = cursorCoords(cm, cm.doc.sel.head, "div"); | 1239 var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); |
| 794 var wrapOff = getRect(display.wrapper), lineOff = getRect(display.lineDiv)
; | 1240 var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.l
ineDiv.getBoundingClientRect(); |
| 795 display.inputDiv.style.top = Math.max(0, Math.min(display.wrapper.clientHe
ight - 10, | 1241 var top = Math.max(0, Math.min(display.wrapper.clientHeight - 10, |
| 796 headPos.top + lineOff.to
p - wrapOff.top)) + "px"; | 1242 headPos.top + lineOff.top - wrapOff.top)); |
| 797 display.inputDiv.style.left = Math.max(0, Math.min(display.wrapper.clientW
idth - 10, | 1243 var left = Math.max(0, Math.min(display.wrapper.clientWidth - 10, |
| 798 headPos.left + lineOff.
left - wrapOff.left)) + "px"; | 1244 headPos.left + lineOff.left - wrapOff.left
)); |
| 799 } | 1245 display.inputDiv.style.top = top + "px"; |
| 800 } | 1246 display.inputDiv.style.left = left + "px"; |
| 801 | 1247 } |
| 802 // No selection, plain cursor | 1248 |
| 803 function updateSelectionCursor(cm) { | 1249 removeChildrenAndAdd(display.cursorDiv, curFragment); |
| 804 var display = cm.display, pos = cursorCoords(cm, cm.doc.sel.head, "div"); | 1250 removeChildrenAndAdd(display.selectionDiv, selFragment); |
| 805 display.cursor.style.left = pos.left + "px"; | 1251 } |
| 806 display.cursor.style.top = pos.top + "px"; | 1252 |
| 807 display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options
.cursorHeight + "px"; | 1253 // Draws a cursor for the given range |
| 808 display.cursor.style.display = ""; | 1254 function updateSelectionCursor(cm, range, output) { |
| 1255 var pos = cursorCoords(cm, range.head, "div"); |
| 1256 |
| 1257 var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); |
| 1258 cursor.style.left = pos.left + "px"; |
| 1259 cursor.style.top = pos.top + "px"; |
| 1260 cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorH
eight + "px"; |
| 809 | 1261 |
| 810 if (pos.other) { | 1262 if (pos.other) { |
| 811 display.otherCursor.style.display = ""; | 1263 // Secondary cursor, shown when on a 'jump' in bi-directional text |
| 812 display.otherCursor.style.left = pos.other.left + "px"; | 1264 var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-curs
or CodeMirror-secondarycursor")); |
| 813 display.otherCursor.style.top = pos.other.top + "px"; | 1265 otherCursor.style.display = ""; |
| 814 display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .8
5 + "px"; | 1266 otherCursor.style.left = pos.other.left + "px"; |
| 815 } else { display.otherCursor.style.display = "none"; } | 1267 otherCursor.style.top = pos.other.top + "px"; |
| 816 } | 1268 otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"
; |
| 817 | 1269 } |
| 818 // Highlight selection | 1270 } |
| 819 function updateSelectionRange(cm) { | 1271 |
| 820 var display = cm.display, doc = cm.doc, sel = cm.doc.sel; | 1272 // Draws the given range as a highlighted selection |
| 1273 function updateSelectionRange(cm, range, output) { |
| 1274 var display = cm.display, doc = cm.doc; |
| 821 var fragment = document.createDocumentFragment(); | 1275 var fragment = document.createDocumentFragment(); |
| 822 var clientWidth = display.lineSpace.offsetWidth, pl = paddingLeft(cm.display
); | 1276 var padding = paddingH(cm.display), leftSide = padding.left, rightSide = dis
play.lineSpace.offsetWidth - padding.right; |
| 823 | 1277 |
| 824 function add(left, top, width, bottom) { | 1278 function add(left, top, width, bottom) { |
| 825 if (top < 0) top = 0; | 1279 if (top < 0) top = 0; |
| 826 fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: ab
solute; left: " + left + | 1280 fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: ab
solute; left: " + left + |
| 827 "px; top: " + top + "px; width: " + (width == nul
l ? clientWidth - left : width) + | 1281 "px; top: " + top + "px; width: " + (width == nul
l ? rightSide - left : width) + |
| 828 "px; height: " + (bottom - top) + "px")); | 1282 "px; height: " + (bottom - top) + "px")); |
| 829 } | 1283 } |
| 830 | 1284 |
| 831 function drawForLine(line, fromArg, toArg) { | 1285 function drawForLine(line, fromArg, toArg) { |
| 832 var lineObj = getLine(doc, line); | 1286 var lineObj = getLine(doc, line); |
| 833 var lineLen = lineObj.text.length; | 1287 var lineLen = lineObj.text.length; |
| 834 var start, end; | 1288 var start, end; |
| 835 function coords(ch, bias) { | 1289 function coords(ch, bias) { |
| 836 return charCoords(cm, Pos(line, ch), "div", lineObj, bias); | 1290 return charCoords(cm, Pos(line, ch), "div", lineObj, bias); |
| 837 } | 1291 } |
| 838 | 1292 |
| 839 iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineL
en : toArg, function(from, to, dir) { | 1293 iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineL
en : toArg, function(from, to, dir) { |
| 840 var leftPos = coords(from, "left"), rightPos, left, right; | 1294 var leftPos = coords(from, "left"), rightPos, left, right; |
| 841 if (from == to) { | 1295 if (from == to) { |
| 842 rightPos = leftPos; | 1296 rightPos = leftPos; |
| 843 left = right = leftPos.left; | 1297 left = right = leftPos.left; |
| 844 } else { | 1298 } else { |
| 845 rightPos = coords(to - 1, "right"); | 1299 rightPos = coords(to - 1, "right"); |
| 846 if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos =
tmp; } | 1300 if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos =
tmp; } |
| 847 left = leftPos.left; | 1301 left = leftPos.left; |
| 848 right = rightPos.right; | 1302 right = rightPos.right; |
| 849 } | 1303 } |
| 850 if (fromArg == null && from == 0) left = pl; | 1304 if (fromArg == null && from == 0) left = leftSide; |
| 851 if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part | 1305 if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part |
| 852 add(left, leftPos.top, null, leftPos.bottom); | 1306 add(left, leftPos.top, null, leftPos.bottom); |
| 853 left = pl; | 1307 left = leftSide; |
| 854 if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rig
htPos.top); | 1308 if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rig
htPos.top); |
| 855 } | 1309 } |
| 856 if (toArg == null && to == lineLen) right = clientWidth; | 1310 if (toArg == null && to == lineLen) right = rightSide; |
| 857 if (!start || leftPos.top < start.top || leftPos.top == start.top && lef
tPos.left < start.left) | 1311 if (!start || leftPos.top < start.top || leftPos.top == start.top && lef
tPos.left < start.left) |
| 858 start = leftPos; | 1312 start = leftPos; |
| 859 if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.botto
m && rightPos.right > end.right) | 1313 if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.botto
m && rightPos.right > end.right) |
| 860 end = rightPos; | 1314 end = rightPos; |
| 861 if (left < pl + 1) left = pl; | 1315 if (left < leftSide + 1) left = leftSide; |
| 862 add(left, rightPos.top, right - left, rightPos.bottom); | 1316 add(left, rightPos.top, right - left, rightPos.bottom); |
| 863 }); | 1317 }); |
| 864 return {start: start, end: end}; | 1318 return {start: start, end: end}; |
| 865 } | 1319 } |
| 866 | 1320 |
| 867 if (sel.from.line == sel.to.line) { | 1321 var sFrom = range.from(), sTo = range.to(); |
| 868 drawForLine(sel.from.line, sel.from.ch, sel.to.ch); | 1322 if (sFrom.line == sTo.line) { |
| 1323 drawForLine(sFrom.line, sFrom.ch, sTo.ch); |
| 869 } else { | 1324 } else { |
| 870 var fromLine = getLine(doc, sel.from.line), toLine = getLine(doc, sel.to.l
ine); | 1325 var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); |
| 871 var singleVLine = visualLine(doc, fromLine) == visualLine(doc, toLine); | 1326 var singleVLine = visualLine(fromLine) == visualLine(toLine); |
| 872 var leftEnd = drawForLine(sel.from.line, sel.from.ch, singleVLine ? fromLi
ne.text.length : null).end; | 1327 var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.tex
t.length + 1 : null).end; |
| 873 var rightStart = drawForLine(sel.to.line, singleVLine ? 0 : null, sel.to.c
h).start; | 1328 var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).sta
rt; |
| 874 if (singleVLine) { | 1329 if (singleVLine) { |
| 875 if (leftEnd.top < rightStart.top - 2) { | 1330 if (leftEnd.top < rightStart.top - 2) { |
| 876 add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); | 1331 add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); |
| 877 add(pl, rightStart.top, rightStart.left, rightStart.bottom); | 1332 add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); |
| 878 } else { | 1333 } else { |
| 879 add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftE
nd.bottom); | 1334 add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftE
nd.bottom); |
| 880 } | 1335 } |
| 881 } | 1336 } |
| 882 if (leftEnd.bottom < rightStart.top) | 1337 if (leftEnd.bottom < rightStart.top) |
| 883 add(pl, leftEnd.bottom, null, rightStart.top); | 1338 add(leftSide, leftEnd.bottom, null, rightStart.top); |
| 884 } | 1339 } |
| 885 | 1340 |
| 886 removeChildrenAndAdd(display.selectionDiv, fragment); | 1341 output.appendChild(fragment); |
| 887 display.selectionDiv.style.display = ""; | |
| 888 } | 1342 } |
| 889 | 1343 |
| 890 // Cursor-blinking | 1344 // Cursor-blinking |
| 891 function restartBlink(cm) { | 1345 function restartBlink(cm) { |
| 892 if (!cm.state.focused) return; | 1346 if (!cm.state.focused) return; |
| 893 var display = cm.display; | 1347 var display = cm.display; |
| 894 clearInterval(display.blinker); | 1348 clearInterval(display.blinker); |
| 895 var on = true; | 1349 var on = true; |
| 896 display.cursor.style.visibility = display.otherCursor.style.visibility = ""; | 1350 display.cursorDiv.style.visibility = ""; |
| 897 if (cm.options.cursorBlinkRate > 0) | 1351 if (cm.options.cursorBlinkRate > 0) |
| 898 display.blinker = setInterval(function() { | 1352 display.blinker = setInterval(function() { |
| 899 display.cursor.style.visibility = display.otherCursor.style.visibility =
(on = !on) ? "" : "hidden"; | 1353 display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; |
| 900 }, cm.options.cursorBlinkRate); | 1354 }, cm.options.cursorBlinkRate); |
| 901 } | 1355 } |
| 902 | 1356 |
| 903 // HIGHLIGHT WORKER | 1357 // HIGHLIGHT WORKER |
| 904 | 1358 |
| 905 function startWorker(cm, time) { | 1359 function startWorker(cm, time) { |
| 906 if (cm.doc.mode.startState && cm.doc.frontier < cm.display.showingTo) | 1360 if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo) |
| 907 cm.state.highlight.set(time, bind(highlightWorker, cm)); | 1361 cm.state.highlight.set(time, bind(highlightWorker, cm)); |
| 908 } | 1362 } |
| 909 | 1363 |
| 910 function highlightWorker(cm) { | 1364 function highlightWorker(cm) { |
| 911 var doc = cm.doc; | 1365 var doc = cm.doc; |
| 912 if (doc.frontier < doc.first) doc.frontier = doc.first; | 1366 if (doc.frontier < doc.first) doc.frontier = doc.first; |
| 913 if (doc.frontier >= cm.display.showingTo) return; | 1367 if (doc.frontier >= cm.display.viewTo) return; |
| 914 var end = +new Date + cm.options.workTime; | 1368 var end = +new Date + cm.options.workTime; |
| 915 var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)); | 1369 var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)); |
| 916 var changed = [], prevChange; | 1370 |
| 917 doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.showingTo +
500), function(line) { | 1371 runInOp(cm, function() { |
| 918 if (doc.frontier >= cm.display.showingFrom) { // Visible | 1372 doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 50
0), function(line) { |
| 1373 if (doc.frontier >= cm.display.viewFrom) { // Visible |
| 919 var oldStyles = line.styles; | 1374 var oldStyles = line.styles; |
| 920 line.styles = highlightLine(cm, line, state, true); | 1375 line.styles = highlightLine(cm, line, state, true); |
| 921 var ischange = !oldStyles || oldStyles.length != line.styles.length; | 1376 var ischange = !oldStyles || oldStyles.length != line.styles.length; |
| 922 for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldSt
yles[i] != line.styles[i]; | 1377 for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldSt
yles[i] != line.styles[i]; |
| 923 if (ischange) { | 1378 if (ischange) regLineChange(cm, doc.frontier, "text"); |
| 924 if (prevChange && prevChange.end == doc.frontier) prevChange.end++; | |
| 925 else changed.push(prevChange = {start: doc.frontier, end: doc.frontier
+ 1}); | |
| 926 } | |
| 927 line.stateAfter = copyState(doc.mode, state); | 1379 line.stateAfter = copyState(doc.mode, state); |
| 928 } else { | 1380 } else { |
| 929 processLine(cm, line.text, state); | 1381 processLine(cm, line.text, state); |
| 930 line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : n
ull; | 1382 line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : n
ull; |
| 931 } | 1383 } |
| 932 ++doc.frontier; | 1384 ++doc.frontier; |
| 933 if (+new Date > end) { | 1385 if (+new Date > end) { |
| 934 startWorker(cm, cm.options.workDelay); | 1386 startWorker(cm, cm.options.workDelay); |
| 935 return true; | 1387 return true; |
| 936 } | 1388 } |
| 937 }); | 1389 }); |
| 938 if (changed.length) | 1390 }); |
| 939 operation(cm, function() { | |
| 940 for (var i = 0; i < changed.length; ++i) | |
| 941 regChange(this, changed[i].start, changed[i].end); | |
| 942 })(); | |
| 943 } | 1391 } |
| 944 | 1392 |
| 945 // Finds the line to start with when starting a parse. Tries to | 1393 // Finds the line to start with when starting a parse. Tries to |
| 946 // find a line with a stateAfter, so that it can start with a | 1394 // find a line with a stateAfter, so that it can start with a |
| 947 // valid state. If that fails, it returns the line with the | 1395 // valid state. If that fails, it returns the line with the |
| 948 // smallest indentation, which tends to need the least context to | 1396 // smallest indentation, which tends to need the least context to |
| 949 // parse correctly. | 1397 // parse correctly. |
| 950 function findStartLine(cm, n, precise) { | 1398 function findStartLine(cm, n, precise) { |
| 951 var minindent, minline, doc = cm.doc; | 1399 var minindent, minline, doc = cm.doc; |
| 952 var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); | 1400 var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); |
| (...skipping 11 matching lines...) Expand all Loading... |
| 964 } | 1412 } |
| 965 | 1413 |
| 966 function getStateBefore(cm, n, precise) { | 1414 function getStateBefore(cm, n, precise) { |
| 967 var doc = cm.doc, display = cm.display; | 1415 var doc = cm.doc, display = cm.display; |
| 968 if (!doc.mode.startState) return true; | 1416 if (!doc.mode.startState) return true; |
| 969 var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(
doc, pos-1).stateAfter; | 1417 var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(
doc, pos-1).stateAfter; |
| 970 if (!state) state = startState(doc.mode); | 1418 if (!state) state = startState(doc.mode); |
| 971 else state = copyState(doc.mode, state); | 1419 else state = copyState(doc.mode, state); |
| 972 doc.iter(pos, n, function(line) { | 1420 doc.iter(pos, n, function(line) { |
| 973 processLine(cm, line.text, state); | 1421 processLine(cm, line.text, state); |
| 974 var save = pos == n - 1 || pos % 5 == 0 || pos >= display.showingFrom && p
os < display.showingTo; | 1422 var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos
< display.viewTo; |
| 975 line.stateAfter = save ? copyState(doc.mode, state) : null; | 1423 line.stateAfter = save ? copyState(doc.mode, state) : null; |
| 976 ++pos; | 1424 ++pos; |
| 977 }); | 1425 }); |
| 978 if (precise) doc.frontier = pos; | 1426 if (precise) doc.frontier = pos; |
| 979 return state; | 1427 return state; |
| 980 } | 1428 } |
| 981 | 1429 |
| 982 // POSITION MEASUREMENT | 1430 // POSITION MEASUREMENT |
| 983 | 1431 |
| 984 function paddingTop(display) {return display.lineSpace.offsetTop;} | 1432 function paddingTop(display) {return display.lineSpace.offsetTop;} |
| 985 function paddingVert(display) {return display.mover.offsetHeight - display.lin
eSpace.offsetHeight;} | 1433 function paddingVert(display) {return display.mover.offsetHeight - display.lin
eSpace.offsetHeight;} |
| 986 function paddingLeft(display) { | 1434 function paddingH(display) { |
| 987 var e = removeChildrenAndAdd(display.measure, elt("pre", null, null, "text-a
lign: left")).appendChild(elt("span", "x")); | 1435 if (display.cachedPaddingH) return display.cachedPaddingH; |
| 988 return e.offsetLeft; | 1436 var e = removeChildrenAndAdd(display.measure, elt("pre", "x")); |
| 989 } | 1437 var style = window.getComputedStyle ? window.getComputedStyle(e) : e.current
Style; |
| 990 | 1438 return display.cachedPaddingH = {left: parseInt(style.paddingLeft), |
| 991 function measureChar(cm, line, ch, data, bias) { | 1439 right: parseInt(style.paddingRight)}; |
| 992 var dir = -1; | 1440 } |
| 993 data = data || measureLine(cm, line); | 1441 |
| 994 if (data.crude) { | 1442 // Ensure the lineView.wrapping.heights array is populated. This is |
| 995 var left = data.left + ch * data.width; | 1443 // an array of bottom offsets for the lines that make up a drawn |
| 996 return {left: left, right: left + data.width, top: data.top, bottom: data.
bottom}; | 1444 // line. When lineWrapping is on, there might be more than one |
| 997 } | 1445 // height. |
| 998 | 1446 function ensureLineHeights(cm, lineView, rect) { |
| 999 for (var pos = ch;; pos += dir) { | 1447 var wrapping = cm.options.lineWrapping; |
| 1000 var r = data[pos]; | 1448 var curWidth = wrapping && cm.display.scroller.clientWidth; |
| 1001 if (r) break; | 1449 if (!lineView.measure.heights || wrapping && lineView.measure.width != curWi
dth) { |
| 1002 if (dir < 0 && pos == 0) dir = 1; | 1450 var heights = lineView.measure.heights = []; |
| 1003 } | 1451 if (wrapping) { |
| 1004 bias = pos > ch ? "left" : pos < ch ? "right" : bias; | 1452 lineView.measure.width = curWidth; |
| 1005 if (bias == "left" && r.leftSide) r = r.leftSide; | 1453 var rects = lineView.text.firstChild.getClientRects(); |
| 1006 else if (bias == "right" && r.rightSide) r = r.rightSide; | 1454 for (var i = 0; i < rects.length - 1; i++) { |
| 1007 return {left: pos < ch ? r.right : r.left, | 1455 var cur = rects[i], next = rects[i + 1]; |
| 1008 right: pos > ch ? r.left : r.right, | 1456 if (Math.abs(cur.bottom - next.bottom) > 2) |
| 1009 top: r.top, | 1457 heights.push((cur.bottom + next.top) / 2 - rect.top); |
| 1010 bottom: r.bottom}; | |
| 1011 } | |
| 1012 | |
| 1013 function findCachedMeasurement(cm, line) { | |
| 1014 var cache = cm.display.measureLineCache; | |
| 1015 for (var i = 0; i < cache.length; ++i) { | |
| 1016 var memo = cache[i]; | |
| 1017 if (memo.text == line.text && memo.markedSpans == line.markedSpans && | |
| 1018 cm.display.scroller.clientWidth == memo.width && | |
| 1019 memo.classes == line.textClass + "|" + line.wrapClass) | |
| 1020 return memo; | |
| 1021 } | |
| 1022 } | |
| 1023 | |
| 1024 function clearCachedMeasurement(cm, line) { | |
| 1025 var exists = findCachedMeasurement(cm, line); | |
| 1026 if (exists) exists.text = exists.measure = exists.markedSpans = null; | |
| 1027 } | |
| 1028 | |
| 1029 function measureLine(cm, line) { | |
| 1030 // First look in the cache | |
| 1031 var cached = findCachedMeasurement(cm, line); | |
| 1032 if (cached) return cached.measure; | |
| 1033 | |
| 1034 // Failing that, recompute and store result in cache | |
| 1035 var measure = measureLineInner(cm, line); | |
| 1036 var cache = cm.display.measureLineCache; | |
| 1037 var memo = {text: line.text, width: cm.display.scroller.clientWidth, | |
| 1038 markedSpans: line.markedSpans, measure: measure, | |
| 1039 classes: line.textClass + "|" + line.wrapClass}; | |
| 1040 if (cache.length == 16) cache[++cm.display.measureLineCachePos % 16] = memo; | |
| 1041 else cache.push(memo); | |
| 1042 return measure; | |
| 1043 } | |
| 1044 | |
| 1045 function measureLineInner(cm, line) { | |
| 1046 if (!cm.options.lineWrapping && line.text.length >= cm.options.crudeMeasurin
gFrom) | |
| 1047 return crudelyMeasureLine(cm, line); | |
| 1048 | |
| 1049 var display = cm.display, measure = emptyArray(line.text.length); | |
| 1050 var pre = buildLineContent(cm, line, measure, true).pre; | |
| 1051 | |
| 1052 // IE does not cache element positions of inline elements between | |
| 1053 // calls to getBoundingClientRect. This makes the loop below, | |
| 1054 // which gathers the positions of all the characters on the line, | |
| 1055 // do an amount of layout work quadratic to the number of | |
| 1056 // characters. When line wrapping is off, we try to improve things | |
| 1057 // by first subdividing the line into a bunch of inline blocks, so | |
| 1058 // that IE can reuse most of the layout information from caches | |
| 1059 // for those blocks. This does interfere with line wrapping, so it | |
| 1060 // doesn't work when wrapping is on, but in that case the | |
| 1061 // situation is slightly better, since IE does cache line-wrapping | |
| 1062 // information and only recomputes per-line. | |
| 1063 if (old_ie && !ie_lt8 && !cm.options.lineWrapping && pre.childNodes.length >
100) { | |
| 1064 var fragment = document.createDocumentFragment(); | |
| 1065 var chunk = 10, n = pre.childNodes.length; | |
| 1066 for (var i = 0, chunks = Math.ceil(n / chunk); i < chunks; ++i) { | |
| 1067 var wrap = elt("div", null, null, "display: inline-block"); | |
| 1068 for (var j = 0; j < chunk && n; ++j) { | |
| 1069 wrap.appendChild(pre.firstChild); | |
| 1070 --n; | |
| 1071 } | 1458 } |
| 1072 fragment.appendChild(wrap); | 1459 } |
| 1073 } | 1460 heights.push(rect.bottom - rect.top); |
| 1074 pre.appendChild(fragment); | 1461 } |
| 1075 } | 1462 } |
| 1076 | 1463 |
| 1077 removeChildrenAndAdd(display.measure, pre); | 1464 // Find a line map (mapping character offsets to text nodes) and a |
| 1078 | 1465 // measurement cache for the given line number. (A line view might |
| 1079 var outer = getRect(display.lineDiv); | 1466 // contain multiple lines when collapsed ranges are present.) |
| 1080 var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHe
ight; | 1467 function mapFromLineView(lineView, line, lineN) { |
| 1081 // Work around an IE7/8 bug where it will sometimes have randomly | 1468 if (lineView.line == line) |
| 1082 // replaced our pre with a clone at this point. | 1469 return {map: lineView.measure.map, cache: lineView.measure.cache}; |
| 1083 if (ie_lt9 && display.measure.first != pre) | 1470 for (var i = 0; i < lineView.rest.length; i++) |
| 1084 removeChildrenAndAdd(display.measure, pre); | 1471 if (lineView.rest[i] == line) |
| 1085 | 1472 return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]
}; |
| 1086 function measureRect(rect) { | 1473 for (var i = 0; i < lineView.rest.length; i++) |
| 1087 var top = rect.top - outer.top, bot = rect.bottom - outer.top; | 1474 if (lineNo(lineView.rest[i]) > lineN) |
| 1088 if (bot > maxBot) bot = maxBot; | 1475 return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]
, before: true}; |
| 1089 if (top < 0) top = 0; | 1476 } |
| 1090 for (var i = vranges.length - 2; i >= 0; i -= 2) { | 1477 |
| 1091 var rtop = vranges[i], rbot = vranges[i+1]; | 1478 // Render a line into the hidden node display.externalMeasured. Used |
| 1092 if (rtop > bot || rbot < top) continue; | 1479 // when measurement is needed for a line that's not in the viewport. |
| 1093 if (rtop <= top && rbot >= bot || | 1480 function updateExternalMeasurement(cm, line) { |
| 1094 top <= rtop && bot >= rbot || | 1481 line = visualLine(line); |
| 1095 Math.min(bot, rbot) - Math.max(top, rtop) >= (bot - top) >> 1) { | 1482 var lineN = lineNo(line); |
| 1096 vranges[i] = Math.min(top, rtop); | 1483 var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); |
| 1097 vranges[i+1] = Math.max(bot, rbot); | 1484 view.lineN = lineN; |
| 1098 break; | 1485 var built = view.built = buildLineContent(cm, view); |
| 1099 } | 1486 view.text = built.pre; |
| 1100 } | 1487 removeChildrenAndAdd(cm.display.lineMeasure, built.pre); |
| 1101 if (i < 0) { i = vranges.length; vranges.push(top, bot); } | 1488 return view; |
| 1102 return {left: rect.left - outer.left, | 1489 } |
| 1103 right: rect.right - outer.left, | 1490 |
| 1104 top: i, bottom: null}; | 1491 // Get a {top, bottom, left, right} box (in line-local coordinates) |
| 1105 } | 1492 // for a given character. |
| 1106 function finishRect(rect) { | 1493 function measureChar(cm, line, ch, bias) { |
| 1107 rect.bottom = vranges[rect.top+1]; | 1494 return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias); |
| 1108 rect.top = vranges[rect.top]; | 1495 } |
| 1109 } | 1496 |
| 1110 | 1497 // Find a line view that corresponds to the given line number. |
| 1111 for (var i = 0, cur; i < measure.length; ++i) if (cur = measure[i]) { | 1498 function findViewForLine(cm, lineN) { |
| 1112 var node = cur, rect = null; | 1499 if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) |
| 1113 // A widget might wrap, needs special care | 1500 return cm.display.view[findViewIndex(cm, lineN)]; |
| 1114 if (/\bCodeMirror-widget\b/.test(cur.className) && cur.getClientRects) { | 1501 var ext = cm.display.externalMeasured; |
| 1115 if (cur.firstChild.nodeType == 1) node = cur.firstChild; | 1502 if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) |
| 1116 var rects = node.getClientRects(); | 1503 return ext; |
| 1117 if (rects.length > 1) { | 1504 } |
| 1118 rect = data[i] = measureRect(rects[0]); | 1505 |
| 1119 rect.rightSide = measureRect(rects[rects.length - 1]); | 1506 // Measurement can be split in two steps, the set-up work that |
| 1120 } | 1507 // applies to the whole line, and the measurement of the actual |
| 1121 } | 1508 // character. Functions like coordsChar, that need to do a lot of |
| 1122 if (!rect) rect = data[i] = measureRect(getRect(node)); | 1509 // measurements in a row, can thus ensure that the set-up work is |
| 1123 if (cur.measureRight) rect.right = getRect(cur.measureRight).left - outer.
left; | 1510 // only done once. |
| 1124 if (cur.leftSide) rect.leftSide = measureRect(getRect(cur.leftSide)); | 1511 function prepareMeasureForLine(cm, line) { |
| 1125 } | 1512 var lineN = lineNo(line); |
| 1126 removeChildren(cm.display.measure); | 1513 var view = findViewForLine(cm, lineN); |
| 1127 for (var i = 0, cur; i < data.length; ++i) if (cur = data[i]) { | 1514 if (view && !view.text) |
| 1128 finishRect(cur); | 1515 view = null; |
| 1129 if (cur.leftSide) finishRect(cur.leftSide); | 1516 else if (view && view.changes) |
| 1130 if (cur.rightSide) finishRect(cur.rightSide); | 1517 updateLineForChanges(cm, view, lineN, getDimensions(cm)); |
| 1131 } | 1518 if (!view) |
| 1132 return data; | 1519 view = updateExternalMeasurement(cm, line); |
| 1133 } | 1520 |
| 1134 | 1521 var info = mapFromLineView(view, line, lineN); |
| 1135 function crudelyMeasureLine(cm, line) { | 1522 return { |
| 1136 var copy = new Line(line.text.slice(0, 100), null); | 1523 line: line, view: view, rect: null, |
| 1137 if (line.textClass) copy.textClass = line.textClass; | 1524 map: info.map, cache: info.cache, before: info.before, |
| 1138 var measure = measureLineInner(cm, copy); | 1525 hasHeights: false |
| 1139 var left = measureChar(cm, copy, 0, measure, "left"); | 1526 }; |
| 1140 var right = measureChar(cm, copy, 99, measure, "right"); | 1527 } |
| 1141 return {crude: true, top: left.top, left: left.left, bottom: left.bottom, wi
dth: (right.right - left.left) / 100}; | 1528 |
| 1142 } | 1529 // Given a prepared measurement object, measures the position of an |
| 1143 | 1530 // actual character (or fetches it from the cache). |
| 1144 function measureLineWidth(cm, line) { | 1531 function measureCharPrepared(cm, prepared, ch, bias) { |
| 1145 var hasBadSpan = false; | 1532 if (prepared.before) ch = -1; |
| 1146 if (line.markedSpans) for (var i = 0; i < line.markedSpans; ++i) { | 1533 var key = ch + (bias || ""), found; |
| 1147 var sp = line.markedSpans[i]; | 1534 if (prepared.cache.hasOwnProperty(key)) { |
| 1148 if (sp.collapsed && (sp.to == null || sp.to == line.text.length)) hasBadSp
an = true; | 1535 found = prepared.cache[key]; |
| 1149 } | 1536 } else { |
| 1150 var cached = !hasBadSpan && findCachedMeasurement(cm, line); | 1537 if (!prepared.rect) |
| 1151 if (cached || line.text.length >= cm.options.crudeMeasuringFrom) | 1538 prepared.rect = prepared.view.text.getBoundingClientRect(); |
| 1152 return measureChar(cm, line, line.text.length, cached && cached.measure, "
right").right; | 1539 if (!prepared.hasHeights) { |
| 1153 | 1540 ensureLineHeights(cm, prepared.view, prepared.rect); |
| 1154 var pre = buildLineContent(cm, line, null, true).pre; | 1541 prepared.hasHeights = true; |
| 1155 var end = pre.appendChild(zeroWidthElement(cm.display.measure)); | 1542 } |
| 1156 removeChildrenAndAdd(cm.display.measure, pre); | 1543 found = measureCharInner(cm, prepared, ch, bias); |
| 1157 return getRect(end).right - getRect(cm.display.lineDiv).left; | 1544 if (!found.bogus) prepared.cache[key] = found; |
| 1545 } |
| 1546 return {left: found.left, right: found.right, top: found.top, bottom: found.
bottom}; |
| 1547 } |
| 1548 |
| 1549 var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; |
| 1550 |
| 1551 function measureCharInner(cm, prepared, ch, bias) { |
| 1552 var map = prepared.map; |
| 1553 |
| 1554 var node, start, end, collapse; |
| 1555 // First, search the line map for the text node corresponding to, |
| 1556 // or closest to, the target character. |
| 1557 for (var i = 0; i < map.length; i += 3) { |
| 1558 var mStart = map[i], mEnd = map[i + 1]; |
| 1559 if (ch < mStart) { |
| 1560 start = 0; end = 1; |
| 1561 collapse = "left"; |
| 1562 } else if (ch < mEnd) { |
| 1563 start = ch - mStart; |
| 1564 end = start + 1; |
| 1565 } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { |
| 1566 end = mEnd - mStart; |
| 1567 start = end - 1; |
| 1568 if (ch >= mEnd) collapse = "right"; |
| 1569 } |
| 1570 if (start != null) { |
| 1571 node = map[i + 2]; |
| 1572 if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) |
| 1573 collapse = bias; |
| 1574 if (bias == "left" && start == 0) |
| 1575 while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { |
| 1576 node = map[(i -= 3) + 2]; |
| 1577 collapse = "left"; |
| 1578 } |
| 1579 if (bias == "right" && start == mEnd - mStart) |
| 1580 while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].i
nsertLeft) { |
| 1581 node = map[(i += 3) + 2]; |
| 1582 collapse = "right"; |
| 1583 } |
| 1584 break; |
| 1585 } |
| 1586 } |
| 1587 |
| 1588 var rect; |
| 1589 if (node.nodeType == 3) { // If it is a text node, use a range to retrieve t
he coordinates. |
| 1590 while (start && isExtendingChar(prepared.line.text.charAt(mStart + start))
) --start; |
| 1591 while (mStart + end < mEnd && isExtendingChar(prepared.line.text.charAt(mS
tart + end))) ++end; |
| 1592 if (ie_upto8 && start == 0 && end == mEnd - mStart) { |
| 1593 rect = node.parentNode.getBoundingClientRect(); |
| 1594 } else if (ie && cm.options.lineWrapping) { |
| 1595 var rects = range(node, start, end).getClientRects(); |
| 1596 if (rects.length) |
| 1597 rect = rects[bias == "right" ? rects.length - 1 : 0]; |
| 1598 else |
| 1599 rect = nullRect; |
| 1600 } else { |
| 1601 rect = range(node, start, end).getBoundingClientRect(); |
| 1602 } |
| 1603 } else { // If it is a widget, simply get the box for the whole widget. |
| 1604 if (start > 0) collapse = bias = "right"; |
| 1605 var rects; |
| 1606 if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) |
| 1607 rect = rects[bias == "right" ? rects.length - 1 : 0]; |
| 1608 else |
| 1609 rect = node.getBoundingClientRect(); |
| 1610 } |
| 1611 if (ie_upto8 && !start && (!rect || !rect.left && !rect.right)) { |
| 1612 var rSpan = node.parentNode.getClientRects()[0]; |
| 1613 if (rSpan) |
| 1614 rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top
: rSpan.top, bottom: rSpan.bottom}; |
| 1615 else |
| 1616 rect = nullRect; |
| 1617 } |
| 1618 |
| 1619 var top, bot = (rect.bottom + rect.top) / 2 - prepared.rect.top; |
| 1620 var heights = prepared.view.measure.heights; |
| 1621 for (var i = 0; i < heights.length - 1; i++) |
| 1622 if (bot < heights[i]) break; |
| 1623 top = i ? heights[i - 1] : 0; bot = heights[i]; |
| 1624 var result = {left: (collapse == "right" ? rect.right : rect.left) - prepare
d.rect.left, |
| 1625 right: (collapse == "left" ? rect.left : rect.right) - prepare
d.rect.left, |
| 1626 top: top, bottom: bot}; |
| 1627 if (!rect.left && !rect.right) result.bogus = true; |
| 1628 return result; |
| 1629 } |
| 1630 |
| 1631 function clearLineMeasurementCacheFor(lineView) { |
| 1632 if (lineView.measure) { |
| 1633 lineView.measure.cache = {}; |
| 1634 lineView.measure.heights = null; |
| 1635 if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) |
| 1636 lineView.measure.caches[i] = {}; |
| 1637 } |
| 1638 } |
| 1639 |
| 1640 function clearLineMeasurementCache(cm) { |
| 1641 cm.display.externalMeasure = null; |
| 1642 removeChildren(cm.display.lineMeasure); |
| 1643 for (var i = 0; i < cm.display.view.length; i++) |
| 1644 clearLineMeasurementCacheFor(cm.display.view[i]); |
| 1158 } | 1645 } |
| 1159 | 1646 |
| 1160 function clearCaches(cm) { | 1647 function clearCaches(cm) { |
| 1161 cm.display.measureLineCache.length = cm.display.measureLineCachePos = 0; | 1648 clearLineMeasurementCache(cm); |
| 1162 cm.display.cachedCharWidth = cm.display.cachedTextHeight = null; | 1649 cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cached
PaddingH = null; |
| 1163 if (!cm.options.lineWrapping) cm.display.maxLineChanged = true; | 1650 if (!cm.options.lineWrapping) cm.display.maxLineChanged = true; |
| 1164 cm.display.lineNumChars = null; | 1651 cm.display.lineNumChars = null; |
| 1165 } | 1652 } |
| 1166 | 1653 |
| 1167 function pageScrollX() { return window.pageXOffset || (document.documentElemen
t || document.body).scrollLeft; } | 1654 function pageScrollX() { return window.pageXOffset || (document.documentElemen
t || document.body).scrollLeft; } |
| 1168 function pageScrollY() { return window.pageYOffset || (document.documentElemen
t || document.body).scrollTop; } | 1655 function pageScrollY() { return window.pageYOffset || (document.documentElemen
t || document.body).scrollTop; } |
| 1169 | 1656 |
| 1170 // Context is one of "line", "div" (display.lineDiv), "local"/null (editor), o
r "page" | 1657 // Converts a {top, bottom, left, right} box from line-local |
| 1658 // coordinates into another coordinate system. Context may be one of |
| 1659 // "line", "div" (display.lineDiv), "local"/null (editor), or "page". |
| 1171 function intoCoordSystem(cm, lineObj, rect, context) { | 1660 function intoCoordSystem(cm, lineObj, rect, context) { |
| 1172 if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (li
neObj.widgets[i].above) { | 1661 if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (li
neObj.widgets[i].above) { |
| 1173 var size = widgetHeight(lineObj.widgets[i]); | 1662 var size = widgetHeight(lineObj.widgets[i]); |
| 1174 rect.top += size; rect.bottom += size; | 1663 rect.top += size; rect.bottom += size; |
| 1175 } | 1664 } |
| 1176 if (context == "line") return rect; | 1665 if (context == "line") return rect; |
| 1177 if (!context) context = "local"; | 1666 if (!context) context = "local"; |
| 1178 var yOff = heightAtLine(cm, lineObj); | 1667 var yOff = heightAtLine(lineObj); |
| 1179 if (context == "local") yOff += paddingTop(cm.display); | 1668 if (context == "local") yOff += paddingTop(cm.display); |
| 1180 else yOff -= cm.display.viewOffset; | 1669 else yOff -= cm.display.viewOffset; |
| 1181 if (context == "page" || context == "window") { | 1670 if (context == "page" || context == "window") { |
| 1182 var lOff = getRect(cm.display.lineSpace); | 1671 var lOff = cm.display.lineSpace.getBoundingClientRect(); |
| 1183 yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); | 1672 yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); |
| 1184 var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); | 1673 var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); |
| 1185 rect.left += xOff; rect.right += xOff; | 1674 rect.left += xOff; rect.right += xOff; |
| 1186 } | 1675 } |
| 1187 rect.top += yOff; rect.bottom += yOff; | 1676 rect.top += yOff; rect.bottom += yOff; |
| 1188 return rect; | 1677 return rect; |
| 1189 } | 1678 } |
| 1190 | 1679 |
| 1191 // Context may be "window", "page", "div", or "local"/null | 1680 // Coverts a box from "div" coords to another coordinate system. |
| 1192 // Result is in "div" coords | 1681 // Context may be "window", "page", "div", or "local"/null. |
| 1193 function fromCoordSystem(cm, coords, context) { | 1682 function fromCoordSystem(cm, coords, context) { |
| 1194 if (context == "div") return coords; | 1683 if (context == "div") return coords; |
| 1195 var left = coords.left, top = coords.top; | 1684 var left = coords.left, top = coords.top; |
| 1196 // First move into "page" coordinate system | 1685 // First move into "page" coordinate system |
| 1197 if (context == "page") { | 1686 if (context == "page") { |
| 1198 left -= pageScrollX(); | 1687 left -= pageScrollX(); |
| 1199 top -= pageScrollY(); | 1688 top -= pageScrollY(); |
| 1200 } else if (context == "local" || !context) { | 1689 } else if (context == "local" || !context) { |
| 1201 var localBox = getRect(cm.display.sizer); | 1690 var localBox = cm.display.sizer.getBoundingClientRect(); |
| 1202 left += localBox.left; | 1691 left += localBox.left; |
| 1203 top += localBox.top; | 1692 top += localBox.top; |
| 1204 } | 1693 } |
| 1205 | 1694 |
| 1206 var lineSpaceBox = getRect(cm.display.lineSpace); | 1695 var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); |
| 1207 return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}; | 1696 return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}; |
| 1208 } | 1697 } |
| 1209 | 1698 |
| 1210 function charCoords(cm, pos, context, lineObj, bias) { | 1699 function charCoords(cm, pos, context, lineObj, bias) { |
| 1211 if (!lineObj) lineObj = getLine(cm.doc, pos.line); | 1700 if (!lineObj) lineObj = getLine(cm.doc, pos.line); |
| 1212 return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, null, b
ias), context); | 1701 return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias),
context); |
| 1213 } | 1702 } |
| 1214 | 1703 |
| 1215 function cursorCoords(cm, pos, context, lineObj, measurement) { | 1704 // Returns a box for a given cursor position, which may have an |
| 1705 // 'other' property containing the position of the secondary cursor |
| 1706 // on a bidi boundary. |
| 1707 function cursorCoords(cm, pos, context, lineObj, preparedMeasure) { |
| 1216 lineObj = lineObj || getLine(cm.doc, pos.line); | 1708 lineObj = lineObj || getLine(cm.doc, pos.line); |
| 1217 if (!measurement) measurement = measureLine(cm, lineObj); | 1709 if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj); |
| 1218 function get(ch, right) { | 1710 function get(ch, right) { |
| 1219 var m = measureChar(cm, lineObj, ch, measurement, right ? "right" : "left"
); | 1711 var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "le
ft"); |
| 1220 if (right) m.left = m.right; else m.right = m.left; | 1712 if (right) m.left = m.right; else m.right = m.left; |
| 1221 return intoCoordSystem(cm, lineObj, m, context); | 1713 return intoCoordSystem(cm, lineObj, m, context); |
| 1222 } | 1714 } |
| 1223 function getBidi(ch, partPos) { | 1715 function getBidi(ch, partPos) { |
| 1224 var part = order[partPos], right = part.level % 2; | 1716 var part = order[partPos], right = part.level % 2; |
| 1225 if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].lev
el) { | 1717 if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].lev
el) { |
| 1226 part = order[--partPos]; | 1718 part = order[--partPos]; |
| 1227 ch = bidiRight(part) - (part.level % 2 ? 0 : 1); | 1719 ch = bidiRight(part) - (part.level % 2 ? 0 : 1); |
| 1228 right = true; | 1720 right = true; |
| 1229 } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.lev
el < order[partPos + 1].level) { | 1721 } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.lev
el < order[partPos + 1].level) { |
| 1230 part = order[++partPos]; | 1722 part = order[++partPos]; |
| 1231 ch = bidiLeft(part) - part.level % 2; | 1723 ch = bidiLeft(part) - part.level % 2; |
| 1232 right = false; | 1724 right = false; |
| 1233 } | 1725 } |
| 1234 if (right && ch == part.to && ch > part.from) return get(ch - 1); | 1726 if (right && ch == part.to && ch > part.from) return get(ch - 1); |
| 1235 return get(ch, right); | 1727 return get(ch, right); |
| 1236 } | 1728 } |
| 1237 var order = getOrder(lineObj), ch = pos.ch; | 1729 var order = getOrder(lineObj), ch = pos.ch; |
| 1238 if (!order) return get(ch); | 1730 if (!order) return get(ch); |
| 1239 var partPos = getBidiPartAt(order, ch); | 1731 var partPos = getBidiPartAt(order, ch); |
| 1240 var val = getBidi(ch, partPos); | 1732 var val = getBidi(ch, partPos); |
| 1241 if (bidiOther != null) val.other = getBidi(ch, bidiOther); | 1733 if (bidiOther != null) val.other = getBidi(ch, bidiOther); |
| 1242 return val; | 1734 return val; |
| 1243 } | 1735 } |
| 1244 | 1736 |
| 1737 // Used to cheaply estimate the coordinates for a position. Used for |
| 1738 // intermediate scroll updates. |
| 1739 function estimateCoords(cm, pos) { |
| 1740 var left = 0, pos = clipPos(cm.doc, pos); |
| 1741 if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch; |
| 1742 var lineObj = getLine(cm.doc, pos.line); |
| 1743 var top = heightAtLine(lineObj) + paddingTop(cm.display); |
| 1744 return {left: left, right: left, top: top, bottom: top + lineObj.height}; |
| 1745 } |
| 1746 |
| 1747 // Positions returned by coordsChar contain some extra information. |
| 1748 // xRel is the relative x position of the input coordinates compared |
| 1749 // to the found position (so xRel > 0 means the coordinates are to |
| 1750 // the right of the character position, for example). When outside |
| 1751 // is true, that means the coordinates lie outside the line's |
| 1752 // vertical range. |
| 1245 function PosWithInfo(line, ch, outside, xRel) { | 1753 function PosWithInfo(line, ch, outside, xRel) { |
| 1246 var pos = new Pos(line, ch); | 1754 var pos = Pos(line, ch); |
| 1247 pos.xRel = xRel; | 1755 pos.xRel = xRel; |
| 1248 if (outside) pos.outside = true; | 1756 if (outside) pos.outside = true; |
| 1249 return pos; | 1757 return pos; |
| 1250 } | 1758 } |
| 1251 | 1759 |
| 1252 // Coords must be lineSpace-local | 1760 // Compute the character position closest to the given coordinates. |
| 1761 // Input must be lineSpace-local ("div" coordinate system). |
| 1253 function coordsChar(cm, x, y) { | 1762 function coordsChar(cm, x, y) { |
| 1254 var doc = cm.doc; | 1763 var doc = cm.doc; |
| 1255 y += cm.display.viewOffset; | 1764 y += cm.display.viewOffset; |
| 1256 if (y < 0) return PosWithInfo(doc.first, 0, true, -1); | 1765 if (y < 0) return PosWithInfo(doc.first, 0, true, -1); |
| 1257 var lineNo = lineAtHeight(doc, y), last = doc.first + doc.size - 1; | 1766 var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; |
| 1258 if (lineNo > last) | 1767 if (lineN > last) |
| 1259 return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.lengt
h, true, 1); | 1768 return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.lengt
h, true, 1); |
| 1260 if (x < 0) x = 0; | 1769 if (x < 0) x = 0; |
| 1261 | 1770 |
| 1771 var lineObj = getLine(doc, lineN); |
| 1262 for (;;) { | 1772 for (;;) { |
| 1263 var lineObj = getLine(doc, lineNo); | 1773 var found = coordsCharInner(cm, lineObj, lineN, x, y); |
| 1264 var found = coordsCharInner(cm, lineObj, lineNo, x, y); | |
| 1265 var merged = collapsedSpanAtEnd(lineObj); | 1774 var merged = collapsedSpanAtEnd(lineObj); |
| 1266 var mergedPos = merged && merged.find(); | 1775 var mergedPos = merged && merged.find(0, true); |
| 1267 if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.
ch && found.xRel > 0)) | 1776 if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.
ch && found.xRel > 0)) |
| 1268 lineNo = mergedPos.to.line; | 1777 lineN = lineNo(lineObj = mergedPos.to.line); |
| 1269 else | 1778 else |
| 1270 return found; | 1779 return found; |
| 1271 } | 1780 } |
| 1272 } | 1781 } |
| 1273 | 1782 |
| 1274 function coordsCharInner(cm, lineObj, lineNo, x, y) { | 1783 function coordsCharInner(cm, lineObj, lineNo, x, y) { |
| 1275 var innerOff = y - heightAtLine(cm, lineObj); | 1784 var innerOff = y - heightAtLine(lineObj); |
| 1276 var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth; | 1785 var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth; |
| 1277 var measurement = measureLine(cm, lineObj); | 1786 var preparedMeasure = prepareMeasureForLine(cm, lineObj); |
| 1278 | 1787 |
| 1279 function getX(ch) { | 1788 function getX(ch) { |
| 1280 var sp = cursorCoords(cm, Pos(lineNo, ch), "line", | 1789 var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasur
e); |
| 1281 lineObj, measurement); | |
| 1282 wrongLine = true; | 1790 wrongLine = true; |
| 1283 if (innerOff > sp.bottom) return sp.left - adjust; | 1791 if (innerOff > sp.bottom) return sp.left - adjust; |
| 1284 else if (innerOff < sp.top) return sp.left + adjust; | 1792 else if (innerOff < sp.top) return sp.left + adjust; |
| 1285 else wrongLine = false; | 1793 else wrongLine = false; |
| 1286 return sp.left; | 1794 return sp.left; |
| 1287 } | 1795 } |
| 1288 | 1796 |
| 1289 var bidi = getOrder(lineObj), dist = lineObj.text.length; | 1797 var bidi = getOrder(lineObj), dist = lineObj.text.length; |
| 1290 var from = lineLeft(lineObj), to = lineRight(lineObj); | 1798 var from = lineLeft(lineObj), to = lineRight(lineObj); |
| 1291 var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside =
wrongLine; | 1799 var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside =
wrongLine; |
| 1292 | 1800 |
| 1293 if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1); | 1801 if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1); |
| 1294 // Do a binary search between these bounds. | 1802 // Do a binary search between these bounds. |
| 1295 for (;;) { | 1803 for (;;) { |
| 1296 if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from
<= 1) { | 1804 if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from
<= 1) { |
| 1297 var ch = x < fromX || x - fromX <= toX - x ? from : to; | 1805 var ch = x < fromX || x - fromX <= toX - x ? from : to; |
| 1298 var xDiff = x - (ch == from ? fromX : toX); | 1806 var xDiff = x - (ch == from ? fromX : toX); |
| 1299 while (isExtendingChar(lineObj.text.charAt(ch))) ++ch; | 1807 while (isExtendingChar(lineObj.text.charAt(ch))) ++ch; |
| 1300 var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside, | 1808 var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside, |
| 1301 xDiff < 0 ? -1 : xDiff ? 1 : 0); | 1809 xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0); |
| 1302 return pos; | 1810 return pos; |
| 1303 } | 1811 } |
| 1304 var step = Math.ceil(dist / 2), middle = from + step; | 1812 var step = Math.ceil(dist / 2), middle = from + step; |
| 1305 if (bidi) { | 1813 if (bidi) { |
| 1306 middle = from; | 1814 middle = from; |
| 1307 for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1)
; | 1815 for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1)
; |
| 1308 } | 1816 } |
| 1309 var middleX = getX(middle); | 1817 var middleX = getX(middle); |
| 1310 if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) t
oX += 1000; dist = step;} | 1818 if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) t
oX += 1000; dist = step;} |
| 1311 else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= ste
p;} | 1819 else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= ste
p;} |
| 1312 } | 1820 } |
| 1313 } | 1821 } |
| 1314 | 1822 |
| 1315 var measureText; | 1823 var measureText; |
| 1824 // Compute the default text height. |
| 1316 function textHeight(display) { | 1825 function textHeight(display) { |
| 1317 if (display.cachedTextHeight != null) return display.cachedTextHeight; | 1826 if (display.cachedTextHeight != null) return display.cachedTextHeight; |
| 1318 if (measureText == null) { | 1827 if (measureText == null) { |
| 1319 measureText = elt("pre"); | 1828 measureText = elt("pre"); |
| 1320 // Measure a bunch of lines, for browsers that compute | 1829 // Measure a bunch of lines, for browsers that compute |
| 1321 // fractional heights. | 1830 // fractional heights. |
| 1322 for (var i = 0; i < 49; ++i) { | 1831 for (var i = 0; i < 49; ++i) { |
| 1323 measureText.appendChild(document.createTextNode("x")); | 1832 measureText.appendChild(document.createTextNode("x")); |
| 1324 measureText.appendChild(elt("br")); | 1833 measureText.appendChild(elt("br")); |
| 1325 } | 1834 } |
| 1326 measureText.appendChild(document.createTextNode("x")); | 1835 measureText.appendChild(document.createTextNode("x")); |
| 1327 } | 1836 } |
| 1328 removeChildrenAndAdd(display.measure, measureText); | 1837 removeChildrenAndAdd(display.measure, measureText); |
| 1329 var height = measureText.offsetHeight / 50; | 1838 var height = measureText.offsetHeight / 50; |
| 1330 if (height > 3) display.cachedTextHeight = height; | 1839 if (height > 3) display.cachedTextHeight = height; |
| 1331 removeChildren(display.measure); | 1840 removeChildren(display.measure); |
| 1332 return height || 1; | 1841 return height || 1; |
| 1333 } | 1842 } |
| 1334 | 1843 |
| 1844 // Compute the default character width. |
| 1335 function charWidth(display) { | 1845 function charWidth(display) { |
| 1336 if (display.cachedCharWidth != null) return display.cachedCharWidth; | 1846 if (display.cachedCharWidth != null) return display.cachedCharWidth; |
| 1337 var anchor = elt("span", "x"); | 1847 var anchor = elt("span", "xxxxxxxxxx"); |
| 1338 var pre = elt("pre", [anchor]); | 1848 var pre = elt("pre", [anchor]); |
| 1339 removeChildrenAndAdd(display.measure, pre); | 1849 removeChildrenAndAdd(display.measure, pre); |
| 1340 var width = anchor.offsetWidth; | 1850 var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left)
/ 10; |
| 1341 if (width > 2) display.cachedCharWidth = width; | 1851 if (width > 2) display.cachedCharWidth = width; |
| 1342 return width || 10; | 1852 return width || 10; |
| 1343 } | 1853 } |
| 1344 | 1854 |
| 1345 // OPERATIONS | 1855 // OPERATIONS |
| 1346 | 1856 |
| 1347 // Operations are used to wrap changes in such a way that each | 1857 // Operations are used to wrap a series of changes to the editor |
| 1348 // change won't have to update the cursor and display (which would | 1858 // state in such a way that each change won't have to update the |
| 1349 // be awkward, slow, and error-prone), but instead updates are | 1859 // cursor and display (which would be awkward, slow, and |
| 1350 // batched and then all combined and executed at once. | 1860 // error-prone). Instead, display updates are batched and then all |
| 1861 // combined and executed at once. |
| 1351 | 1862 |
| 1352 var nextOpId = 0; | 1863 var nextOpId = 0; |
| 1864 // Start a new operation. |
| 1353 function startOperation(cm) { | 1865 function startOperation(cm) { |
| 1354 cm.curOp = { | 1866 cm.curOp = { |
| 1355 // An array of ranges of lines that have to be updated. See | 1867 viewChanged: false, // Flag that indicates that lines might need to b
e redrawn |
| 1356 // updateDisplay. | 1868 startHeight: cm.doc.height, // Used to detect need to update scrollbar |
| 1357 changes: [], | 1869 forceUpdate: false, // Used to force a redraw |
| 1358 forceUpdate: false, | 1870 updateInput: null, // Whether to reset the input textarea |
| 1359 updateInput: null, | 1871 typing: false, // Whether this reset should be careful to leave
existing text (for compositing) |
| 1360 userSelChange: null, | 1872 changeObjs: null, // Accumulated changes, for firing change events |
| 1361 textChanged: null, | 1873 cursorActivity: false, // Whether to fire a cursorActivity event |
| 1362 selectionChanged: false, | 1874 selectionChanged: false, // Whether the selection needs to be redrawn |
| 1363 cursorActivity: false, | 1875 updateMaxLine: false, // Set when the widest line needs to be determine
d anew |
| 1364 updateMaxLine: false, | 1876 scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pu
shed to DOM yet |
| 1365 updateScrollPos: false, | 1877 scrollToPos: null, // Used to scroll to a specific position |
| 1366 id: ++nextOpId | 1878 id: ++nextOpId // Unique ID |
| 1367 }; | 1879 }; |
| 1368 if (!delayedCallbackDepth++) delayedCallbacks = []; | 1880 if (!delayedCallbackDepth++) delayedCallbacks = []; |
| 1369 } | 1881 } |
| 1370 | 1882 |
| 1883 // Finish an operation, updating the display and signalling delayed events |
| 1371 function endOperation(cm) { | 1884 function endOperation(cm) { |
| 1372 var op = cm.curOp, doc = cm.doc, display = cm.display; | 1885 var op = cm.curOp, doc = cm.doc, display = cm.display; |
| 1373 cm.curOp = null; | 1886 cm.curOp = null; |
| 1374 | 1887 |
| 1375 if (op.updateMaxLine) computeMaxLength(cm); | 1888 if (op.updateMaxLine) findMaxLine(cm); |
| 1376 if (display.maxLineChanged && !cm.options.lineWrapping && display.maxLine) { | 1889 |
| 1377 var width = measureLineWidth(cm, display.maxLine); | 1890 // If it looks like an update might be needed, call updateDisplay |
| 1378 display.sizer.style.minWidth = Math.max(0, width + 3 + scrollerCutOff) + "
px"; | 1891 if (op.viewChanged || op.forceUpdate || op.scrollTop != null || |
| 1379 display.maxLineChanged = false; | 1892 op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || |
| 1380 var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + display.sizer.o
ffsetWidth - display.scroller.clientWidth); | 1893 op.scrollToPos.to.line >= display.viewTo) || |
| 1381 if (maxScrollLeft < doc.scrollLeft && !op.updateScrollPos) | 1894 display.maxLineChanged && cm.options.lineWrapping) { |
| 1382 setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft),
true); | 1895 var updated = updateDisplay(cm, {top: op.scrollTop, ensure: op.scrollToPos
}, op.forceUpdate); |
| 1383 } | |
| 1384 var newScrollPos, updated; | |
| 1385 if (op.updateScrollPos) { | |
| 1386 newScrollPos = op.updateScrollPos; | |
| 1387 } else if (op.selectionChanged && display.scroller.clientHeight) { // don't
rescroll if not visible | |
| 1388 var coords = cursorCoords(cm, doc.sel.head); | |
| 1389 newScrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left
, coords.bottom); | |
| 1390 } | |
| 1391 if (op.changes.length || op.forceUpdate || newScrollPos && newScrollPos.scro
llTop != null) { | |
| 1392 updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrol
lTop, op.forceUpdate); | |
| 1393 if (cm.display.scroller.offsetHeight) cm.doc.scrollTop = cm.display.scroll
er.scrollTop; | 1896 if (cm.display.scroller.offsetHeight) cm.doc.scrollTop = cm.display.scroll
er.scrollTop; |
| 1394 } | 1897 } |
| 1898 // If no update was run, but the selection changed, redraw that. |
| 1395 if (!updated && op.selectionChanged) updateSelection(cm); | 1899 if (!updated && op.selectionChanged) updateSelection(cm); |
| 1396 if (op.updateScrollPos) { | 1900 if (!updated && op.startHeight != cm.doc.height) updateScrollbars(cm); |
| 1397 var top = Math.max(0, Math.min(display.scroller.scrollHeight - display.scr
oller.clientHeight, newScrollPos.scrollTop)); | 1901 |
| 1398 var left = Math.max(0, Math.min(display.scroller.scrollWidth - display.scr
oller.clientWidth, newScrollPos.scrollLeft)); | 1902 // Propagate the scroll position to the actual DOM scroller |
| 1903 if (op.scrollTop != null && display.scroller.scrollTop != op.scrollTop) { |
| 1904 var top = Math.max(0, Math.min(display.scroller.scrollHeight - display.scr
oller.clientHeight, op.scrollTop)); |
| 1399 display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop
= top; | 1905 display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop
= top; |
| 1906 } |
| 1907 if (op.scrollLeft != null && display.scroller.scrollLeft != op.scrollLeft) { |
| 1908 var left = Math.max(0, Math.min(display.scroller.scrollWidth - display.scr
oller.clientWidth, op.scrollLeft)); |
| 1400 display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLe
ft = left; | 1909 display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLe
ft = left; |
| 1401 alignHorizontally(cm); | 1910 alignHorizontally(cm); |
| 1402 if (op.scrollToPos) | |
| 1403 scrollPosIntoView(cm, clipPos(cm.doc, op.scrollToPos.from), | |
| 1404 clipPos(cm.doc, op.scrollToPos.to), op.scrollToPos.mar
gin); | |
| 1405 } else if (newScrollPos) { | |
| 1406 scrollCursorIntoView(cm); | |
| 1407 } | 1911 } |
| 1912 // If we need to scroll a specific position into view, do so. |
| 1913 if (op.scrollToPos) { |
| 1914 var coords = scrollPosIntoView(cm, clipPos(cm.doc, op.scrollToPos.from), |
| 1915 clipPos(cm.doc, op.scrollToPos.to), op.scro
llToPos.margin); |
| 1916 if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coo
rds); |
| 1917 } |
| 1918 |
| 1408 if (op.selectionChanged) restartBlink(cm); | 1919 if (op.selectionChanged) restartBlink(cm); |
| 1409 | 1920 |
| 1410 if (cm.state.focused && op.updateInput) | 1921 if (cm.state.focused && op.updateInput) |
| 1411 resetInput(cm, op.userSelChange); | 1922 resetInput(cm, op.typing); |
| 1412 | 1923 |
| 1924 // Fire events for markers that are hidden/unidden by editing or |
| 1925 // undoing |
| 1413 var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; | 1926 var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; |
| 1414 if (hidden) for (var i = 0; i < hidden.length; ++i) | 1927 if (hidden) for (var i = 0; i < hidden.length; ++i) |
| 1415 if (!hidden[i].lines.length) signal(hidden[i], "hide"); | 1928 if (!hidden[i].lines.length) signal(hidden[i], "hide"); |
| 1416 if (unhidden) for (var i = 0; i < unhidden.length; ++i) | 1929 if (unhidden) for (var i = 0; i < unhidden.length; ++i) |
| 1417 if (unhidden[i].lines.length) signal(unhidden[i], "unhide"); | 1930 if (unhidden[i].lines.length) signal(unhidden[i], "unhide"); |
| 1418 | 1931 |
| 1419 var delayed; | 1932 var delayed; |
| 1420 if (!--delayedCallbackDepth) { | 1933 if (!--delayedCallbackDepth) { |
| 1421 delayed = delayedCallbacks; | 1934 delayed = delayedCallbacks; |
| 1422 delayedCallbacks = null; | 1935 delayedCallbacks = null; |
| 1423 } | 1936 } |
| 1424 if (op.textChanged) | 1937 // Fire change events, and delayed event handlers |
| 1425 signal(cm, "change", cm, op.textChanged); | 1938 if (op.changeObjs) { |
| 1939 for (var i = 0; i < op.changeObjs.length; i++) |
| 1940 signal(cm, "change", cm, op.changeObjs[i]); |
| 1941 signal(cm, "changes", cm, op.changeObjs); |
| 1942 } |
| 1426 if (op.cursorActivity) signal(cm, "cursorActivity", cm); | 1943 if (op.cursorActivity) signal(cm, "cursorActivity", cm); |
| 1427 if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i](); | 1944 if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i](); |
| 1428 } | 1945 } |
| 1429 | 1946 |
| 1947 // Run the given function in an operation |
| 1948 function runInOp(cm, f) { |
| 1949 if (cm.curOp) return f(); |
| 1950 startOperation(cm); |
| 1951 try { return f(); } |
| 1952 finally { endOperation(cm); } |
| 1953 } |
| 1430 // Wraps a function in an operation. Returns the wrapped function. | 1954 // Wraps a function in an operation. Returns the wrapped function. |
| 1431 function operation(cm1, f) { | 1955 function operation(cm, f) { |
| 1432 return function() { | 1956 return function() { |
| 1433 var cm = cm1 || this, withOp = !cm.curOp; | 1957 if (cm.curOp) return f.apply(cm, arguments); |
| 1434 if (withOp) startOperation(cm); | 1958 startOperation(cm); |
| 1435 try { var result = f.apply(cm, arguments); } | 1959 try { return f.apply(cm, arguments); } |
| 1436 finally { if (withOp) endOperation(cm); } | 1960 finally { endOperation(cm); } |
| 1437 return result; | |
| 1438 }; | 1961 }; |
| 1439 } | 1962 } |
| 1440 function docOperation(f) { | 1963 // Used to add methods to editor and doc instances, wrapping them in |
| 1964 // operations. |
| 1965 function methodOp(f) { |
| 1441 return function() { | 1966 return function() { |
| 1442 var withOp = this.cm && !this.cm.curOp, result; | 1967 if (this.curOp) return f.apply(this, arguments); |
| 1443 if (withOp) startOperation(this.cm); | 1968 startOperation(this); |
| 1444 try { result = f.apply(this, arguments); } | 1969 try { return f.apply(this, arguments); } |
| 1445 finally { if (withOp) endOperation(this.cm); } | 1970 finally { endOperation(this); } |
| 1446 return result; | |
| 1447 }; | 1971 }; |
| 1448 } | 1972 } |
| 1449 function runInOp(cm, f) { | 1973 function docMethodOp(f) { |
| 1450 var withOp = !cm.curOp, result; | 1974 return function() { |
| 1451 if (withOp) startOperation(cm); | 1975 var cm = this.cm; |
| 1452 try { result = f(); } | 1976 if (!cm || cm.curOp) return f.apply(this, arguments); |
| 1453 finally { if (withOp) endOperation(cm); } | 1977 startOperation(cm); |
| 1454 return result; | 1978 try { return f.apply(this, arguments); } |
| 1455 } | 1979 finally { endOperation(cm); } |
| 1456 | 1980 }; |
| 1981 } |
| 1982 |
| 1983 // VIEW TRACKING |
| 1984 |
| 1985 // These objects are used to represent the visible (currently drawn) |
| 1986 // part of the document. A LineView may correspond to multiple |
| 1987 // logical lines, if those are connected by collapsed ranges. |
| 1988 function LineView(doc, line, lineN) { |
| 1989 // The starting line |
| 1990 this.line = line; |
| 1991 // Continuing lines, if any |
| 1992 this.rest = visualLineContinued(line); |
| 1993 // Number of logical lines in this visual line |
| 1994 this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; |
| 1995 this.node = this.text = null; |
| 1996 this.hidden = lineIsHidden(doc, line); |
| 1997 } |
| 1998 |
| 1999 // Create a range of LineView objects for the given lines. |
| 2000 function buildViewArray(cm, from, to) { |
| 2001 var array = [], nextPos; |
| 2002 for (var pos = from; pos < to; pos = nextPos) { |
| 2003 var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); |
| 2004 nextPos = pos + view.size; |
| 2005 array.push(view); |
| 2006 } |
| 2007 return array; |
| 2008 } |
| 2009 |
| 2010 // Updates the display.view data structure for a given change to the |
| 2011 // document. From and to are in pre-change coordinates. Lendiff is |
| 2012 // the amount of lines added or subtracted by the change. This is |
| 2013 // used for changes that span multiple lines, or change the way |
| 2014 // lines are divided into visual lines. regLineChange (below) |
| 2015 // registers single-line changes. |
| 1457 function regChange(cm, from, to, lendiff) { | 2016 function regChange(cm, from, to, lendiff) { |
| 1458 if (from == null) from = cm.doc.first; | 2017 if (from == null) from = cm.doc.first; |
| 1459 if (to == null) to = cm.doc.first + cm.doc.size; | 2018 if (to == null) to = cm.doc.first + cm.doc.size; |
| 1460 cm.curOp.changes.push({from: from, to: to, diff: lendiff}); | 2019 if (!lendiff) lendiff = 0; |
| 2020 |
| 2021 var display = cm.display; |
| 2022 if (lendiff && to < display.viewTo && |
| 2023 (display.updateLineNumbers == null || display.updateLineNumbers > from)) |
| 2024 display.updateLineNumbers = from; |
| 2025 |
| 2026 cm.curOp.viewChanged = true; |
| 2027 |
| 2028 if (from >= display.viewTo) { // Change after |
| 2029 if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) |
| 2030 resetView(cm); |
| 2031 } else if (to <= display.viewFrom) { // Change before |
| 2032 if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.v
iewFrom) { |
| 2033 resetView(cm); |
| 2034 } else { |
| 2035 display.viewFrom += lendiff; |
| 2036 display.viewTo += lendiff; |
| 2037 } |
| 2038 } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overl
ap |
| 2039 resetView(cm); |
| 2040 } else if (from <= display.viewFrom) { // Top overlap |
| 2041 var cut = viewCuttingPoint(cm, to, to + lendiff, 1); |
| 2042 if (cut) { |
| 2043 display.view = display.view.slice(cut.index); |
| 2044 display.viewFrom = cut.lineN; |
| 2045 display.viewTo += lendiff; |
| 2046 } else { |
| 2047 resetView(cm); |
| 2048 } |
| 2049 } else if (to >= display.viewTo) { // Bottom overlap |
| 2050 var cut = viewCuttingPoint(cm, from, from, -1); |
| 2051 if (cut) { |
| 2052 display.view = display.view.slice(0, cut.index); |
| 2053 display.viewTo = cut.lineN; |
| 2054 } else { |
| 2055 resetView(cm); |
| 2056 } |
| 2057 } else { // Gap in the middle |
| 2058 var cutTop = viewCuttingPoint(cm, from, from, -1); |
| 2059 var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); |
| 2060 if (cutTop && cutBot) { |
| 2061 display.view = display.view.slice(0, cutTop.index) |
| 2062 .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) |
| 2063 .concat(display.view.slice(cutBot.index)); |
| 2064 display.viewTo += lendiff; |
| 2065 } else { |
| 2066 resetView(cm); |
| 2067 } |
| 2068 } |
| 2069 |
| 2070 var ext = display.externalMeasured; |
| 2071 if (ext) { |
| 2072 if (to < ext.lineN) |
| 2073 ext.lineN += lendiff; |
| 2074 else if (from < ext.lineN + ext.size) |
| 2075 display.externalMeasured = null; |
| 2076 } |
| 2077 } |
| 2078 |
| 2079 // Register a change to a single line. Type must be one of "text", |
| 2080 // "gutter", "class", "widget" |
| 2081 function regLineChange(cm, line, type) { |
| 2082 cm.curOp.viewChanged = true; |
| 2083 var display = cm.display, ext = cm.display.externalMeasured; |
| 2084 if (ext && line >= ext.lineN && line < ext.lineN + ext.size) |
| 2085 display.externalMeasured = null; |
| 2086 |
| 2087 if (line < display.viewFrom || line >= display.viewTo) return; |
| 2088 var lineView = display.view[findViewIndex(cm, line)]; |
| 2089 if (lineView.node == null) return; |
| 2090 var arr = lineView.changes || (lineView.changes = []); |
| 2091 if (indexOf(arr, type) == -1) arr.push(type); |
| 2092 } |
| 2093 |
| 2094 // Clear the view. |
| 2095 function resetView(cm) { |
| 2096 cm.display.viewFrom = cm.display.viewTo = cm.doc.first; |
| 2097 cm.display.view = []; |
| 2098 cm.display.viewOffset = 0; |
| 2099 } |
| 2100 |
| 2101 // Find the view element corresponding to a given line. Return null |
| 2102 // when the line isn't visible. |
| 2103 function findViewIndex(cm, n) { |
| 2104 if (n >= cm.display.viewTo) return null; |
| 2105 n -= cm.display.viewFrom; |
| 2106 if (n < 0) return null; |
| 2107 var view = cm.display.view; |
| 2108 for (var i = 0; i < view.length; i++) { |
| 2109 n -= view[i].size; |
| 2110 if (n < 0) return i; |
| 2111 } |
| 2112 } |
| 2113 |
| 2114 function viewCuttingPoint(cm, oldN, newN, dir) { |
| 2115 var index = findViewIndex(cm, oldN), diff, view = cm.display.view; |
| 2116 if (!sawCollapsedSpans) return {index: index, lineN: newN}; |
| 2117 for (var i = 0, n = cm.display.viewFrom; i < index; i++) |
| 2118 n += view[i].size; |
| 2119 if (n != oldN) { |
| 2120 if (dir > 0) { |
| 2121 if (index == view.length - 1) return null; |
| 2122 diff = (n + view[index].size) - oldN; |
| 2123 index++; |
| 2124 } else { |
| 2125 diff = n - oldN; |
| 2126 } |
| 2127 oldN += diff; newN += diff; |
| 2128 } |
| 2129 while (visualLineNo(cm.doc, newN) != newN) { |
| 2130 if (index == (dir < 0 ? 0 : view.length - 1)) return null; |
| 2131 newN += dir * view[index - (dir < 0 ? 1 : 0)].size; |
| 2132 index += dir; |
| 2133 } |
| 2134 return {index: index, lineN: newN}; |
| 2135 } |
| 2136 |
| 2137 // Force the view to cover a given range, adding empty view element |
| 2138 // or clipping off existing ones as needed. |
| 2139 function adjustView(cm, from, to) { |
| 2140 var display = cm.display, view = display.view; |
| 2141 if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { |
| 2142 display.view = buildViewArray(cm, from, to); |
| 2143 display.viewFrom = from; |
| 2144 } else { |
| 2145 if (display.viewFrom > from) |
| 2146 display.view = buildViewArray(cm, from, display.viewFrom).concat(display
.view); |
| 2147 else if (display.viewFrom < from) |
| 2148 display.view = display.view.slice(findViewIndex(cm, from)); |
| 2149 display.viewFrom = from; |
| 2150 if (display.viewTo < to) |
| 2151 display.view = display.view.concat(buildViewArray(cm, display.viewTo, to
)); |
| 2152 else if (display.viewTo > to) |
| 2153 display.view = display.view.slice(0, findViewIndex(cm, to)); |
| 2154 } |
| 2155 display.viewTo = to; |
| 2156 } |
| 2157 |
| 2158 // Count the number of lines in the view whose DOM representation is |
| 2159 // out of date (or nonexistent). |
| 2160 function countDirtyView(cm) { |
| 2161 var view = cm.display.view, dirty = 0; |
| 2162 for (var i = 0; i < view.length; i++) { |
| 2163 var lineView = view[i]; |
| 2164 if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty; |
| 2165 } |
| 2166 return dirty; |
| 1461 } | 2167 } |
| 1462 | 2168 |
| 1463 // INPUT HANDLING | 2169 // INPUT HANDLING |
| 1464 | 2170 |
| 2171 // Poll for input changes, using the normal rate of polling. This |
| 2172 // runs as long as the editor is focused. |
| 1465 function slowPoll(cm) { | 2173 function slowPoll(cm) { |
| 1466 if (cm.display.pollingFast) return; | 2174 if (cm.display.pollingFast) return; |
| 1467 cm.display.poll.set(cm.options.pollInterval, function() { | 2175 cm.display.poll.set(cm.options.pollInterval, function() { |
| 1468 readInput(cm); | 2176 readInput(cm); |
| 1469 if (cm.state.focused) slowPoll(cm); | 2177 if (cm.state.focused) slowPoll(cm); |
| 1470 }); | 2178 }); |
| 1471 } | 2179 } |
| 1472 | 2180 |
| 2181 // When an event has just come in that is likely to add or change |
| 2182 // something in the input textarea, we poll faster, to ensure that |
| 2183 // the change appears on the screen quickly. |
| 1473 function fastPoll(cm) { | 2184 function fastPoll(cm) { |
| 1474 var missed = false; | 2185 var missed = false; |
| 1475 cm.display.pollingFast = true; | 2186 cm.display.pollingFast = true; |
| 1476 function p() { | 2187 function p() { |
| 1477 var changed = readInput(cm); | 2188 var changed = readInput(cm); |
| 1478 if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);} | 2189 if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);} |
| 1479 else {cm.display.pollingFast = false; slowPoll(cm);} | 2190 else {cm.display.pollingFast = false; slowPoll(cm);} |
| 1480 } | 2191 } |
| 1481 cm.display.poll.set(20, p); | 2192 cm.display.poll.set(20, p); |
| 1482 } | 2193 } |
| 1483 | 2194 |
| 1484 // prevInput is a hack to work with IME. If we reset the textarea | 2195 // Read input from the textarea, and update the document to match. |
| 1485 // on every change, that breaks IME. So we look for changes | 2196 // When something is selected, it is present in the textarea, and |
| 1486 // compared to the previous content instead. (Modern browsers have | 2197 // selected (unless it is huge, in which case a placeholder is |
| 1487 // events that indicate IME taking place, but these are not widely | 2198 // used). When nothing is selected, the cursor sits after previously |
| 1488 // supported or compatible enough yet to rely on.) | 2199 // seen text (can be empty), which is stored in prevInput (we must |
| 2200 // not reset the textarea when typing, because that breaks IME). |
| 1489 function readInput(cm) { | 2201 function readInput(cm) { |
| 1490 var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc
, sel = doc.sel; | 2202 var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc
; |
| 2203 // Since this is called a *lot*, try to bail out as cheaply as |
| 2204 // possible when it is clear that nothing happened. hasSelection |
| 2205 // will be the case when there is a lot of text in the textarea, |
| 2206 // in which case reading its value would be expensive. |
| 1491 if (!cm.state.focused || hasSelection(input) || isReadOnly(cm) || cm.options
.disableInput) return false; | 2207 if (!cm.state.focused || hasSelection(input) || isReadOnly(cm) || cm.options
.disableInput) return false; |
| 1492 if (cm.state.pasteIncoming && cm.state.fakedLastChar) { | |
| 1493 input.value = input.value.substring(0, input.value.length - 1); | |
| 1494 cm.state.fakedLastChar = false; | |
| 1495 } | |
| 1496 var text = input.value; | 2208 var text = input.value; |
| 1497 if (text == prevInput && posEq(sel.from, sel.to)) return false; | 2209 // If nothing changed, bail. |
| 1498 if (ie && !ie_lt9 && cm.display.inputHasSelection === text) { | 2210 if (text == prevInput && !cm.somethingSelected()) return false; |
| 1499 resetInput(cm, true); | 2211 // Work around nonsensical selection resetting in IE9/10 |
| 2212 if (ie && !ie_upto8 && cm.display.inputHasSelection === text) { |
| 2213 resetInput(cm); |
| 1500 return false; | 2214 return false; |
| 1501 } | 2215 } |
| 1502 | 2216 |
| 1503 var withOp = !cm.curOp; | 2217 var withOp = !cm.curOp; |
| 1504 if (withOp) startOperation(cm); | 2218 if (withOp) startOperation(cm); |
| 1505 sel.shift = false; | 2219 cm.display.shift = false; |
| 2220 |
| 2221 // Find the part of the input that is actually new |
| 1506 var same = 0, l = Math.min(prevInput.length, text.length); | 2222 var same = 0, l = Math.min(prevInput.length, text.length); |
| 1507 while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++sa
me; | 2223 while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++sa
me; |
| 1508 var from = sel.from, to = sel.to; | 2224 var inserted = text.slice(same), textLines = splitLines(inserted); |
| 1509 var inserted = text.slice(same); | |
| 1510 if (same < prevInput.length) | |
| 1511 from = Pos(from.line, from.ch - (prevInput.length - same)); | |
| 1512 else if (cm.state.overwrite && posEq(from, to) && !cm.state.pasteIncoming) | |
| 1513 to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + inse
rted.length)); | |
| 1514 | 2225 |
| 1515 var updateInput = cm.curOp.updateInput; | 2226 // When pasing N lines into N selections, insert one line per selection |
| 1516 var changeEvent = {from: from, to: to, text: splitLines(inserted), | 2227 var multiPaste = cm.state.pasteIncoming && textLines.length > 1 && doc.sel.r
anges.length == textLines.length; |
| 1517 origin: cm.state.pasteIncoming ? "paste" : cm.state.cutIn
coming ? "cut" : "+input"}; | 2228 |
| 1518 makeChange(cm.doc, changeEvent, "end"); | 2229 // Normal behavior is to insert the new text into every selection |
| 2230 for (var i = doc.sel.ranges.length - 1; i >= 0; i--) { |
| 2231 var range = doc.sel.ranges[i]; |
| 2232 var from = range.from(), to = range.to(); |
| 2233 // Handle deletion |
| 2234 if (same < prevInput.length) |
| 2235 from = Pos(from.line, from.ch - (prevInput.length - same)); |
| 2236 // Handle overwrite |
| 2237 else if (cm.state.overwrite && range.empty() && !cm.state.pasteIncoming) |
| 2238 to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + ls
t(textLines).length)); |
| 2239 var updateInput = cm.curOp.updateInput; |
| 2240 var changeEvent = {from: from, to: to, text: multiPaste ? [textLines[i]] :
textLines, |
| 2241 origin: cm.state.pasteIncoming ? "paste" : cm.state.cut
Incoming ? "cut" : "+input"}; |
| 2242 makeChange(cm.doc, changeEvent); |
| 2243 signalLater(cm, "inputRead", cm, changeEvent); |
| 2244 // When an 'electric' character is inserted, immediately trigger a reinden
t |
| 2245 if (inserted && !cm.state.pasteIncoming && cm.options.electricChars && |
| 2246 cm.options.smartIndent && range.head.ch < 100 && |
| 2247 (!i || doc.sel.ranges[i - 1].head.line != range.head.line)) { |
| 2248 var electric = cm.getModeAt(range.head).electricChars; |
| 2249 if (electric) for (var j = 0; j < electric.length; j++) |
| 2250 if (inserted.indexOf(electric.charAt(j)) > -1) { |
| 2251 indentLine(cm, range.head.line, "smart"); |
| 2252 break; |
| 2253 } |
| 2254 } |
| 2255 } |
| 2256 ensureCursorVisible(cm); |
| 1519 cm.curOp.updateInput = updateInput; | 2257 cm.curOp.updateInput = updateInput; |
| 1520 signalLater(cm, "inputRead", cm, changeEvent); | 2258 cm.curOp.typing = true; |
| 1521 if (inserted && !cm.state.pasteIncoming && cm.options.electricChars && | |
| 1522 cm.options.smartIndent && sel.head.ch < 100) { | |
| 1523 var electric = cm.getModeAt(sel.head).electricChars; | |
| 1524 if (electric) for (var i = 0; i < electric.length; i++) | |
| 1525 if (inserted.indexOf(electric.charAt(i)) > -1) { | |
| 1526 indentLine(cm, sel.head.line, "smart"); | |
| 1527 break; | |
| 1528 } | |
| 1529 } | |
| 1530 | 2259 |
| 2260 // Don't leave long text in the textarea, since it makes further polling slo
w |
| 1531 if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.
prevInput = ""; | 2261 if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.
prevInput = ""; |
| 1532 else cm.display.prevInput = text; | 2262 else cm.display.prevInput = text; |
| 1533 if (withOp) endOperation(cm); | 2263 if (withOp) endOperation(cm); |
| 1534 cm.state.pasteIncoming = cm.state.cutIncoming = false; | 2264 cm.state.pasteIncoming = cm.state.cutIncoming = false; |
| 1535 return true; | 2265 return true; |
| 1536 } | 2266 } |
| 1537 | 2267 |
| 1538 function resetInput(cm, user) { | 2268 // Reset the input to correspond to the selection (or to be empty, |
| 2269 // when not typing and nothing is selected) |
| 2270 function resetInput(cm, typing) { |
| 1539 var minimal, selected, doc = cm.doc; | 2271 var minimal, selected, doc = cm.doc; |
| 1540 if (!posEq(doc.sel.from, doc.sel.to)) { | 2272 if (cm.somethingSelected()) { |
| 1541 cm.display.prevInput = ""; | 2273 cm.display.prevInput = ""; |
| 2274 var range = doc.sel.primary(); |
| 1542 minimal = hasCopyEvent && | 2275 minimal = hasCopyEvent && |
| 1543 (doc.sel.to.line - doc.sel.from.line > 100 || (selected = cm.getSelectio
n()).length > 1000); | 2276 (range.to().line - range.from().line > 100 || (selected = cm.getSelectio
n()).length > 1000); |
| 1544 var content = minimal ? "-" : selected || cm.getSelection(); | 2277 var content = minimal ? "-" : selected || cm.getSelection(); |
| 1545 cm.display.input.value = content; | 2278 cm.display.input.value = content; |
| 1546 if (cm.state.focused) selectInput(cm.display.input); | 2279 if (cm.state.focused) selectInput(cm.display.input); |
| 1547 if (ie && !ie_lt9) cm.display.inputHasSelection = content; | 2280 if (ie && !ie_upto8) cm.display.inputHasSelection = content; |
| 1548 } else if (user) { | 2281 } else if (!typing) { |
| 1549 cm.display.prevInput = cm.display.input.value = ""; | 2282 cm.display.prevInput = cm.display.input.value = ""; |
| 1550 if (ie && !ie_lt9) cm.display.inputHasSelection = null; | 2283 if (ie && !ie_upto8) cm.display.inputHasSelection = null; |
| 1551 } | 2284 } |
| 1552 cm.display.inaccurateSelection = minimal; | 2285 cm.display.inaccurateSelection = minimal; |
| 1553 } | 2286 } |
| 1554 | 2287 |
| 1555 function focusInput(cm) { | 2288 function focusInput(cm) { |
| 1556 if (cm.options.readOnly != "nocursor" && (!mobile || document.activeElement
!= cm.display.input)) | 2289 if (cm.options.readOnly != "nocursor" && (!mobile || activeElt() != cm.displ
ay.input)) |
| 1557 cm.display.input.focus(); | 2290 cm.display.input.focus(); |
| 1558 } | 2291 } |
| 1559 | 2292 |
| 2293 function ensureFocus(cm) { |
| 2294 if (!cm.state.focused) { focusInput(cm); onFocus(cm); } |
| 2295 } |
| 2296 |
| 1560 function isReadOnly(cm) { | 2297 function isReadOnly(cm) { |
| 1561 return cm.options.readOnly || cm.doc.cantEdit; | 2298 return cm.options.readOnly || cm.doc.cantEdit; |
| 1562 } | 2299 } |
| 1563 | 2300 |
| 1564 // EVENT HANDLERS | 2301 // EVENT HANDLERS |
| 1565 | 2302 |
| 2303 // Attach the necessary event handlers when initializing the editor |
| 1566 function registerEventHandlers(cm) { | 2304 function registerEventHandlers(cm) { |
| 1567 var d = cm.display; | 2305 var d = cm.display; |
| 1568 on(d.scroller, "mousedown", operation(cm, onMouseDown)); | 2306 on(d.scroller, "mousedown", operation(cm, onMouseDown)); |
| 1569 if (old_ie) | 2307 // Older IE's will not fire a second mousedown for a double click |
| 2308 if (ie_upto10) |
| 1570 on(d.scroller, "dblclick", operation(cm, function(e) { | 2309 on(d.scroller, "dblclick", operation(cm, function(e) { |
| 1571 if (signalDOMEvent(cm, e)) return; | 2310 if (signalDOMEvent(cm, e)) return; |
| 1572 var pos = posFromMouse(cm, e); | 2311 var pos = posFromMouse(cm, e); |
| 1573 if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return
; | 2312 if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return
; |
| 1574 e_preventDefault(e); | 2313 e_preventDefault(e); |
| 1575 var word = findWordAt(getLine(cm.doc, pos.line).text, pos); | 2314 var word = findWordAt(cm.doc, pos); |
| 1576 extendSelection(cm.doc, word.from, word.to); | 2315 extendSelection(cm.doc, word.anchor, word.head); |
| 1577 })); | 2316 })); |
| 1578 else | 2317 else |
| 1579 on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preven
tDefault(e); }); | 2318 on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preven
tDefault(e); }); |
| 2319 // Prevent normal selection in the editor (we handle our own) |
| 1580 on(d.lineSpace, "selectstart", function(e) { | 2320 on(d.lineSpace, "selectstart", function(e) { |
| 1581 if (!eventInWidget(d, e)) e_preventDefault(e); | 2321 if (!eventInWidget(d, e)) e_preventDefault(e); |
| 1582 }); | 2322 }); |
| 1583 // Gecko browsers fire contextmenu *after* opening the menu, at | 2323 // Some browsers fire contextmenu *after* opening the menu, at |
| 1584 // which point we can't mess with it anymore. Context menu is | 2324 // which point we can't mess with it anymore. Context menu is |
| 1585 // handled in onMouseDown for Gecko. | 2325 // handled in onMouseDown for these browsers. |
| 1586 if (!captureMiddleClick) on(d.scroller, "contextmenu", function(e) {onContex
tMenu(cm, e);}); | 2326 if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContext
Menu(cm, e);}); |
| 1587 | 2327 |
| 2328 // Sync scrolling between fake scrollbars and real scrollable |
| 2329 // area, ensure viewport is updated when scrolling. |
| 1588 on(d.scroller, "scroll", function() { | 2330 on(d.scroller, "scroll", function() { |
| 1589 if (d.scroller.clientHeight) { | 2331 if (d.scroller.clientHeight) { |
| 1590 setScrollTop(cm, d.scroller.scrollTop); | 2332 setScrollTop(cm, d.scroller.scrollTop); |
| 1591 setScrollLeft(cm, d.scroller.scrollLeft, true); | 2333 setScrollLeft(cm, d.scroller.scrollLeft, true); |
| 1592 signal(cm, "scroll", cm); | 2334 signal(cm, "scroll", cm); |
| 1593 } | 2335 } |
| 1594 }); | 2336 }); |
| 1595 on(d.scrollbarV, "scroll", function() { | 2337 on(d.scrollbarV, "scroll", function() { |
| 1596 if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop); | 2338 if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop); |
| 1597 }); | 2339 }); |
| 1598 on(d.scrollbarH, "scroll", function() { | 2340 on(d.scrollbarH, "scroll", function() { |
| 1599 if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft); | 2341 if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft); |
| 1600 }); | 2342 }); |
| 1601 | 2343 |
| 2344 // Listen to wheel events in order to try and update the viewport on time. |
| 1602 on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);}); | 2345 on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);}); |
| 1603 on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);}); | 2346 on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);}); |
| 1604 | 2347 |
| 2348 // Prevent clicks in the scrollbars from killing focus |
| 1605 function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm),
0); } | 2349 function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm),
0); } |
| 1606 on(d.scrollbarH, "mousedown", reFocus); | 2350 on(d.scrollbarH, "mousedown", reFocus); |
| 1607 on(d.scrollbarV, "mousedown", reFocus); | 2351 on(d.scrollbarV, "mousedown", reFocus); |
| 1608 // Prevent wrapper from ever scrolling | 2352 // Prevent wrapper from ever scrolling |
| 1609 on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollL
eft = 0; }); | 2353 on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollL
eft = 0; }); |
| 1610 | 2354 |
| 2355 // When the window resizes, we need to refresh active editors. |
| 1611 var resizeTimer; | 2356 var resizeTimer; |
| 1612 function onResize() { | 2357 function onResize() { |
| 1613 if (resizeTimer == null) resizeTimer = setTimeout(function() { | 2358 if (resizeTimer == null) resizeTimer = setTimeout(function() { |
| 1614 resizeTimer = null; | 2359 resizeTimer = null; |
| 1615 // Might be a text scaling operation, clear size caches. | 2360 // Might be a text scaling operation, clear size caches. |
| 1616 d.cachedCharWidth = d.cachedTextHeight = knownScrollbarWidth = null; | 2361 d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = knownScrollb
arWidth = null; |
| 1617 clearCaches(cm); | 2362 cm.setSize(); |
| 1618 runInOp(cm, bind(regChange, cm)); | |
| 1619 }, 100); | 2363 }, 100); |
| 1620 } | 2364 } |
| 1621 on(window, "resize", onResize); | 2365 on(window, "resize", onResize); |
| 1622 // Above handler holds on to the editor and its data structures. | 2366 // The above handler holds on to the editor and its data |
| 1623 // Here we poll to unregister it when the editor is no longer in | 2367 // structures. Here we poll to unregister it when the editor is no |
| 1624 // the document, so that it can be garbage-collected. | 2368 // longer in the document, so that it can be garbage-collected. |
| 1625 function unregister() { | 2369 function unregister() { |
| 1626 for (var p = d.wrapper.parentNode; p && p != document.body; p = p.parentNo
de) {} | 2370 if (contains(document.body, d.wrapper)) setTimeout(unregister, 5000); |
| 1627 if (p) setTimeout(unregister, 5000); | |
| 1628 else off(window, "resize", onResize); | 2371 else off(window, "resize", onResize); |
| 1629 } | 2372 } |
| 1630 setTimeout(unregister, 5000); | 2373 setTimeout(unregister, 5000); |
| 1631 | 2374 |
| 1632 on(d.input, "keyup", operation(cm, onKeyUp)); | 2375 on(d.input, "keyup", operation(cm, onKeyUp)); |
| 1633 on(d.input, "input", function() { | 2376 on(d.input, "input", function() { |
| 1634 if (ie && !ie_lt9 && cm.display.inputHasSelection) cm.display.inputHasSele
ction = null; | 2377 if (ie && !ie_upto8 && cm.display.inputHasSelection) cm.display.inputHasSe
lection = null; |
| 1635 fastPoll(cm); | 2378 fastPoll(cm); |
| 1636 }); | 2379 }); |
| 1637 on(d.input, "keydown", operation(cm, onKeyDown)); | 2380 on(d.input, "keydown", operation(cm, onKeyDown)); |
| 1638 on(d.input, "keypress", operation(cm, onKeyPress)); | 2381 on(d.input, "keypress", operation(cm, onKeyPress)); |
| 1639 on(d.input, "focus", bind(onFocus, cm)); | 2382 on(d.input, "focus", bind(onFocus, cm)); |
| 1640 on(d.input, "blur", bind(onBlur, cm)); | 2383 on(d.input, "blur", bind(onBlur, cm)); |
| 1641 | 2384 |
| 1642 function drag_(e) { | 2385 function drag_(e) { |
| 1643 if (signalDOMEvent(cm, e) || cm.options.onDragEvent && cm.options.onDragEv
ent(cm, addStop(e))) return; | 2386 if (!signalDOMEvent(cm, e)) e_stop(e); |
| 1644 e_stop(e); | |
| 1645 } | 2387 } |
| 1646 if (cm.options.dragDrop) { | 2388 if (cm.options.dragDrop) { |
| 1647 on(d.scroller, "dragstart", function(e){onDragStart(cm, e);}); | 2389 on(d.scroller, "dragstart", function(e){onDragStart(cm, e);}); |
| 1648 on(d.scroller, "dragenter", drag_); | 2390 on(d.scroller, "dragenter", drag_); |
| 1649 on(d.scroller, "dragover", drag_); | 2391 on(d.scroller, "dragover", drag_); |
| 1650 on(d.scroller, "drop", operation(cm, onDrop)); | 2392 on(d.scroller, "drop", operation(cm, onDrop)); |
| 1651 } | 2393 } |
| 1652 on(d.scroller, "paste", function(e) { | 2394 on(d.scroller, "paste", function(e) { |
| 1653 if (eventInWidget(d, e)) return; | 2395 if (eventInWidget(d, e)) return; |
| 2396 cm.state.pasteIncoming = true; |
| 1654 focusInput(cm); | 2397 focusInput(cm); |
| 1655 fastPoll(cm); | 2398 fastPoll(cm); |
| 1656 }); | 2399 }); |
| 1657 on(d.input, "paste", function() { | 2400 on(d.input, "paste", function() { |
| 1658 // Workaround for webkit bug https://bugs.webkit.org/show_bug.cgi?id=90206 | |
| 1659 // Add a char to the end of textarea before paste occur so that | |
| 1660 // selection doesn't span to the end of textarea. | |
| 1661 if (webkit && !cm.state.fakedLastChar && !(new Date - cm.state.lastMiddleD
own < 200)) { | |
| 1662 var start = d.input.selectionStart, end = d.input.selectionEnd; | |
| 1663 d.input.value += "$"; | |
| 1664 d.input.selectionStart = start; | |
| 1665 d.input.selectionEnd = end; | |
| 1666 cm.state.fakedLastChar = true; | |
| 1667 } | |
| 1668 cm.state.pasteIncoming = true; | 2401 cm.state.pasteIncoming = true; |
| 1669 fastPoll(cm); | 2402 fastPoll(cm); |
| 1670 }); | 2403 }); |
| 1671 | 2404 |
| 1672 function prepareCopy(e) { | 2405 function prepareCopy(e) { |
| 1673 if (d.inaccurateSelection) { | 2406 if (d.inaccurateSelection) { |
| 1674 d.prevInput = ""; | 2407 d.prevInput = ""; |
| 1675 d.inaccurateSelection = false; | 2408 d.inaccurateSelection = false; |
| 1676 d.input.value = cm.getSelection(); | 2409 d.input.value = cm.getSelection(); |
| 1677 selectInput(d.input); | 2410 selectInput(d.input); |
| 1678 } | 2411 } |
| 1679 if (e.type == "cut") cm.state.cutIncoming = true; | 2412 if (e.type == "cut") cm.state.cutIncoming = true; |
| 1680 } | 2413 } |
| 1681 on(d.input, "cut", prepareCopy); | 2414 on(d.input, "cut", prepareCopy); |
| 1682 on(d.input, "copy", prepareCopy); | 2415 on(d.input, "copy", prepareCopy); |
| 1683 | 2416 |
| 1684 // Needed to handle Tab key in KHTML | 2417 // Needed to handle Tab key in KHTML |
| 1685 if (khtml) on(d.sizer, "mouseup", function() { | 2418 if (khtml) on(d.sizer, "mouseup", function() { |
| 1686 if (document.activeElement == d.input) d.input.blur(); | 2419 if (activeElt() == d.input) d.input.blur(); |
| 1687 focusInput(cm); | 2420 focusInput(cm); |
| 1688 }); | 2421 }); |
| 1689 } | 2422 } |
| 1690 | 2423 |
| 2424 // MOUSE EVENTS |
| 2425 |
| 2426 // Return true when the given mouse event happened in a widget |
| 1691 function eventInWidget(display, e) { | 2427 function eventInWidget(display, e) { |
| 1692 for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { | 2428 for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { |
| 1693 if (!n || n.ignoreEvents || n.parentNode == display.sizer && n != display.
mover) return true; | 2429 if (!n || n.ignoreEvents || n.parentNode == display.sizer && n != display.
mover) return true; |
| 1694 } | 2430 } |
| 1695 } | 2431 } |
| 1696 | 2432 |
| 1697 function posFromMouse(cm, e, liberal) { | 2433 // Given a mouse event, find the corresponding position. If liberal |
| 2434 // is false, it checks whether a gutter or scrollbar was clicked, |
| 2435 // and returns null if it was. forRect is used by rectangular |
| 2436 // selections, and tries to estimate a character position even for |
| 2437 // coordinates beyond the right of the text. |
| 2438 function posFromMouse(cm, e, liberal, forRect) { |
| 1698 var display = cm.display; | 2439 var display = cm.display; |
| 1699 if (!liberal) { | 2440 if (!liberal) { |
| 1700 var target = e_target(e); | 2441 var target = e_target(e); |
| 1701 if (target == display.scrollbarH || target == display.scrollbarH.firstChil
d || | 2442 if (target == display.scrollbarH || target == display.scrollbarV || |
| 1702 target == display.scrollbarV || target == display.scrollbarV.firstChil
d || | |
| 1703 target == display.scrollbarFiller || target == display.gutterFiller) r
eturn null; | 2443 target == display.scrollbarFiller || target == display.gutterFiller) r
eturn null; |
| 1704 } | 2444 } |
| 1705 var x, y, space = getRect(display.lineSpace); | 2445 var x, y, space = display.lineSpace.getBoundingClientRect(); |
| 1706 // Fails unpredictably on IE[67] when mouse is dragged around quickly. | 2446 // Fails unpredictably on IE[67] when mouse is dragged around quickly. |
| 1707 try { x = e.clientX; y = e.clientY; } catch (e) { return null; } | 2447 try { x = e.clientX - space.left; y = e.clientY - space.top; } |
| 1708 return coordsChar(cm, x - space.left, y - space.top); | 2448 catch (e) { return null; } |
| 2449 var coords = coordsChar(cm, x, y), line; |
| 2450 if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text
).length == coords.ch) { |
| 2451 var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.le
ngth; |
| 2452 coords = Pos(coords.line, Math.round((x - paddingH(cm.display).left) / cha
rWidth(cm.display)) - colDiff); |
| 2453 } |
| 2454 return coords; |
| 1709 } | 2455 } |
| 1710 | 2456 |
| 1711 var lastClick, lastDoubleClick; | 2457 // A mouse down can be a single click, double click, triple click, |
| 2458 // start of selection drag, start of text drag, new cursor |
| 2459 // (ctrl-click), rectangle drag (alt-drag), or xwin |
| 2460 // middle-click-paste. Or it might be a click on something we should |
| 2461 // not interfere with, such as a scrollbar or widget. |
| 1712 function onMouseDown(e) { | 2462 function onMouseDown(e) { |
| 1713 if (signalDOMEvent(this, e)) return; | 2463 if (signalDOMEvent(this, e)) return; |
| 1714 var cm = this, display = cm.display, doc = cm.doc, sel = doc.sel; | 2464 var cm = this, display = cm.display; |
| 1715 sel.shift = e.shiftKey; | 2465 display.shift = e.shiftKey; |
| 1716 | 2466 |
| 1717 if (eventInWidget(display, e)) { | 2467 if (eventInWidget(display, e)) { |
| 1718 if (!webkit) { | 2468 if (!webkit) { |
| 2469 // Briefly turn off draggability, to allow widgets to do |
| 2470 // normal dragging things. |
| 1719 display.scroller.draggable = false; | 2471 display.scroller.draggable = false; |
| 1720 setTimeout(function(){display.scroller.draggable = true;}, 100); | 2472 setTimeout(function(){display.scroller.draggable = true;}, 100); |
| 1721 } | 2473 } |
| 1722 return; | 2474 return; |
| 1723 } | 2475 } |
| 1724 if (clickInGutter(cm, e)) return; | 2476 if (clickInGutter(cm, e)) return; |
| 1725 var start = posFromMouse(cm, e); | 2477 var start = posFromMouse(cm, e); |
| 2478 window.focus(); |
| 1726 | 2479 |
| 1727 switch (e_button(e)) { | 2480 switch (e_button(e)) { |
| 1728 case 3: | 2481 case 1: |
| 1729 if (captureMiddleClick) onContextMenu.call(cm, cm, e); | 2482 if (start) |
| 1730 return; | 2483 leftButtonDown(cm, e, start); |
| 2484 else if (e_target(e) == display.scroller) |
| 2485 e_preventDefault(e); |
| 2486 break; |
| 1731 case 2: | 2487 case 2: |
| 1732 if (webkit) cm.state.lastMiddleDown = +new Date; | 2488 if (webkit) cm.state.lastMiddleDown = +new Date; |
| 1733 if (start) extendSelection(cm.doc, start); | 2489 if (start) extendSelection(cm.doc, start); |
| 1734 setTimeout(bind(focusInput, cm), 20); | 2490 setTimeout(bind(focusInput, cm), 20); |
| 1735 e_preventDefault(e); | 2491 e_preventDefault(e); |
| 1736 return; | 2492 break; |
| 2493 case 3: |
| 2494 if (captureRightClick) onContextMenu(cm, e); |
| 2495 break; |
| 1737 } | 2496 } |
| 1738 // For button 1, if it was clicked inside the editor | 2497 } |
| 1739 // (posFromMouse returning non-null), we have to adjust the | |
| 1740 // selection. | |
| 1741 if (!start) {if (e_target(e) == display.scroller) e_preventDefault(e); retur
n;} | |
| 1742 | 2498 |
| 1743 if (!cm.state.focused) onFocus(cm); | 2499 var lastClick, lastDoubleClick; |
| 2500 function leftButtonDown(cm, e, start) { |
| 2501 setTimeout(bind(ensureFocus, cm), 0); |
| 1744 | 2502 |
| 1745 var now = +new Date, type = "single"; | 2503 var now = +new Date, type; |
| 1746 if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleC
lick.pos, start)) { | 2504 if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleCli
ck.pos, start) == 0) { |
| 1747 type = "triple"; | 2505 type = "triple"; |
| 1748 e_preventDefault(e); | 2506 } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, sta
rt) == 0) { |
| 1749 setTimeout(bind(focusInput, cm), 20); | |
| 1750 selectLine(cm, start.line); | |
| 1751 } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, s
tart)) { | |
| 1752 type = "double"; | 2507 type = "double"; |
| 1753 lastDoubleClick = {time: now, pos: start}; | 2508 lastDoubleClick = {time: now, pos: start}; |
| 1754 e_preventDefault(e); | 2509 } else { |
| 1755 var word = findWordAt(getLine(doc, start.line).text, start); | 2510 type = "single"; |
| 1756 extendSelection(cm.doc, word.from, word.to); | 2511 lastClick = {time: now, pos: start}; |
| 1757 } else { lastClick = {time: now, pos: start}; } | 2512 } |
| 1758 | 2513 |
| 1759 var last = start; | 2514 var sel = cm.doc.sel, addNew = mac ? e.metaKey : e.ctrlKey; |
| 1760 if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && !posEq(sel.from
, sel.to) && | 2515 if (cm.options.dragDrop && dragAndDrop && !addNew && !isReadOnly(cm) && |
| 1761 !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single"
) { | 2516 type == "single" && sel.contains(start) > -1 && sel.somethingSelected()) |
| 1762 var dragEnd = operation(cm, function(e2) { | 2517 leftButtonStartDrag(cm, e, start); |
| 1763 if (webkit) display.scroller.draggable = false; | 2518 else |
| 1764 cm.state.draggingText = false; | 2519 leftButtonSelect(cm, e, start, type, addNew); |
| 1765 off(document, "mouseup", dragEnd); | 2520 } |
| 1766 off(display.scroller, "drop", dragEnd); | 2521 |
| 1767 if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY)
< 10) { | 2522 // Start a text drag. When it ends, see if any dragging actually |
| 1768 e_preventDefault(e2); | 2523 // happen, and treat as a click if it didn't. |
| 1769 extendSelection(cm.doc, start); | 2524 function leftButtonStartDrag(cm, e, start) { |
| 1770 focusInput(cm); | 2525 var display = cm.display; |
| 1771 // Work around unexplainable focus problem in IE9 (#2127) | 2526 var dragEnd = operation(cm, function(e2) { |
| 1772 if (old_ie && !ie_lt9) | 2527 if (webkit) display.scroller.draggable = false; |
| 1773 setTimeout(function() {document.body.focus(); focusInput(cm);}, 20); | 2528 cm.state.draggingText = false; |
| 2529 off(document, "mouseup", dragEnd); |
| 2530 off(display.scroller, "drop", dragEnd); |
| 2531 if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) <
10) { |
| 2532 e_preventDefault(e2); |
| 2533 extendSelection(cm.doc, start); |
| 2534 focusInput(cm); |
| 2535 // Work around unexplainable focus problem in IE9 (#2127) |
| 2536 if (ie_upto10 && !ie_upto8) |
| 2537 setTimeout(function() {document.body.focus(); focusInput(cm);}, 20); |
| 2538 } |
| 2539 }); |
| 2540 // Let the drag handler handle this. |
| 2541 if (webkit) display.scroller.draggable = true; |
| 2542 cm.state.draggingText = dragEnd; |
| 2543 // IE's approach to draggable |
| 2544 if (display.scroller.dragDrop) display.scroller.dragDrop(); |
| 2545 on(document, "mouseup", dragEnd); |
| 2546 on(display.scroller, "drop", dragEnd); |
| 2547 } |
| 2548 |
| 2549 // Normal selection, as opposed to text dragging. |
| 2550 function leftButtonSelect(cm, e, start, type, addNew) { |
| 2551 var display = cm.display, doc = cm.doc; |
| 2552 e_preventDefault(e); |
| 2553 |
| 2554 var ourRange, ourIndex, startSel = doc.sel; |
| 2555 if (addNew) { |
| 2556 ourIndex = doc.sel.contains(start); |
| 2557 if (ourIndex > -1) |
| 2558 ourRange = doc.sel.ranges[ourIndex]; |
| 2559 else |
| 2560 ourRange = new Range(start, start); |
| 2561 } else { |
| 2562 ourRange = doc.sel.primary(); |
| 2563 } |
| 2564 |
| 2565 if (e.altKey) { |
| 2566 type = "rect"; |
| 2567 if (!addNew) ourRange = new Range(start, start); |
| 2568 start = posFromMouse(cm, e, true, true); |
| 2569 ourIndex = -1; |
| 2570 } else if (type == "double") { |
| 2571 var word = findWordAt(doc, start); |
| 2572 if (cm.display.shift || doc.extend) |
| 2573 ourRange = extendRange(doc, ourRange, word.anchor, word.head); |
| 2574 else |
| 2575 ourRange = word; |
| 2576 } else if (type == "triple") { |
| 2577 var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1,
0))); |
| 2578 if (cm.display.shift || doc.extend) |
| 2579 ourRange = extendRange(doc, ourRange, line.anchor, line.head); |
| 2580 else |
| 2581 ourRange = line; |
| 2582 } else { |
| 2583 ourRange = extendRange(doc, ourRange, start); |
| 2584 } |
| 2585 |
| 2586 if (!addNew) { |
| 2587 ourIndex = 0; |
| 2588 setSelection(doc, new Selection([ourRange], 0), sel_mouse); |
| 2589 } else if (ourIndex > -1) { |
| 2590 replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); |
| 2591 } else { |
| 2592 ourIndex = doc.sel.ranges.length; |
| 2593 setSelection(doc, normalizeSelection(doc.sel.ranges.concat([ourRange]), ou
rIndex), |
| 2594 {scroll: false, origin: "*mouse"}); |
| 2595 } |
| 2596 |
| 2597 var lastPos = start; |
| 2598 function extendTo(pos) { |
| 2599 if (cmp(lastPos, pos) == 0) return; |
| 2600 lastPos = pos; |
| 2601 |
| 2602 if (type == "rect") { |
| 2603 var ranges = [], tabSize = cm.options.tabSize; |
| 2604 var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabS
ize); |
| 2605 var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); |
| 2606 var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol
); |
| 2607 for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLi
ne(), Math.max(start.line, pos.line)); |
| 2608 line <= end; line++) { |
| 2609 var text = getLine(doc, line).text, leftPos = findColumn(text, left, t
abSize); |
| 2610 if (left == right) |
| 2611 ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); |
| 2612 else if (text.length > leftPos) |
| 2613 ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text,
right, tabSize)))); |
| 1774 } | 2614 } |
| 1775 }); | 2615 if (!ranges.length) ranges.push(new Range(start, start)); |
| 1776 // Let the drag handler handle this. | 2616 setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).
concat(ranges), ourIndex), sel_mouse); |
| 1777 if (webkit) display.scroller.draggable = true; | 2617 } else { |
| 1778 cm.state.draggingText = dragEnd; | 2618 var oldRange = ourRange; |
| 1779 // IE's approach to draggable | 2619 var anchor = oldRange.anchor, head = pos; |
| 1780 if (display.scroller.dragDrop) display.scroller.dragDrop(); | 2620 if (type != "single") { |
| 1781 on(document, "mouseup", dragEnd); | 2621 if (type == "double") |
| 1782 on(display.scroller, "drop", dragEnd); | 2622 var range = findWordAt(doc, pos); |
| 1783 return; | 2623 else |
| 1784 } | 2624 var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line +
1, 0))); |
| 1785 e_preventDefault(e); | 2625 if (cmp(range.anchor, anchor) > 0) { |
| 1786 if (type == "single") extendSelection(cm.doc, clipPos(doc, start)); | 2626 head = range.head; |
| 1787 | 2627 anchor = minPos(oldRange.from(), range.anchor); |
| 1788 var startstart = sel.from, startend = sel.to, lastPos = start; | 2628 } else { |
| 1789 | 2629 head = range.anchor; |
| 1790 function doSelect(cur) { | 2630 anchor = maxPos(oldRange.to(), range.head); |
| 1791 if (posEq(lastPos, cur)) return; | 2631 } |
| 1792 lastPos = cur; | 2632 } |
| 1793 | 2633 var ranges = startSel.ranges.slice(0); |
| 1794 if (type == "single") { | 2634 ranges[ourIndex] = new Range(clipPos(doc, anchor), head); |
| 1795 extendSelection(cm.doc, clipPos(doc, start), cur); | 2635 setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse); |
| 1796 return; | |
| 1797 } | |
| 1798 | |
| 1799 startstart = clipPos(doc, startstart); | |
| 1800 startend = clipPos(doc, startend); | |
| 1801 if (type == "double") { | |
| 1802 var word = findWordAt(getLine(doc, cur.line).text, cur); | |
| 1803 if (posLess(cur, startstart)) extendSelection(cm.doc, word.from, starten
d); | |
| 1804 else extendSelection(cm.doc, startstart, word.to); | |
| 1805 } else if (type == "triple") { | |
| 1806 if (posLess(cur, startstart)) extendSelection(cm.doc, startend, clipPos(
doc, Pos(cur.line, 0))); | |
| 1807 else extendSelection(cm.doc, startstart, clipPos(doc, Pos(cur.line + 1,
0))); | |
| 1808 } | 2636 } |
| 1809 } | 2637 } |
| 1810 | 2638 |
| 1811 var editorSize = getRect(display.wrapper); | 2639 var editorSize = display.wrapper.getBoundingClientRect(); |
| 1812 // Used to ensure timeout re-tries don't fire when another extend | 2640 // Used to ensure timeout re-tries don't fire when another extend |
| 1813 // happened in the meantime (clearTimeout isn't reliable -- at | 2641 // happened in the meantime (clearTimeout isn't reliable -- at |
| 1814 // least on Chrome, the timeouts still happen even when cleared, | 2642 // least on Chrome, the timeouts still happen even when cleared, |
| 1815 // if the clear happens after their scheduled firing time). | 2643 // if the clear happens after their scheduled firing time). |
| 1816 var counter = 0; | 2644 var counter = 0; |
| 1817 | 2645 |
| 1818 function extend(e) { | 2646 function extend(e) { |
| 1819 var curCount = ++counter; | 2647 var curCount = ++counter; |
| 1820 var cur = posFromMouse(cm, e, true); | 2648 var cur = posFromMouse(cm, e, true, type == "rect"); |
| 1821 if (!cur) return; | 2649 if (!cur) return; |
| 1822 if (!posEq(cur, last)) { | 2650 if (cmp(cur, lastPos) != 0) { |
| 1823 if (!cm.state.focused) onFocus(cm); | 2651 ensureFocus(cm); |
| 1824 last = cur; | 2652 extendTo(cur); |
| 1825 doSelect(cur); | |
| 1826 var visible = visibleLines(display, doc); | 2653 var visible = visibleLines(display, doc); |
| 1827 if (cur.line >= visible.to || cur.line < visible.from) | 2654 if (cur.line >= visible.to || cur.line < visible.from) |
| 1828 setTimeout(operation(cm, function(){if (counter == curCount) extend(e)
;}), 150); | 2655 setTimeout(operation(cm, function(){if (counter == curCount) extend(e)
;}), 150); |
| 1829 } else { | 2656 } else { |
| 1830 var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.
bottom ? 20 : 0; | 2657 var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.
bottom ? 20 : 0; |
| 1831 if (outside) setTimeout(operation(cm, function() { | 2658 if (outside) setTimeout(operation(cm, function() { |
| 1832 if (counter != curCount) return; | 2659 if (counter != curCount) return; |
| 1833 display.scroller.scrollTop += outside; | 2660 display.scroller.scrollTop += outside; |
| 1834 extend(e); | 2661 extend(e); |
| 1835 }), 50); | 2662 }), 50); |
| 1836 } | 2663 } |
| 1837 } | 2664 } |
| 1838 | 2665 |
| 1839 function done(e) { | 2666 function done(e) { |
| 1840 counter = Infinity; | 2667 counter = Infinity; |
| 1841 e_preventDefault(e); | 2668 e_preventDefault(e); |
| 1842 focusInput(cm); | 2669 focusInput(cm); |
| 1843 off(document, "mousemove", move); | 2670 off(document, "mousemove", move); |
| 1844 off(document, "mouseup", up); | 2671 off(document, "mouseup", up); |
| 2672 doc.history.lastSelOrigin = null; |
| 1845 } | 2673 } |
| 1846 | 2674 |
| 1847 var move = operation(cm, function(e) { | 2675 var move = operation(cm, function(e) { |
| 1848 if (!old_ie && !e_button(e)) done(e); | 2676 if ((ie && !ie_upto9) ? !e.buttons : !e_button(e)) done(e); |
| 1849 else extend(e); | 2677 else extend(e); |
| 1850 }); | 2678 }); |
| 1851 var up = operation(cm, done); | 2679 var up = operation(cm, done); |
| 1852 on(document, "mousemove", move); | 2680 on(document, "mousemove", move); |
| 1853 on(document, "mouseup", up); | 2681 on(document, "mouseup", up); |
| 1854 } | 2682 } |
| 1855 | 2683 |
| 2684 // Determines whether an event happened in the gutter, and fires the |
| 2685 // handlers for the corresponding event. |
| 1856 function gutterEvent(cm, e, type, prevent, signalfn) { | 2686 function gutterEvent(cm, e, type, prevent, signalfn) { |
| 1857 try { var mX = e.clientX, mY = e.clientY; } | 2687 try { var mX = e.clientX, mY = e.clientY; } |
| 1858 catch(e) { return false; } | 2688 catch(e) { return false; } |
| 1859 if (mX >= Math.floor(getRect(cm.display.gutters).right)) return false; | 2689 if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) retu
rn false; |
| 1860 if (prevent) e_preventDefault(e); | 2690 if (prevent) e_preventDefault(e); |
| 1861 | 2691 |
| 1862 var display = cm.display; | 2692 var display = cm.display; |
| 1863 var lineBox = getRect(display.lineDiv); | 2693 var lineBox = display.lineDiv.getBoundingClientRect(); |
| 1864 | 2694 |
| 1865 if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(
e); | 2695 if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(
e); |
| 1866 mY -= lineBox.top - display.viewOffset; | 2696 mY -= lineBox.top - display.viewOffset; |
| 1867 | 2697 |
| 1868 for (var i = 0; i < cm.options.gutters.length; ++i) { | 2698 for (var i = 0; i < cm.options.gutters.length; ++i) { |
| 1869 var g = display.gutters.childNodes[i]; | 2699 var g = display.gutters.childNodes[i]; |
| 1870 if (g && getRect(g).right >= mX) { | 2700 if (g && g.getBoundingClientRect().right >= mX) { |
| 1871 var line = lineAtHeight(cm.doc, mY); | 2701 var line = lineAtHeight(cm.doc, mY); |
| 1872 var gutter = cm.options.gutters[i]; | 2702 var gutter = cm.options.gutters[i]; |
| 1873 signalfn(cm, type, cm, line, gutter, e); | 2703 signalfn(cm, type, cm, line, gutter, e); |
| 1874 return e_defaultPrevented(e); | 2704 return e_defaultPrevented(e); |
| 1875 } | 2705 } |
| 1876 } | 2706 } |
| 1877 } | 2707 } |
| 1878 | 2708 |
| 1879 function contextMenuInGutter(cm, e) { | |
| 1880 if (!hasHandler(cm, "gutterContextMenu")) return false; | |
| 1881 return gutterEvent(cm, e, "gutterContextMenu", false, signal); | |
| 1882 } | |
| 1883 | |
| 1884 function clickInGutter(cm, e) { | 2709 function clickInGutter(cm, e) { |
| 1885 return gutterEvent(cm, e, "gutterClick", true, signalLater); | 2710 return gutterEvent(cm, e, "gutterClick", true, signalLater); |
| 1886 } | 2711 } |
| 1887 | 2712 |
| 1888 // Kludge to work around strange IE behavior where it'll sometimes | 2713 // Kludge to work around strange IE behavior where it'll sometimes |
| 1889 // re-fire a series of drag-related events right after the drop (#1551) | 2714 // re-fire a series of drag-related events right after the drop (#1551) |
| 1890 var lastDrop = 0; | 2715 var lastDrop = 0; |
| 1891 | 2716 |
| 1892 function onDrop(e) { | 2717 function onDrop(e) { |
| 1893 var cm = this; | 2718 var cm = this; |
| 1894 if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e) || (cm.options.onD
ragEvent && cm.options.onDragEvent(cm, addStop(e)))) | 2719 if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) |
| 1895 return; | 2720 return; |
| 1896 e_preventDefault(e); | 2721 e_preventDefault(e); |
| 1897 if (ie) lastDrop = +new Date; | 2722 if (ie_upto10) lastDrop = +new Date; |
| 1898 var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; | 2723 var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; |
| 1899 if (!pos || isReadOnly(cm)) return; | 2724 if (!pos || isReadOnly(cm)) return; |
| 2725 // Might be a file drop, in which case we simply extract the text |
| 2726 // and insert it. |
| 1900 if (files && files.length && window.FileReader && window.File) { | 2727 if (files && files.length && window.FileReader && window.File) { |
| 1901 var n = files.length, text = Array(n), read = 0; | 2728 var n = files.length, text = Array(n), read = 0; |
| 1902 var loadFile = function(file, i) { | 2729 var loadFile = function(file, i) { |
| 1903 var reader = new FileReader; | 2730 var reader = new FileReader; |
| 1904 reader.onload = function() { | 2731 reader.onload = function() { |
| 1905 text[i] = reader.result; | 2732 text[i] = reader.result; |
| 1906 if (++read == n) { | 2733 if (++read == n) { |
| 1907 pos = clipPos(cm.doc, pos); | 2734 pos = clipPos(cm.doc, pos); |
| 1908 makeChange(cm.doc, {from: pos, to: pos, text: splitLines(text.join("
\n")), origin: "paste"}, "around"); | 2735 var change = {from: pos, to: pos, text: splitLines(text.join("\n")),
origin: "paste"}; |
| 2736 makeChange(cm.doc, change); |
| 2737 setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(ch
ange))); |
| 1909 } | 2738 } |
| 1910 }; | 2739 }; |
| 1911 reader.readAsText(file); | 2740 reader.readAsText(file); |
| 1912 }; | 2741 }; |
| 1913 for (var i = 0; i < n; ++i) loadFile(files[i], i); | 2742 for (var i = 0; i < n; ++i) loadFile(files[i], i); |
| 1914 } else { | 2743 } else { // Normal drop |
| 1915 // Don't do a replace if the drop happened inside of the selected text. | 2744 // Don't do a replace if the drop happened inside of the selected text. |
| 1916 if (cm.state.draggingText && !(posLess(pos, cm.doc.sel.from) || posLess(cm
.doc.sel.to, pos))) { | 2745 if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { |
| 1917 cm.state.draggingText(e); | 2746 cm.state.draggingText(e); |
| 1918 // Ensure the editor is re-focused | 2747 // Ensure the editor is re-focused |
| 1919 setTimeout(bind(focusInput, cm), 20); | 2748 setTimeout(bind(focusInput, cm), 20); |
| 1920 return; | 2749 return; |
| 1921 } | 2750 } |
| 1922 try { | 2751 try { |
| 1923 var text = e.dataTransfer.getData("Text"); | 2752 var text = e.dataTransfer.getData("Text"); |
| 1924 if (text) { | 2753 if (text) { |
| 1925 var curFrom = cm.doc.sel.from, curTo = cm.doc.sel.to; | 2754 var selected = cm.state.draggingText && cm.listSelections(); |
| 1926 setSelection(cm.doc, pos, pos); | 2755 setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); |
| 1927 if (cm.state.draggingText) replaceRange(cm.doc, "", curFrom, curTo, "p
aste"); | 2756 if (selected) for (var i = 0; i < selected.length; ++i) |
| 1928 cm.replaceSelection(text, null, "paste"); | 2757 replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag
"); |
| 2758 cm.replaceSelection(text, "around", "paste"); |
| 1929 focusInput(cm); | 2759 focusInput(cm); |
| 1930 } | 2760 } |
| 1931 } | 2761 } |
| 1932 catch(e){} | 2762 catch(e){} |
| 1933 } | 2763 } |
| 1934 } | 2764 } |
| 1935 | 2765 |
| 1936 function onDragStart(cm, e) { | 2766 function onDragStart(cm, e) { |
| 1937 if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e
); return; } | 2767 if (ie_upto10 && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e
_stop(e); return; } |
| 1938 if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return; | 2768 if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return; |
| 1939 | 2769 |
| 1940 var txt = cm.getSelection(); | 2770 e.dataTransfer.setData("Text", cm.getSelection()); |
| 1941 e.dataTransfer.setData("Text", txt); | |
| 1942 | 2771 |
| 1943 // Use dummy image instead of default browsers image. | 2772 // Use dummy image instead of default browsers image. |
| 1944 // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so
we don't do it there. | 2773 // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so
we don't do it there. |
| 1945 if (e.dataTransfer.setDragImage && !safari) { | 2774 if (e.dataTransfer.setDragImage && !safari) { |
| 1946 var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); | 2775 var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); |
| 1947 img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAA
AICTAEAOw=="; | 2776 img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAA
AICTAEAOw=="; |
| 1948 if (opera) { | 2777 if (presto) { |
| 1949 img.width = img.height = 1; | 2778 img.width = img.height = 1; |
| 1950 cm.display.wrapper.appendChild(img); | 2779 cm.display.wrapper.appendChild(img); |
| 1951 // Force a relayout, or Opera won't use our image for some obscure reaso
n | 2780 // Force a relayout, or Opera won't use our image for some obscure reaso
n |
| 1952 img._top = img.offsetTop; | 2781 img._top = img.offsetTop; |
| 1953 } | 2782 } |
| 1954 e.dataTransfer.setDragImage(img, 0, 0); | 2783 e.dataTransfer.setDragImage(img, 0, 0); |
| 1955 if (opera) img.parentNode.removeChild(img); | 2784 if (presto) img.parentNode.removeChild(img); |
| 1956 } | 2785 } |
| 1957 } | 2786 } |
| 1958 | 2787 |
| 2788 // SCROLL EVENTS |
| 2789 |
| 2790 // Sync the scrollable area and scrollbars, ensure the viewport |
| 2791 // covers the visible area. |
| 1959 function setScrollTop(cm, val) { | 2792 function setScrollTop(cm, val) { |
| 1960 if (Math.abs(cm.doc.scrollTop - val) < 2) return; | 2793 if (Math.abs(cm.doc.scrollTop - val) < 2) return; |
| 1961 cm.doc.scrollTop = val; | 2794 cm.doc.scrollTop = val; |
| 1962 if (!gecko) updateDisplay(cm, [], val); | 2795 if (!gecko) updateDisplay(cm, {top: val}); |
| 1963 if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = va
l; | 2796 if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = va
l; |
| 1964 if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop
= val; | 2797 if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop
= val; |
| 1965 if (gecko) updateDisplay(cm, []); | 2798 if (gecko) updateDisplay(cm); |
| 1966 startWorker(cm, 100); | 2799 startWorker(cm, 100); |
| 1967 } | 2800 } |
| 2801 // Sync scroller and scrollbar, ensure the gutter elements are |
| 2802 // aligned. |
| 1968 function setScrollLeft(cm, val, isScroller) { | 2803 function setScrollLeft(cm, val, isScroller) { |
| 1969 if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val
) < 2) return; | 2804 if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val
) < 2) return; |
| 1970 val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.cl
ientWidth); | 2805 val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.cl
ientWidth); |
| 1971 cm.doc.scrollLeft = val; | 2806 cm.doc.scrollLeft = val; |
| 1972 alignHorizontally(cm); | 2807 alignHorizontally(cm); |
| 1973 if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft =
val; | 2808 if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft =
val; |
| 1974 if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLef
t = val; | 2809 if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLef
t = val; |
| 1975 } | 2810 } |
| 1976 | 2811 |
| 1977 // Since the delta values reported on mouse wheel events are | 2812 // Since the delta values reported on mouse wheel events are |
| 1978 // unstandardized between browsers and even browser versions, and | 2813 // unstandardized between browsers and even browser versions, and |
| 1979 // generally horribly unpredictable, this code starts by measuring | 2814 // generally horribly unpredictable, this code starts by measuring |
| 1980 // the scroll effect that the first few mouse wheel events have, | 2815 // the scroll effect that the first few mouse wheel events have, |
| 1981 // and, from that, detects the way it can convert deltas to pixel | 2816 // and, from that, detects the way it can convert deltas to pixel |
| 1982 // offsets afterwards. | 2817 // offsets afterwards. |
| 1983 // | 2818 // |
| 1984 // The reason we want to know the amount a wheel event will scroll | 2819 // The reason we want to know the amount a wheel event will scroll |
| 1985 // is that it gives us a chance to update the display before the | 2820 // is that it gives us a chance to update the display before the |
| 1986 // actual scrolling happens, reducing flickering. | 2821 // actual scrolling happens, reducing flickering. |
| 1987 | 2822 |
| 1988 var wheelSamples = 0, wheelPixelsPerUnit = null; | 2823 var wheelSamples = 0, wheelPixelsPerUnit = null; |
| 1989 // Fill in a browser-detected starting value on browsers where we | 2824 // Fill in a browser-detected starting value on browsers where we |
| 1990 // know one. These don't have to be accurate -- the result of them | 2825 // know one. These don't have to be accurate -- the result of them |
| 1991 // being wrong would just be a slight flicker on the first wheel | 2826 // being wrong would just be a slight flicker on the first wheel |
| 1992 // scroll (if it is large enough). | 2827 // scroll (if it is large enough). |
| 1993 if (old_ie) wheelPixelsPerUnit = -.53; | 2828 if (ie) wheelPixelsPerUnit = -.53; |
| 1994 else if (gecko) wheelPixelsPerUnit = 15; | 2829 else if (gecko) wheelPixelsPerUnit = 15; |
| 1995 else if (chrome) wheelPixelsPerUnit = -.7; | 2830 else if (chrome) wheelPixelsPerUnit = -.7; |
| 1996 else if (safari) wheelPixelsPerUnit = -1/3; | 2831 else if (safari) wheelPixelsPerUnit = -1/3; |
| 1997 | 2832 |
| 1998 function onScrollWheel(cm, e) { | 2833 function onScrollWheel(cm, e) { |
| 1999 var dx = e.wheelDeltaX, dy = e.wheelDeltaY; | 2834 var dx = e.wheelDeltaX, dy = e.wheelDeltaY; |
| 2000 if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; | 2835 if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; |
| 2001 if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; | 2836 if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; |
| 2002 else if (dy == null) dy = e.wheelDelta; | 2837 else if (dy == null) dy = e.wheelDelta; |
| 2003 | 2838 |
| 2004 var display = cm.display, scroll = display.scroller; | 2839 var display = cm.display, scroll = display.scroller; |
| 2005 // Quit if there's nothing to scroll here | 2840 // Quit if there's nothing to scroll here |
| 2006 if (!(dx && scroll.scrollWidth > scroll.clientWidth || | 2841 if (!(dx && scroll.scrollWidth > scroll.clientWidth || |
| 2007 dy && scroll.scrollHeight > scroll.clientHeight)) return; | 2842 dy && scroll.scrollHeight > scroll.clientHeight)) return; |
| 2008 | 2843 |
| 2009 // Webkit browsers on OS X abort momentum scrolls when the target | 2844 // Webkit browsers on OS X abort momentum scrolls when the target |
| 2010 // of the scroll event is removed from the scrollable element. | 2845 // of the scroll event is removed from the scrollable element. |
| 2011 // This hack (see related code in patchDisplay) makes sure the | 2846 // This hack (see related code in patchDisplay) makes sure the |
| 2012 // element is kept around. | 2847 // element is kept around. |
| 2013 if (dy && mac && webkit) { | 2848 if (dy && mac && webkit) { |
| 2014 for (var cur = e.target; cur != scroll; cur = cur.parentNode) { | 2849 outer: for (var cur = e.target, view = display.view; cur != scroll; cur =
cur.parentNode) { |
| 2015 if (cur.lineObj) { | 2850 for (var i = 0; i < view.length; i++) { |
| 2016 cm.display.currentWheelTarget = cur; | 2851 if (view[i].node == cur) { |
| 2017 break; | 2852 cm.display.currentWheelTarget = cur; |
| 2853 break outer; |
| 2854 } |
| 2018 } | 2855 } |
| 2019 } | 2856 } |
| 2020 } | 2857 } |
| 2021 | 2858 |
| 2022 // On some browsers, horizontal scrolling will cause redraws to | 2859 // On some browsers, horizontal scrolling will cause redraws to |
| 2023 // happen before the gutter has been realigned, causing it to | 2860 // happen before the gutter has been realigned, causing it to |
| 2024 // wriggle around in a most unseemly way. When we have an | 2861 // wriggle around in a most unseemly way. When we have an |
| 2025 // estimated pixels/delta value, we just handle horizontal | 2862 // estimated pixels/delta value, we just handle horizontal |
| 2026 // scrolling entirely here. It'll be slightly off from native, but | 2863 // scrolling entirely here. It'll be slightly off from native, but |
| 2027 // better than glitching out. | 2864 // better than glitching out. |
| 2028 if (dx && !gecko && !opera && wheelPixelsPerUnit != null) { | 2865 if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { |
| 2029 if (dy) | 2866 if (dy) |
| 2030 setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixel
sPerUnit, scroll.scrollHeight - scroll.clientHeight))); | 2867 setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixel
sPerUnit, scroll.scrollHeight - scroll.clientHeight))); |
| 2031 setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixel
sPerUnit, scroll.scrollWidth - scroll.clientWidth))); | 2868 setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixel
sPerUnit, scroll.scrollWidth - scroll.clientWidth))); |
| 2032 e_preventDefault(e); | 2869 e_preventDefault(e); |
| 2033 display.wheelStartX = null; // Abort measurement, if in progress | 2870 display.wheelStartX = null; // Abort measurement, if in progress |
| 2034 return; | 2871 return; |
| 2035 } | 2872 } |
| 2036 | 2873 |
| 2874 // 'Project' the visible viewport to cover the area that is being |
| 2875 // scrolled into view (if we know enough to estimate it). |
| 2037 if (dy && wheelPixelsPerUnit != null) { | 2876 if (dy && wheelPixelsPerUnit != null) { |
| 2038 var pixels = dy * wheelPixelsPerUnit; | 2877 var pixels = dy * wheelPixelsPerUnit; |
| 2039 var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; | 2878 var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; |
| 2040 if (pixels < 0) top = Math.max(0, top + pixels - 50); | 2879 if (pixels < 0) top = Math.max(0, top + pixels - 50); |
| 2041 else bot = Math.min(cm.doc.height, bot + pixels + 50); | 2880 else bot = Math.min(cm.doc.height, bot + pixels + 50); |
| 2042 updateDisplay(cm, [], {top: top, bottom: bot}); | 2881 updateDisplay(cm, {top: top, bottom: bot}); |
| 2043 } | 2882 } |
| 2044 | 2883 |
| 2045 if (wheelSamples < 20) { | 2884 if (wheelSamples < 20) { |
| 2046 if (display.wheelStartX == null) { | 2885 if (display.wheelStartX == null) { |
| 2047 display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.sc
rollTop; | 2886 display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.sc
rollTop; |
| 2048 display.wheelDX = dx; display.wheelDY = dy; | 2887 display.wheelDX = dx; display.wheelDY = dy; |
| 2049 setTimeout(function() { | 2888 setTimeout(function() { |
| 2050 if (display.wheelStartX == null) return; | 2889 if (display.wheelStartX == null) return; |
| 2051 var movedX = scroll.scrollLeft - display.wheelStartX; | 2890 var movedX = scroll.scrollLeft - display.wheelStartX; |
| 2052 var movedY = scroll.scrollTop - display.wheelStartY; | 2891 var movedY = scroll.scrollTop - display.wheelStartY; |
| 2053 var sample = (movedY && display.wheelDY && movedY / display.wheelDY) |
| | 2892 var sample = (movedY && display.wheelDY && movedY / display.wheelDY) |
| |
| 2054 (movedX && display.wheelDX && movedX / display.wheelDX); | 2893 (movedX && display.wheelDX && movedX / display.wheelDX); |
| 2055 display.wheelStartX = display.wheelStartY = null; | 2894 display.wheelStartX = display.wheelStartY = null; |
| 2056 if (!sample) return; | 2895 if (!sample) return; |
| 2057 wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (w
heelSamples + 1); | 2896 wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (w
heelSamples + 1); |
| 2058 ++wheelSamples; | 2897 ++wheelSamples; |
| 2059 }, 200); | 2898 }, 200); |
| 2060 } else { | 2899 } else { |
| 2061 display.wheelDX += dx; display.wheelDY += dy; | 2900 display.wheelDX += dx; display.wheelDY += dy; |
| 2062 } | 2901 } |
| 2063 } | 2902 } |
| 2064 } | 2903 } |
| 2065 | 2904 |
| 2905 // KEY EVENTS |
| 2906 |
| 2907 // Run a handler that was bound to a key. |
| 2066 function doHandleBinding(cm, bound, dropShift) { | 2908 function doHandleBinding(cm, bound, dropShift) { |
| 2067 if (typeof bound == "string") { | 2909 if (typeof bound == "string") { |
| 2068 bound = commands[bound]; | 2910 bound = commands[bound]; |
| 2069 if (!bound) return false; | 2911 if (!bound) return false; |
| 2070 } | 2912 } |
| 2071 // Ensure previous input has been read, so that the handler sees a | 2913 // Ensure previous input has been read, so that the handler sees a |
| 2072 // consistent view of the document | 2914 // consistent view of the document |
| 2073 if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false; | 2915 if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false; |
| 2074 var doc = cm.doc, prevShift = doc.sel.shift, done = false; | 2916 var prevShift = cm.display.shift, done = false; |
| 2075 try { | 2917 try { |
| 2076 if (isReadOnly(cm)) cm.state.suppressEdits = true; | 2918 if (isReadOnly(cm)) cm.state.suppressEdits = true; |
| 2077 if (dropShift) doc.sel.shift = false; | 2919 if (dropShift) cm.display.shift = false; |
| 2078 done = bound(cm) != Pass; | 2920 done = bound(cm) != Pass; |
| 2079 } finally { | 2921 } finally { |
| 2080 doc.sel.shift = prevShift; | 2922 cm.display.shift = prevShift; |
| 2081 cm.state.suppressEdits = false; | 2923 cm.state.suppressEdits = false; |
| 2082 } | 2924 } |
| 2083 return done; | 2925 return done; |
| 2084 } | 2926 } |
| 2085 | 2927 |
| 2928 // Collect the currently active keymaps. |
| 2086 function allKeyMaps(cm) { | 2929 function allKeyMaps(cm) { |
| 2087 var maps = cm.state.keyMaps.slice(0); | 2930 var maps = cm.state.keyMaps.slice(0); |
| 2088 if (cm.options.extraKeys) maps.push(cm.options.extraKeys); | 2931 if (cm.options.extraKeys) maps.push(cm.options.extraKeys); |
| 2089 maps.push(cm.options.keyMap); | 2932 maps.push(cm.options.keyMap); |
| 2090 return maps; | 2933 return maps; |
| 2091 } | 2934 } |
| 2092 | 2935 |
| 2093 var maybeTransition; | 2936 var maybeTransition; |
| 2937 // Handle a key from the keydown event. |
| 2094 function handleKeyBinding(cm, e) { | 2938 function handleKeyBinding(cm, e) { |
| 2095 // Handle auto keymap transitions | 2939 // Handle automatic keymap transitions |
| 2096 var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto; | 2940 var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto; |
| 2097 clearTimeout(maybeTransition); | 2941 clearTimeout(maybeTransition); |
| 2098 if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() { | 2942 if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() { |
| 2099 if (getKeyMap(cm.options.keyMap) == startMap) { | 2943 if (getKeyMap(cm.options.keyMap) == startMap) { |
| 2100 cm.options.keyMap = (next.call ? next.call(null, cm) : next); | 2944 cm.options.keyMap = (next.call ? next.call(null, cm) : next); |
| 2101 keyMapChanged(cm); | 2945 keyMapChanged(cm); |
| 2102 } | 2946 } |
| 2103 }, 50); | 2947 }, 50); |
| 2104 | 2948 |
| 2105 var name = keyName(e, true), handled = false; | 2949 var name = keyName(e, true), handled = false; |
| 2106 if (!name) return false; | 2950 if (!name) return false; |
| 2107 var keymaps = allKeyMaps(cm); | 2951 var keymaps = allKeyMaps(cm); |
| 2108 | 2952 |
| 2109 if (e.shiftKey) { | 2953 if (e.shiftKey) { |
| 2110 // First try to resolve full name (including 'Shift-'). Failing | 2954 // First try to resolve full name (including 'Shift-'). Failing |
| 2111 // that, see if there is a cursor-motion command (starting with | 2955 // that, see if there is a cursor-motion command (starting with |
| 2112 // 'go') bound to the keyname without 'Shift-'. | 2956 // 'go') bound to the keyname without 'Shift-'. |
| 2113 handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandle
Binding(cm, b, true);}) | 2957 handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandle
Binding(cm, b, true);}) |
| 2114 || lookupKey(name, keymaps, function(b) { | 2958 || lookupKey(name, keymaps, function(b) { |
| 2115 if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) | 2959 if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) |
| 2116 return doHandleBinding(cm, b); | 2960 return doHandleBinding(cm, b); |
| 2117 }); | 2961 }); |
| 2118 } else { | 2962 } else { |
| 2119 handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm
, b); }); | 2963 handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm
, b); }); |
| 2120 } | 2964 } |
| 2121 | 2965 |
| 2122 if (handled) { | 2966 if (handled) { |
| 2123 e_preventDefault(e); | 2967 e_preventDefault(e); |
| 2124 restartBlink(cm); | 2968 restartBlink(cm); |
| 2125 if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; } | |
| 2126 signalLater(cm, "keyHandled", cm, name, e); | 2969 signalLater(cm, "keyHandled", cm, name, e); |
| 2127 } | 2970 } |
| 2128 return handled; | 2971 return handled; |
| 2129 } | 2972 } |
| 2130 | 2973 |
| 2974 // Handle a key from the keypress event |
| 2131 function handleCharBinding(cm, e, ch) { | 2975 function handleCharBinding(cm, e, ch) { |
| 2132 var handled = lookupKey("'" + ch + "'", allKeyMaps(cm), | 2976 var handled = lookupKey("'" + ch + "'", allKeyMaps(cm), |
| 2133 function(b) { return doHandleBinding(cm, b, true); }
); | 2977 function(b) { return doHandleBinding(cm, b, true); }
); |
| 2134 if (handled) { | 2978 if (handled) { |
| 2135 e_preventDefault(e); | 2979 e_preventDefault(e); |
| 2136 restartBlink(cm); | 2980 restartBlink(cm); |
| 2137 signalLater(cm, "keyHandled", cm, "'" + ch + "'", e); | 2981 signalLater(cm, "keyHandled", cm, "'" + ch + "'", e); |
| 2138 } | 2982 } |
| 2139 return handled; | 2983 return handled; |
| 2140 } | 2984 } |
| 2141 | 2985 |
| 2142 function onKeyUp(e) { | |
| 2143 var cm = this; | |
| 2144 if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(
cm, addStop(e))) return; | |
| 2145 if (e.keyCode == 16) cm.doc.sel.shift = false; | |
| 2146 } | |
| 2147 | |
| 2148 var lastStoppedKey = null; | 2986 var lastStoppedKey = null; |
| 2149 function onKeyDown(e) { | 2987 function onKeyDown(e) { |
| 2150 var cm = this; | 2988 var cm = this; |
| 2151 if (!cm.state.focused) onFocus(cm); | 2989 ensureFocus(cm); |
| 2152 if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(
cm, addStop(e))) return; | 2990 if (signalDOMEvent(cm, e)) return; |
| 2153 if (old_ie && e.keyCode == 27) e.returnValue = false; | 2991 // IE does strange things with escape. |
| 2992 if (ie_upto10 && e.keyCode == 27) e.returnValue = false; |
| 2154 var code = e.keyCode; | 2993 var code = e.keyCode; |
| 2155 // IE does strange things with escape. | 2994 cm.display.shift = code == 16 || e.shiftKey; |
| 2156 cm.doc.sel.shift = code == 16 || e.shiftKey; | |
| 2157 // First give onKeyEvent option a chance to handle this. | |
| 2158 var handled = handleKeyBinding(cm, e); | 2995 var handled = handleKeyBinding(cm, e); |
| 2159 if (opera) { | 2996 if (presto) { |
| 2160 lastStoppedKey = handled ? code : null; | 2997 lastStoppedKey = handled ? code : null; |
| 2161 // Opera has no cut event... we try to at least catch the key combo | 2998 // Opera has no cut event... we try to at least catch the key combo |
| 2162 if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKe
y)) | 2999 if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKe
y)) |
| 2163 cm.replaceSelection(""); | 3000 cm.replaceSelection("", null, "cut"); |
| 2164 } | 3001 } |
| 2165 } | 3002 } |
| 2166 | 3003 |
| 3004 function onKeyUp(e) { |
| 3005 if (signalDOMEvent(this, e)) return; |
| 3006 if (e.keyCode == 16) this.doc.sel.shift = false; |
| 3007 } |
| 3008 |
| 2167 function onKeyPress(e) { | 3009 function onKeyPress(e) { |
| 2168 var cm = this; | 3010 var cm = this; |
| 2169 if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(
cm, addStop(e))) return; | 3011 if (signalDOMEvent(cm, e)) return; |
| 2170 var keyCode = e.keyCode, charCode = e.charCode; | 3012 var keyCode = e.keyCode, charCode = e.charCode; |
| 2171 if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDef
ault(e); return;} | 3013 if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDe
fault(e); return;} |
| 2172 if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm,
e)) return; | 3014 if (((presto && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm
, e)) return; |
| 2173 var ch = String.fromCharCode(charCode == null ? keyCode : charCode); | 3015 var ch = String.fromCharCode(charCode == null ? keyCode : charCode); |
| 2174 if (handleCharBinding(cm, e, ch)) return; | 3016 if (handleCharBinding(cm, e, ch)) return; |
| 2175 if (ie && !ie_lt9) cm.display.inputHasSelection = null; | 3017 if (ie && !ie_upto8) cm.display.inputHasSelection = null; |
| 2176 fastPoll(cm); | 3018 fastPoll(cm); |
| 2177 } | 3019 } |
| 2178 | 3020 |
| 3021 // FOCUS/BLUR EVENTS |
| 3022 |
| 2179 function onFocus(cm) { | 3023 function onFocus(cm) { |
| 2180 if (cm.options.readOnly == "nocursor") return; | 3024 if (cm.options.readOnly == "nocursor") return; |
| 2181 if (!cm.state.focused) { | 3025 if (!cm.state.focused) { |
| 2182 signal(cm, "focus", cm); | 3026 signal(cm, "focus", cm); |
| 2183 cm.state.focused = true; | 3027 cm.state.focused = true; |
| 2184 if (cm.display.wrapper.className.search(/\bCodeMirror-focused\b/) == -1) | 3028 if (cm.display.wrapper.className.search(/\bCodeMirror-focused\b/) == -1) |
| 2185 cm.display.wrapper.className += " CodeMirror-focused"; | 3029 cm.display.wrapper.className += " CodeMirror-focused"; |
| 2186 if (!cm.curOp) { | 3030 if (!cm.curOp) { |
| 2187 resetInput(cm, true); | 3031 resetInput(cm); |
| 2188 if (webkit) setTimeout(bind(resetInput, cm, true), 0); // Issue #1730 | 3032 if (webkit) setTimeout(bind(resetInput, cm, true), 0); // Issue #1730 |
| 2189 } | 3033 } |
| 2190 } | 3034 } |
| 2191 slowPoll(cm); | 3035 slowPoll(cm); |
| 2192 restartBlink(cm); | 3036 restartBlink(cm); |
| 2193 } | 3037 } |
| 2194 function onBlur(cm) { | 3038 function onBlur(cm) { |
| 2195 if (cm.state.focused) { | 3039 if (cm.state.focused) { |
| 2196 signal(cm, "blur", cm); | 3040 signal(cm, "blur", cm); |
| 2197 cm.state.focused = false; | 3041 cm.state.focused = false; |
| 2198 cm.display.wrapper.className = cm.display.wrapper.className.replace(" Code
Mirror-focused", ""); | 3042 cm.display.wrapper.className = cm.display.wrapper.className.replace(" Code
Mirror-focused", ""); |
| 2199 } | 3043 } |
| 2200 clearInterval(cm.display.blinker); | 3044 clearInterval(cm.display.blinker); |
| 2201 setTimeout(function() {if (!cm.state.focused) cm.doc.sel.shift = false;}, 15
0); | 3045 setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 15
0); |
| 2202 } | 3046 } |
| 2203 | 3047 |
| 3048 // CONTEXT MENU HANDLING |
| 3049 |
| 2204 var detectingSelectAll; | 3050 var detectingSelectAll; |
| 3051 // To make the context menu work, we need to briefly unhide the |
| 3052 // textarea (making it as unobtrusive as possible) to let the |
| 3053 // right-click take effect on it. |
| 2205 function onContextMenu(cm, e) { | 3054 function onContextMenu(cm, e) { |
| 2206 if (signalDOMEvent(cm, e, "contextmenu")) return; | 3055 if (signalDOMEvent(cm, e, "contextmenu")) return; |
| 2207 var display = cm.display, sel = cm.doc.sel; | 3056 var display = cm.display; |
| 2208 if (eventInWidget(display, e) || contextMenuInGutter(cm, e)) return; | 3057 if (eventInWidget(display, e) || contextMenuInGutter(cm, e)) return; |
| 2209 | 3058 |
| 2210 var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; | 3059 var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; |
| 2211 if (!pos || opera) return; // Opera is difficult. | 3060 if (!pos || presto) return; // Opera is difficult. |
| 2212 | 3061 |
| 2213 // Reset the current text selection only if the click is done outside of the
selection | 3062 // Reset the current text selection only if the click is done outside of the
selection |
| 2214 // and 'resetSelectionOnContextMenu' option is true. | 3063 // and 'resetSelectionOnContextMenu' option is true. |
| 2215 var reset = cm.options.resetSelectionOnContextMenu; | 3064 var reset = cm.options.resetSelectionOnContextMenu; |
| 2216 if (reset && (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(
pos, sel.to))) | 3065 if (reset && cm.doc.sel.contains(pos) == -1) |
| 2217 operation(cm, setSelection)(cm.doc, pos, pos); | 3066 operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); |
| 2218 | 3067 |
| 2219 var oldCSS = display.input.style.cssText; | 3068 var oldCSS = display.input.style.cssText; |
| 2220 display.inputDiv.style.position = "absolute"; | 3069 display.inputDiv.style.position = "absolute"; |
| 2221 display.input.style.cssText = "position: fixed; width: 30px; height: 30px; t
op: " + (e.clientY - 5) + | 3070 display.input.style.cssText = "position: fixed; width: 30px; height: 30px; t
op: " + (e.clientY - 5) + |
| 2222 "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: transpare
nt; outline: none;" + | 3071 "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " + |
| 2223 "border-width: 0; outline: none; overflow: hidden; opacity: .05; -ms-opaci
ty: .05; filter: alpha(opacity=5);"; | 3072 (ie ? "rgba(255, 255, 255, .05)" : "transparent") + |
| 3073 "; outline: none; border-width: 0; outline: none; overflow: hidden; opacit
y: .05; filter: alpha(opacity=5);"; |
| 2224 focusInput(cm); | 3074 focusInput(cm); |
| 2225 resetInput(cm, true); | 3075 resetInput(cm); |
| 2226 // Adds "Select all" to context menu in FF | 3076 // Adds "Select all" to context menu in FF |
| 2227 if (posEq(sel.from, sel.to)) display.input.value = display.prevInput = " "; | 3077 if (!cm.somethingSelected()) display.input.value = display.prevInput = " "; |
| 2228 | 3078 |
| 3079 // Select-all will be greyed out if there's nothing to select, so |
| 3080 // this adds a zero-width space so that we can later check whether |
| 3081 // it got selected. |
| 2229 function prepareSelectAllHack() { | 3082 function prepareSelectAllHack() { |
| 2230 if (display.input.selectionStart != null) { | 3083 if (display.input.selectionStart != null) { |
| 2231 var extval = display.input.value = "\u200b" + (posEq(sel.from, sel.to) ?
"" : display.input.value); | 3084 var extval = display.input.value = "\u200b" + (cm.somethingSelected() ?
display.input.value : ""); |
| 2232 display.prevInput = "\u200b"; | 3085 display.prevInput = "\u200b"; |
| 2233 display.input.selectionStart = 1; display.input.selectionEnd = extval.le
ngth; | 3086 display.input.selectionStart = 1; display.input.selectionEnd = extval.le
ngth; |
| 2234 } | 3087 } |
| 2235 } | 3088 } |
| 2236 function rehide() { | 3089 function rehide() { |
| 2237 display.inputDiv.style.position = "relative"; | 3090 display.inputDiv.style.position = "relative"; |
| 2238 display.input.style.cssText = oldCSS; | 3091 display.input.style.cssText = oldCSS; |
| 2239 if (ie_lt9) display.scrollbarV.scrollTop = display.scroller.scrollTop = sc
rollPos; | 3092 if (ie_upto8) display.scrollbarV.scrollTop = display.scroller.scrollTop =
scrollPos; |
| 2240 slowPoll(cm); | 3093 slowPoll(cm); |
| 2241 | 3094 |
| 2242 // Try to detect the user choosing select-all | 3095 // Try to detect the user choosing select-all |
| 2243 if (display.input.selectionStart != null) { | 3096 if (display.input.selectionStart != null) { |
| 2244 if (!old_ie || ie_lt9) prepareSelectAllHack(); | 3097 if (!ie || ie_upto8) prepareSelectAllHack(); |
| 2245 clearTimeout(detectingSelectAll); | 3098 clearTimeout(detectingSelectAll); |
| 2246 var i = 0, poll = function(){ | 3099 var i = 0, poll = function(){ |
| 2247 if (display.prevInput == "\u200b" && display.input.selectionStart == 0
) | 3100 if (display.prevInput == "\u200b" && display.input.selectionStart == 0
) |
| 2248 operation(cm, commands.selectAll)(cm); | 3101 operation(cm, commands.selectAll)(cm); |
| 2249 else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500); | 3102 else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500); |
| 2250 else resetInput(cm); | 3103 else resetInput(cm); |
| 2251 }; | 3104 }; |
| 2252 detectingSelectAll = setTimeout(poll, 200); | 3105 detectingSelectAll = setTimeout(poll, 200); |
| 2253 } | 3106 } |
| 2254 } | 3107 } |
| 2255 | 3108 |
| 2256 if (old_ie && !ie_lt9) prepareSelectAllHack(); | 3109 if (ie && !ie_upto8) prepareSelectAllHack(); |
| 2257 if (captureMiddleClick) { | 3110 if (captureRightClick) { |
| 2258 e_stop(e); | 3111 e_stop(e); |
| 2259 var mouseup = function() { | 3112 var mouseup = function() { |
| 2260 off(window, "mouseup", mouseup); | 3113 off(window, "mouseup", mouseup); |
| 2261 setTimeout(rehide, 20); | 3114 setTimeout(rehide, 20); |
| 2262 }; | 3115 }; |
| 2263 on(window, "mouseup", mouseup); | 3116 on(window, "mouseup", mouseup); |
| 2264 } else { | 3117 } else { |
| 2265 setTimeout(rehide, 50); | 3118 setTimeout(rehide, 50); |
| 2266 } | 3119 } |
| 2267 } | 3120 } |
| 2268 | 3121 |
| 3122 function contextMenuInGutter(cm, e) { |
| 3123 if (!hasHandler(cm, "gutterContextMenu")) return false; |
| 3124 return gutterEvent(cm, e, "gutterContextMenu", false, signal); |
| 3125 } |
| 3126 |
| 2269 // UPDATING | 3127 // UPDATING |
| 2270 | 3128 |
| 3129 // Compute the position of the end of a change (its 'to' property |
| 3130 // refers to the pre-change end). |
| 2271 var changeEnd = CodeMirror.changeEnd = function(change) { | 3131 var changeEnd = CodeMirror.changeEnd = function(change) { |
| 2272 if (!change.text) return change.to; | 3132 if (!change.text) return change.to; |
| 2273 return Pos(change.from.line + change.text.length - 1, | 3133 return Pos(change.from.line + change.text.length - 1, |
| 2274 lst(change.text).length + (change.text.length == 1 ? change.from.
ch : 0)); | 3134 lst(change.text).length + (change.text.length == 1 ? change.from.
ch : 0)); |
| 2275 }; | 3135 }; |
| 2276 | 3136 |
| 2277 // Make sure a position will be valid after the given change. | 3137 // Adjust a position to refer to the post-change position of the |
| 2278 function clipPostChange(doc, change, pos) { | 3138 // same text, or the end of the change if the change covers it. |
| 2279 if (!posLess(change.from, pos)) return clipPos(doc, pos); | 3139 function adjustForChange(pos, change) { |
| 2280 var diff = (change.text.length - 1) - (change.to.line - change.from.line); | 3140 if (cmp(pos, change.from) < 0) return pos; |
| 2281 if (pos.line > change.to.line + diff) { | 3141 if (cmp(pos, change.to) <= 0) return changeEnd(change); |
| 2282 var preLine = pos.line - diff, lastLine = doc.first + doc.size - 1; | 3142 |
| 2283 if (preLine > lastLine) return Pos(lastLine, getLine(doc, lastLine).text.l
ength); | 3143 var line = pos.line + change.text.length - (change.to.line - change.from.lin
e) - 1, ch = pos.ch; |
| 2284 return clipToLen(pos, getLine(doc, preLine).text.length); | 3144 if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch; |
| 2285 } | 3145 return Pos(line, ch); |
| 2286 if (pos.line == change.to.line + diff) | |
| 2287 return clipToLen(pos, lst(change.text).length + (change.text.length == 1 ?
change.from.ch : 0) + | |
| 2288 getLine(doc, change.to.line).text.length - change.to.ch); | |
| 2289 var inside = pos.line - change.from.line; | |
| 2290 return clipToLen(pos, change.text[inside].length + (inside ? 0 : change.from
.ch)); | |
| 2291 } | 3146 } |
| 2292 | 3147 |
| 2293 // Hint can be null|"end"|"start"|"around"|{anchor,head} | 3148 function computeSelAfterChange(doc, change) { |
| 2294 function computeSelAfterChange(doc, change, hint) { | 3149 var out = []; |
| 2295 if (hint && typeof hint == "object") // Assumed to be {anchor, head} object | 3150 for (var i = 0; i < doc.sel.ranges.length; i++) { |
| 2296 return {anchor: clipPostChange(doc, change, hint.anchor), | 3151 var range = doc.sel.ranges[i]; |
| 2297 head: clipPostChange(doc, change, hint.head)}; | 3152 out.push(new Range(adjustForChange(range.anchor, change), |
| 2298 | 3153 adjustForChange(range.head, change))); |
| 2299 if (hint == "start") return {anchor: change.from, head: change.from}; | 3154 } |
| 2300 | 3155 return normalizeSelection(out, doc.sel.primIndex); |
| 2301 var end = changeEnd(change); | |
| 2302 if (hint == "around") return {anchor: change.from, head: end}; | |
| 2303 if (hint == "end") return {anchor: end, head: end}; | |
| 2304 | |
| 2305 // hint is null, leave the selection alone as much as possible | |
| 2306 var adjustPos = function(pos) { | |
| 2307 if (posLess(pos, change.from)) return pos; | |
| 2308 if (!posLess(change.to, pos)) return end; | |
| 2309 | |
| 2310 var line = pos.line + change.text.length - (change.to.line - change.from.l
ine) - 1, ch = pos.ch; | |
| 2311 if (pos.line == change.to.line) ch += end.ch - change.to.ch; | |
| 2312 return Pos(line, ch); | |
| 2313 }; | |
| 2314 return {anchor: adjustPos(doc.sel.anchor), head: adjustPos(doc.sel.head)}; | |
| 2315 } | 3156 } |
| 2316 | 3157 |
| 3158 function offsetPos(pos, old, nw) { |
| 3159 if (pos.line == old.line) |
| 3160 return Pos(nw.line, pos.ch - old.ch + nw.ch); |
| 3161 else |
| 3162 return Pos(nw.line + (pos.line - old.line), pos.ch); |
| 3163 } |
| 3164 |
| 3165 // Used by replaceSelections to allow moving the selection to the |
| 3166 // start or around the replaced test. Hint may be "start" or "around". |
| 3167 function computeReplacedSel(doc, changes, hint) { |
| 3168 var out = []; |
| 3169 var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; |
| 3170 for (var i = 0; i < changes.length; i++) { |
| 3171 var change = changes[i]; |
| 3172 var from = offsetPos(change.from, oldPrev, newPrev); |
| 3173 var to = offsetPos(changeEnd(change), oldPrev, newPrev); |
| 3174 oldPrev = change.to; |
| 3175 newPrev = to; |
| 3176 if (hint == "around") { |
| 3177 var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; |
| 3178 out[i] = new Range(inv ? to : from, inv ? from : to); |
| 3179 } else { |
| 3180 out[i] = new Range(from, from); |
| 3181 } |
| 3182 } |
| 3183 return new Selection(out, doc.sel.primIndex); |
| 3184 } |
| 3185 |
| 3186 // Allow "beforeChange" event handlers to influence a change |
| 2317 function filterChange(doc, change, update) { | 3187 function filterChange(doc, change, update) { |
| 2318 var obj = { | 3188 var obj = { |
| 2319 canceled: false, | 3189 canceled: false, |
| 2320 from: change.from, | 3190 from: change.from, |
| 2321 to: change.to, | 3191 to: change.to, |
| 2322 text: change.text, | 3192 text: change.text, |
| 2323 origin: change.origin, | 3193 origin: change.origin, |
| 2324 cancel: function() { this.canceled = true; } | 3194 cancel: function() { this.canceled = true; } |
| 2325 }; | 3195 }; |
| 2326 if (update) obj.update = function(from, to, text, origin) { | 3196 if (update) obj.update = function(from, to, text, origin) { |
| 2327 if (from) this.from = clipPos(doc, from); | 3197 if (from) this.from = clipPos(doc, from); |
| 2328 if (to) this.to = clipPos(doc, to); | 3198 if (to) this.to = clipPos(doc, to); |
| 2329 if (text) this.text = text; | 3199 if (text) this.text = text; |
| 2330 if (origin !== undefined) this.origin = origin; | 3200 if (origin !== undefined) this.origin = origin; |
| 2331 }; | 3201 }; |
| 2332 signal(doc, "beforeChange", doc, obj); | 3202 signal(doc, "beforeChange", doc, obj); |
| 2333 if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj); | 3203 if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj); |
| 2334 | 3204 |
| 2335 if (obj.canceled) return null; | 3205 if (obj.canceled) return null; |
| 2336 return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}; | 3206 return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}; |
| 2337 } | 3207 } |
| 2338 | 3208 |
| 2339 // Replace the range from from to to by the strings in replacement. | 3209 // Apply a change to a document, and add it to the document's |
| 2340 // change is a {from, to, text [, origin]} object | 3210 // history, and propagating it to all linked documents. |
| 2341 function makeChange(doc, change, selUpdate, ignoreReadOnly) { | 3211 function makeChange(doc, change, ignoreReadOnly) { |
| 2342 if (doc.cm) { | 3212 if (doc.cm) { |
| 2343 if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, selUp
date, ignoreReadOnly); | 3213 if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignor
eReadOnly); |
| 2344 if (doc.cm.state.suppressEdits) return; | 3214 if (doc.cm.state.suppressEdits) return; |
| 2345 } | 3215 } |
| 2346 | 3216 |
| 2347 if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeC
hange")) { | 3217 if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeC
hange")) { |
| 2348 change = filterChange(doc, change, true); | 3218 change = filterChange(doc, change, true); |
| 2349 if (!change) return; | 3219 if (!change) return; |
| 2350 } | 3220 } |
| 2351 | 3221 |
| 2352 // Possibly split or suppress the update based on the presence | 3222 // Possibly split or suppress the update based on the presence |
| 2353 // of read-only spans in its range. | 3223 // of read-only spans in its range. |
| 2354 var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc,
change.from, change.to); | 3224 var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc,
change.from, change.to); |
| 2355 if (split) { | 3225 if (split) { |
| 2356 for (var i = split.length - 1; i >= 1; --i) | 3226 for (var i = split.length - 1; i >= 0; --i) |
| 2357 makeChangeNoReadonly(doc, {from: split[i].from, to: split[i].to, text: [
""]}); | 3227 makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? ["
"] : change.text}); |
| 2358 if (split.length) | |
| 2359 makeChangeNoReadonly(doc, {from: split[0].from, to: split[0].to, text: c
hange.text}, selUpdate); | |
| 2360 } else { | 3228 } else { |
| 2361 makeChangeNoReadonly(doc, change, selUpdate); | 3229 makeChangeInner(doc, change); |
| 2362 } | 3230 } |
| 2363 } | 3231 } |
| 2364 | 3232 |
| 2365 function makeChangeNoReadonly(doc, change, selUpdate) { | 3233 function makeChangeInner(doc, change) { |
| 2366 if (change.text.length == 1 && change.text[0] == "" && posEq(change.from, ch
ange.to)) return; | 3234 if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, chan
ge.to) == 0) return; |
| 2367 var selAfter = computeSelAfterChange(doc, change, selUpdate); | 3235 var selAfter = computeSelAfterChange(doc, change); |
| 2368 addToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); | 3236 addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); |
| 2369 | 3237 |
| 2370 makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, chang
e)); | 3238 makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, chang
e)); |
| 2371 var rebased = []; | 3239 var rebased = []; |
| 2372 | 3240 |
| 2373 linkedDocs(doc, function(doc, sharedHist) { | 3241 linkedDocs(doc, function(doc, sharedHist) { |
| 2374 if (!sharedHist && indexOf(rebased, doc.history) == -1) { | 3242 if (!sharedHist && indexOf(rebased, doc.history) == -1) { |
| 2375 rebaseHist(doc.history, change); | 3243 rebaseHist(doc.history, change); |
| 2376 rebased.push(doc.history); | 3244 rebased.push(doc.history); |
| 2377 } | 3245 } |
| 2378 makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)
); | 3246 makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)
); |
| 2379 }); | 3247 }); |
| 2380 } | 3248 } |
| 2381 | 3249 |
| 2382 function makeChangeFromHistory(doc, type) { | 3250 // Revert a change stored in a document's history. |
| 3251 function makeChangeFromHistory(doc, type, allowSelectionOnly) { |
| 2383 if (doc.cm && doc.cm.state.suppressEdits) return; | 3252 if (doc.cm && doc.cm.state.suppressEdits) return; |
| 2384 | 3253 |
| 2385 var hist = doc.history; | 3254 var hist = doc.history, event, selAfter = doc.sel; |
| 2386 var event = (type == "undo" ? hist.done : hist.undone).pop(); | 3255 var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo"
? hist.undone : hist.done; |
| 2387 if (!event) return; | |
| 2388 | 3256 |
| 2389 var anti = {changes: [], anchorBefore: event.anchorAfter, headBefore: event.
headAfter, | 3257 // Verify that there is a useable event (so that ctrl-z won't |
| 2390 anchorAfter: event.anchorBefore, headAfter: event.headBefore, | 3258 // needlessly clear selection events) |
| 2391 generation: hist.generation}; | 3259 for (var i = 0; i < source.length; i++) { |
| 2392 (type == "undo" ? hist.undone : hist.done).push(anti); | 3260 event = source[i]; |
| 3261 if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.r
anges) |
| 3262 break; |
| 3263 } |
| 3264 if (i == source.length) return; |
| 3265 hist.lastOrigin = hist.lastSelOrigin = null; |
| 3266 |
| 3267 for (;;) { |
| 3268 event = source.pop(); |
| 3269 if (event.ranges) { |
| 3270 pushSelectionToHistory(event, dest); |
| 3271 if (allowSelectionOnly && !event.equals(doc.sel)) { |
| 3272 setSelection(doc, event, {clearRedo: false}); |
| 3273 return; |
| 3274 } |
| 3275 selAfter = event; |
| 3276 } |
| 3277 else break; |
| 3278 } |
| 3279 |
| 3280 // Build up a reverse change object to add to the opposite history |
| 3281 // stack (redo when undoing, and vice versa). |
| 3282 var antiChanges = []; |
| 3283 pushSelectionToHistory(selAfter, dest); |
| 3284 dest.push({changes: antiChanges, generation: hist.generation}); |
| 2393 hist.generation = event.generation || ++hist.maxGeneration; | 3285 hist.generation = event.generation || ++hist.maxGeneration; |
| 2394 | 3286 |
| 2395 var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm,
"beforeChange"); | 3287 var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm,
"beforeChange"); |
| 2396 | 3288 |
| 2397 for (var i = event.changes.length - 1; i >= 0; --i) { | 3289 for (var i = event.changes.length - 1; i >= 0; --i) { |
| 2398 var change = event.changes[i]; | 3290 var change = event.changes[i]; |
| 2399 change.origin = type; | 3291 change.origin = type; |
| 2400 if (filter && !filterChange(doc, change, false)) { | 3292 if (filter && !filterChange(doc, change, false)) { |
| 2401 (type == "undo" ? hist.done : hist.undone).length = 0; | 3293 source.length = 0; |
| 2402 return; | 3294 return; |
| 2403 } | 3295 } |
| 2404 | 3296 |
| 2405 anti.changes.push(historyChangeFromChange(doc, change)); | 3297 antiChanges.push(historyChangeFromChange(doc, change)); |
| 2406 | 3298 |
| 2407 var after = i ? computeSelAfterChange(doc, change, null) | 3299 var after = i ? computeSelAfterChange(doc, change, null) : lst(source); |
| 2408 : {anchor: event.anchorBefore, head: event.headBefore}; | |
| 2409 makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); | 3300 makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); |
| 3301 if (doc.cm) ensureCursorVisible(doc.cm); |
| 2410 var rebased = []; | 3302 var rebased = []; |
| 2411 | 3303 |
| 3304 // Propagate to the linked documents |
| 2412 linkedDocs(doc, function(doc, sharedHist) { | 3305 linkedDocs(doc, function(doc, sharedHist) { |
| 2413 if (!sharedHist && indexOf(rebased, doc.history) == -1) { | 3306 if (!sharedHist && indexOf(rebased, doc.history) == -1) { |
| 2414 rebaseHist(doc.history, change); | 3307 rebaseHist(doc.history, change); |
| 2415 rebased.push(doc.history); | 3308 rebased.push(doc.history); |
| 2416 } | 3309 } |
| 2417 makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); | 3310 makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); |
| 2418 }); | 3311 }); |
| 2419 } | 3312 } |
| 2420 } | 3313 } |
| 2421 | 3314 |
| 3315 // Sub-views need their line numbers shifted when text is added |
| 3316 // above or below them in the parent document. |
| 2422 function shiftDoc(doc, distance) { | 3317 function shiftDoc(doc, distance) { |
| 2423 function shiftPos(pos) {return Pos(pos.line + distance, pos.ch);} | |
| 2424 doc.first += distance; | 3318 doc.first += distance; |
| 2425 if (doc.cm) regChange(doc.cm, doc.first, doc.first, distance); | 3319 doc.sel = new Selection(map(doc.sel.ranges, function(range) { |
| 2426 doc.sel.head = shiftPos(doc.sel.head); doc.sel.anchor = shiftPos(doc.sel.anc
hor); | 3320 return new Range(Pos(range.anchor.line + distance, range.anchor.ch), |
| 2427 doc.sel.from = shiftPos(doc.sel.from); doc.sel.to = shiftPos(doc.sel.to); | 3321 Pos(range.head.line + distance, range.head.ch)); |
| 3322 }), doc.sel.primIndex); |
| 3323 if (doc.cm) regChange(doc.cm, doc.first, doc.first - distance, distance); |
| 2428 } | 3324 } |
| 2429 | 3325 |
| 3326 // More lower-level change function, handling only a single document |
| 3327 // (not linked ones). |
| 2430 function makeChangeSingleDoc(doc, change, selAfter, spans) { | 3328 function makeChangeSingleDoc(doc, change, selAfter, spans) { |
| 2431 if (doc.cm && !doc.cm.curOp) | 3329 if (doc.cm && !doc.cm.curOp) |
| 2432 return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans
); | 3330 return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans
); |
| 2433 | 3331 |
| 2434 if (change.to.line < doc.first) { | 3332 if (change.to.line < doc.first) { |
| 2435 shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)
); | 3333 shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)
); |
| 2436 return; | 3334 return; |
| 2437 } | 3335 } |
| 2438 if (change.from.line > doc.lastLine()) return; | 3336 if (change.from.line > doc.lastLine()) return; |
| 2439 | 3337 |
| 2440 // Clip the change to the size of this doc | 3338 // Clip the change to the size of this doc |
| 2441 if (change.from.line < doc.first) { | 3339 if (change.from.line < doc.first) { |
| 2442 var shift = change.text.length - 1 - (doc.first - change.from.line); | 3340 var shift = change.text.length - 1 - (doc.first - change.from.line); |
| 2443 shiftDoc(doc, shift); | 3341 shiftDoc(doc, shift); |
| 2444 change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.
to.ch), | 3342 change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.
to.ch), |
| 2445 text: [lst(change.text)], origin: change.origin}; | 3343 text: [lst(change.text)], origin: change.origin}; |
| 2446 } | 3344 } |
| 2447 var last = doc.lastLine(); | 3345 var last = doc.lastLine(); |
| 2448 if (change.to.line > last) { | 3346 if (change.to.line > last) { |
| 2449 change = {from: change.from, to: Pos(last, getLine(doc, last).text.length)
, | 3347 change = {from: change.from, to: Pos(last, getLine(doc, last).text.length)
, |
| 2450 text: [change.text[0]], origin: change.origin}; | 3348 text: [change.text[0]], origin: change.origin}; |
| 2451 } | 3349 } |
| 2452 | 3350 |
| 2453 change.removed = getBetween(doc, change.from, change.to); | 3351 change.removed = getBetween(doc, change.from, change.to); |
| 2454 | 3352 |
| 2455 if (!selAfter) selAfter = computeSelAfterChange(doc, change, null); | 3353 if (!selAfter) selAfter = computeSelAfterChange(doc, change, null); |
| 2456 if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans, selAfter); | 3354 if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans); |
| 2457 else updateDoc(doc, change, spans, selAfter); | 3355 else updateDoc(doc, change, spans); |
| 3356 setSelectionNoUndo(doc, selAfter, sel_dontScroll); |
| 2458 } | 3357 } |
| 2459 | 3358 |
| 2460 function makeChangeSingleDocInEditor(cm, change, spans, selAfter) { | 3359 // Handle the interaction of a change to a document with the editor |
| 3360 // that this document is part of. |
| 3361 function makeChangeSingleDocInEditor(cm, change, spans) { |
| 2461 var doc = cm.doc, display = cm.display, from = change.from, to = change.to; | 3362 var doc = cm.doc, display = cm.display, from = change.from, to = change.to; |
| 2462 | 3363 |
| 2463 var recomputeMaxLength = false, checkWidthStart = from.line; | 3364 var recomputeMaxLength = false, checkWidthStart = from.line; |
| 2464 if (!cm.options.lineWrapping) { | 3365 if (!cm.options.lineWrapping) { |
| 2465 checkWidthStart = lineNo(visualLine(doc, getLine(doc, from.line))); | 3366 checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); |
| 2466 doc.iter(checkWidthStart, to.line + 1, function(line) { | 3367 doc.iter(checkWidthStart, to.line + 1, function(line) { |
| 2467 if (line == display.maxLine) { | 3368 if (line == display.maxLine) { |
| 2468 recomputeMaxLength = true; | 3369 recomputeMaxLength = true; |
| 2469 return true; | 3370 return true; |
| 2470 } | 3371 } |
| 2471 }); | 3372 }); |
| 2472 } | 3373 } |
| 2473 | 3374 |
| 2474 if (!posLess(doc.sel.head, change.from) && !posLess(change.to, doc.sel.head)
) | 3375 if (doc.sel.contains(change.from, change.to) > -1) |
| 2475 cm.curOp.cursorActivity = true; | 3376 cm.curOp.cursorActivity = true; |
| 2476 | 3377 |
| 2477 updateDoc(doc, change, spans, selAfter, estimateHeight(cm)); | 3378 updateDoc(doc, change, spans, estimateHeight(cm)); |
| 2478 | 3379 |
| 2479 if (!cm.options.lineWrapping) { | 3380 if (!cm.options.lineWrapping) { |
| 2480 doc.iter(checkWidthStart, from.line + change.text.length, function(line) { | 3381 doc.iter(checkWidthStart, from.line + change.text.length, function(line) { |
| 2481 var len = lineLength(doc, line); | 3382 var len = lineLength(line); |
| 2482 if (len > display.maxLineLength) { | 3383 if (len > display.maxLineLength) { |
| 2483 display.maxLine = line; | 3384 display.maxLine = line; |
| 2484 display.maxLineLength = len; | 3385 display.maxLineLength = len; |
| 2485 display.maxLineChanged = true; | 3386 display.maxLineChanged = true; |
| 2486 recomputeMaxLength = false; | 3387 recomputeMaxLength = false; |
| 2487 } | 3388 } |
| 2488 }); | 3389 }); |
| 2489 if (recomputeMaxLength) cm.curOp.updateMaxLine = true; | 3390 if (recomputeMaxLength) cm.curOp.updateMaxLine = true; |
| 2490 } | 3391 } |
| 2491 | 3392 |
| 2492 // Adjust frontier, schedule worker | 3393 // Adjust frontier, schedule worker |
| 2493 doc.frontier = Math.min(doc.frontier, from.line); | 3394 doc.frontier = Math.min(doc.frontier, from.line); |
| 2494 startWorker(cm, 400); | 3395 startWorker(cm, 400); |
| 2495 | 3396 |
| 2496 var lendiff = change.text.length - (to.line - from.line) - 1; | 3397 var lendiff = change.text.length - (to.line - from.line) - 1; |
| 2497 // Remember that these lines changed, for updating the display | 3398 // Remember that these lines changed, for updating the display |
| 2498 regChange(cm, from.line, to.line + 1, lendiff); | 3399 if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm
.doc, change)) |
| 3400 regLineChange(cm, from.line, "text"); |
| 3401 else |
| 3402 regChange(cm, from.line, to.line + 1, lendiff); |
| 2499 | 3403 |
| 2500 if (hasHandler(cm, "change")) { | 3404 if (hasHandler(cm, "change") || hasHandler(cm, "changes")) |
| 2501 var changeObj = {from: from, to: to, | 3405 (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push({ |
| 2502 text: change.text, | 3406 from: from, to: to, |
| 2503 removed: change.removed, | 3407 text: change.text, |
| 2504 origin: change.origin}; | 3408 removed: change.removed, |
| 2505 if (cm.curOp.textChanged) { | 3409 origin: change.origin |
| 2506 for (var cur = cm.curOp.textChanged; cur.next; cur = cur.next) {} | 3410 }); |
| 2507 cur.next = changeObj; | |
| 2508 } else cm.curOp.textChanged = changeObj; | |
| 2509 } | |
| 2510 } | 3411 } |
| 2511 | 3412 |
| 2512 function replaceRange(doc, code, from, to, origin) { | 3413 function replaceRange(doc, code, from, to, origin) { |
| 2513 if (!to) to = from; | 3414 if (!to) to = from; |
| 2514 if (posLess(to, from)) { var tmp = to; to = from; from = tmp; } | 3415 if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; } |
| 2515 if (typeof code == "string") code = splitLines(code); | 3416 if (typeof code == "string") code = splitLines(code); |
| 2516 makeChange(doc, {from: from, to: to, text: code, origin: origin}, null); | 3417 makeChange(doc, {from: from, to: to, text: code, origin: origin}); |
| 2517 } | 3418 } |
| 2518 | 3419 |
| 2519 // POSITION OBJECT | 3420 // SCROLLING THINGS INTO VIEW |
| 2520 | 3421 |
| 2521 function Pos(line, ch) { | 3422 // If an editor sits on the top or bottom of the window, partially |
| 2522 if (!(this instanceof Pos)) return new Pos(line, ch); | 3423 // scrolled out of view, this ensures that the cursor is visible. |
| 2523 this.line = line; this.ch = ch; | 3424 function maybeScrollWindow(cm, coords) { |
| 2524 } | 3425 var display = cm.display, box = display.sizer.getBoundingClientRect(), doScr
oll = null; |
| 2525 CodeMirror.Pos = Pos; | |
| 2526 | |
| 2527 function posEq(a, b) {return a.line == b.line && a.ch == b.ch;} | |
| 2528 function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch <
b.ch);} | |
| 2529 function cmp(a, b) {return a.line - b.line || a.ch - b.ch;} | |
| 2530 function copyPos(x) {return Pos(x.line, x.ch);} | |
| 2531 | |
| 2532 // SELECTION | |
| 2533 | |
| 2534 function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first +
doc.size - 1));} | |
| 2535 function clipPos(doc, pos) { | |
| 2536 if (pos.line < doc.first) return Pos(doc.first, 0); | |
| 2537 var last = doc.first + doc.size - 1; | |
| 2538 if (pos.line > last) return Pos(last, getLine(doc, last).text.length); | |
| 2539 return clipToLen(pos, getLine(doc, pos.line).text.length); | |
| 2540 } | |
| 2541 function clipToLen(pos, linelen) { | |
| 2542 var ch = pos.ch; | |
| 2543 if (ch == null || ch > linelen) return Pos(pos.line, linelen); | |
| 2544 else if (ch < 0) return Pos(pos.line, 0); | |
| 2545 else return pos; | |
| 2546 } | |
| 2547 function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;} | |
| 2548 | |
| 2549 // If shift is held, this will move the selection anchor. Otherwise, | |
| 2550 // it'll set the whole selection. | |
| 2551 function extendSelection(doc, pos, other, bias) { | |
| 2552 if (doc.sel.shift || doc.sel.extend) { | |
| 2553 var anchor = doc.sel.anchor; | |
| 2554 if (other) { | |
| 2555 var posBefore = posLess(pos, anchor); | |
| 2556 if (posBefore != posLess(other, anchor)) { | |
| 2557 anchor = pos; | |
| 2558 pos = other; | |
| 2559 } else if (posBefore != posLess(pos, other)) { | |
| 2560 pos = other; | |
| 2561 } | |
| 2562 } | |
| 2563 setSelection(doc, anchor, pos, bias); | |
| 2564 } else { | |
| 2565 setSelection(doc, pos, other || pos, bias); | |
| 2566 } | |
| 2567 if (doc.cm) doc.cm.curOp.userSelChange = true; | |
| 2568 } | |
| 2569 | |
| 2570 function filterSelectionChange(doc, anchor, head) { | |
| 2571 var obj = {anchor: anchor, head: head}; | |
| 2572 signal(doc, "beforeSelectionChange", doc, obj); | |
| 2573 if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); | |
| 2574 obj.anchor = clipPos(doc, obj.anchor); obj.head = clipPos(doc, obj.head); | |
| 2575 return obj; | |
| 2576 } | |
| 2577 | |
| 2578 // Update the selection. Last two args are only used by | |
| 2579 // updateDoc, since they have to be expressed in the line | |
| 2580 // numbers before the update. | |
| 2581 function setSelection(doc, anchor, head, bias, checkAtomic) { | |
| 2582 if (!checkAtomic && hasHandler(doc, "beforeSelectionChange") || doc.cm && ha
sHandler(doc.cm, "beforeSelectionChange")) { | |
| 2583 var filtered = filterSelectionChange(doc, anchor, head); | |
| 2584 head = filtered.head; | |
| 2585 anchor = filtered.anchor; | |
| 2586 } | |
| 2587 | |
| 2588 var sel = doc.sel; | |
| 2589 sel.goalColumn = null; | |
| 2590 if (bias == null) bias = posLess(head, sel.head) ? -1 : 1; | |
| 2591 // Skip over atomic spans. | |
| 2592 if (checkAtomic || !posEq(anchor, sel.anchor)) | |
| 2593 anchor = skipAtomic(doc, anchor, bias, checkAtomic != "push"); | |
| 2594 if (checkAtomic || !posEq(head, sel.head)) | |
| 2595 head = skipAtomic(doc, head, bias, checkAtomic != "push"); | |
| 2596 | |
| 2597 if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return; | |
| 2598 | |
| 2599 sel.anchor = anchor; sel.head = head; | |
| 2600 var inv = posLess(head, anchor); | |
| 2601 sel.from = inv ? head : anchor; | |
| 2602 sel.to = inv ? anchor : head; | |
| 2603 | |
| 2604 if (doc.cm) | |
| 2605 doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = | |
| 2606 doc.cm.curOp.cursorActivity = true; | |
| 2607 | |
| 2608 signalLater(doc, "cursorActivity", doc); | |
| 2609 } | |
| 2610 | |
| 2611 function reCheckSelection(cm) { | |
| 2612 setSelection(cm.doc, cm.doc.sel.from, cm.doc.sel.to, null, "push"); | |
| 2613 } | |
| 2614 | |
| 2615 function skipAtomic(doc, pos, bias, mayClear) { | |
| 2616 var flipped = false, curPos = pos; | |
| 2617 var dir = bias || 1; | |
| 2618 doc.cantEdit = false; | |
| 2619 search: for (;;) { | |
| 2620 var line = getLine(doc, curPos.line); | |
| 2621 if (line.markedSpans) { | |
| 2622 for (var i = 0; i < line.markedSpans.length; ++i) { | |
| 2623 var sp = line.markedSpans[i], m = sp.marker; | |
| 2624 if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.f
rom < curPos.ch)) && | |
| 2625 (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to >
curPos.ch))) { | |
| 2626 if (mayClear) { | |
| 2627 signal(m, "beforeCursorEnter"); | |
| 2628 if (m.explicitlyCleared) { | |
| 2629 if (!line.markedSpans) break; | |
| 2630 else {--i; continue;} | |
| 2631 } | |
| 2632 } | |
| 2633 if (!m.atomic) continue; | |
| 2634 var newPos = m.find()[dir < 0 ? "from" : "to"]; | |
| 2635 if (posEq(newPos, curPos)) { | |
| 2636 newPos.ch += dir; | |
| 2637 if (newPos.ch < 0) { | |
| 2638 if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.li
ne - 1)); | |
| 2639 else newPos = null; | |
| 2640 } else if (newPos.ch > line.text.length) { | |
| 2641 if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.
line + 1, 0); | |
| 2642 else newPos = null; | |
| 2643 } | |
| 2644 if (!newPos) { | |
| 2645 if (flipped) { | |
| 2646 // Driven in a corner -- no valid cursor position found at all | |
| 2647 // -- try again *with* clearing, if we didn't already | |
| 2648 if (!mayClear) return skipAtomic(doc, pos, bias, true); | |
| 2649 // Otherwise, turn off editing until further notice, and retur
n the start of the doc | |
| 2650 doc.cantEdit = true; | |
| 2651 return Pos(doc.first, 0); | |
| 2652 } | |
| 2653 flipped = true; newPos = pos; dir = -dir; | |
| 2654 } | |
| 2655 } | |
| 2656 curPos = newPos; | |
| 2657 continue search; | |
| 2658 } | |
| 2659 } | |
| 2660 } | |
| 2661 return curPos; | |
| 2662 } | |
| 2663 } | |
| 2664 | |
| 2665 // SCROLLING | |
| 2666 | |
| 2667 function scrollCursorIntoView(cm) { | |
| 2668 var coords = scrollPosIntoView(cm, cm.doc.sel.head, null, cm.options.cursorS
crollMargin); | |
| 2669 if (!cm.state.focused) return; | |
| 2670 var display = cm.display, box = getRect(display.sizer), doScroll = null; | |
| 2671 if (coords.top + box.top < 0) doScroll = true; | 3426 if (coords.top + box.top < 0) doScroll = true; |
| 2672 else if (coords.bottom + box.top > (window.innerHeight || document.documentE
lement.clientHeight)) doScroll = false; | 3427 else if (coords.bottom + box.top > (window.innerHeight || document.documentE
lement.clientHeight)) doScroll = false; |
| 2673 if (doScroll != null && !phantom) { | 3428 if (doScroll != null && !phantom) { |
| 2674 var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " + | 3429 var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " + |
| 2675 (coords.top - display.viewOffset) + "px; height: " + | 3430 (coords.top - display.viewOffset - paddingTop(cm.disp
lay)) + "px; height: " + |
| 2676 (coords.bottom - coords.top + scrollerCutOff) + "px;
left: " + | 3431 (coords.bottom - coords.top + scrollerCutOff) + "px;
left: " + |
| 2677 coords.left + "px; width: 2px;"); | 3432 coords.left + "px; width: 2px;"); |
| 2678 cm.display.lineSpace.appendChild(scrollNode); | 3433 cm.display.lineSpace.appendChild(scrollNode); |
| 2679 scrollNode.scrollIntoView(doScroll); | 3434 scrollNode.scrollIntoView(doScroll); |
| 2680 cm.display.lineSpace.removeChild(scrollNode); | 3435 cm.display.lineSpace.removeChild(scrollNode); |
| 2681 } | 3436 } |
| 2682 } | 3437 } |
| 2683 | 3438 |
| 3439 // Scroll a given position into view (immediately), verifying that |
| 3440 // it actually became visible (as line heights are accurately |
| 3441 // measured, the position of something may 'drift' during drawing). |
| 2684 function scrollPosIntoView(cm, pos, end, margin) { | 3442 function scrollPosIntoView(cm, pos, end, margin) { |
| 2685 if (margin == null) margin = 0; | 3443 if (margin == null) margin = 0; |
| 2686 for (;;) { | 3444 for (;;) { |
| 2687 var changed = false, coords = cursorCoords(cm, pos); | 3445 var changed = false, coords = cursorCoords(cm, pos); |
| 2688 var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); | 3446 var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); |
| 2689 var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.lef
t), | 3447 var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.lef
t), |
| 2690 Math.min(coords.top, endCoords.top) - m
argin, | 3448 Math.min(coords.top, endCoords.top) - m
argin, |
| 2691 Math.max(coords.left, endCoords.left), | 3449 Math.max(coords.left, endCoords.left), |
| 2692 Math.max(coords.bottom, endCoords.botto
m) + margin); | 3450 Math.max(coords.bottom, endCoords.botto
m) + margin); |
| 2693 var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; | 3451 var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; |
| 2694 if (scrollPos.scrollTop != null) { | 3452 if (scrollPos.scrollTop != null) { |
| 2695 setScrollTop(cm, scrollPos.scrollTop); | 3453 setScrollTop(cm, scrollPos.scrollTop); |
| 2696 if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true; | 3454 if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true; |
| 2697 } | 3455 } |
| 2698 if (scrollPos.scrollLeft != null) { | 3456 if (scrollPos.scrollLeft != null) { |
| 2699 setScrollLeft(cm, scrollPos.scrollLeft); | 3457 setScrollLeft(cm, scrollPos.scrollLeft); |
| 2700 if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true; | 3458 if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true; |
| 2701 } | 3459 } |
| 2702 if (!changed) return coords; | 3460 if (!changed) return coords; |
| 2703 } | 3461 } |
| 2704 } | 3462 } |
| 2705 | 3463 |
| 3464 // Scroll a given set of coordinates into view (immediately). |
| 2706 function scrollIntoView(cm, x1, y1, x2, y2) { | 3465 function scrollIntoView(cm, x1, y1, x2, y2) { |
| 2707 var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); | 3466 var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); |
| 2708 if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); | 3467 if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); |
| 2709 if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); | 3468 if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); |
| 2710 } | 3469 } |
| 2711 | 3470 |
| 3471 // Calculate a new scroll position needed to scroll the given |
| 3472 // rectangle into view. Returns an object with scrollTop and |
| 3473 // scrollLeft properties. When these are undefined, the |
| 3474 // vertical/horizontal position does not need to be adjusted. |
| 2712 function calculateScrollPos(cm, x1, y1, x2, y2) { | 3475 function calculateScrollPos(cm, x1, y1, x2, y2) { |
| 2713 var display = cm.display, snapMargin = textHeight(cm.display); | 3476 var display = cm.display, snapMargin = textHeight(cm.display); |
| 2714 if (y1 < 0) y1 = 0; | 3477 if (y1 < 0) y1 = 0; |
| 2715 var screen = display.scroller.clientHeight - scrollerCutOff, screentop = dis
play.scroller.scrollTop, result = {}; | 3478 var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop
: display.scroller.scrollTop; |
| 3479 var screen = display.scroller.clientHeight - scrollerCutOff, result = {}; |
| 2716 var docBottom = cm.doc.height + paddingVert(display); | 3480 var docBottom = cm.doc.height + paddingVert(display); |
| 2717 var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin; | 3481 var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin; |
| 2718 if (y1 < screentop) { | 3482 if (y1 < screentop) { |
| 2719 result.scrollTop = atTop ? 0 : y1; | 3483 result.scrollTop = atTop ? 0 : y1; |
| 2720 } else if (y2 > screentop + screen) { | 3484 } else if (y2 > screentop + screen) { |
| 2721 var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen); | 3485 var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen); |
| 2722 if (newTop != screentop) result.scrollTop = newTop; | 3486 if (newTop != screentop) result.scrollTop = newTop; |
| 2723 } | 3487 } |
| 2724 | 3488 |
| 2725 var screenw = display.scroller.clientWidth - scrollerCutOff, screenleft = di
splay.scroller.scrollLeft; | 3489 var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLe
ft : display.scroller.scrollLeft; |
| 3490 var screenw = display.scroller.clientWidth - scrollerCutOff; |
| 2726 x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth; | 3491 x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth; |
| 2727 var gutterw = display.gutters.offsetWidth; | 3492 var gutterw = display.gutters.offsetWidth; |
| 2728 var atLeft = x1 < gutterw + 10; | 3493 var atLeft = x1 < gutterw + 10; |
| 2729 if (x1 < screenleft + gutterw || atLeft) { | 3494 if (x1 < screenleft + gutterw || atLeft) { |
| 2730 if (atLeft) x1 = 0; | 3495 if (atLeft) x1 = 0; |
| 2731 result.scrollLeft = Math.max(0, x1 - 10 - gutterw); | 3496 result.scrollLeft = Math.max(0, x1 - 10 - gutterw); |
| 2732 } else if (x2 > screenw + screenleft - 3) { | 3497 } else if (x2 > screenw + screenleft - 3) { |
| 2733 result.scrollLeft = x2 + 10 - screenw; | 3498 result.scrollLeft = x2 + 10 - screenw; |
| 2734 } | 3499 } |
| 2735 return result; | 3500 return result; |
| 2736 } | 3501 } |
| 2737 | 3502 |
| 2738 function updateScrollPos(cm, left, top) { | 3503 // Store a relative adjustment to the scroll position in the current |
| 2739 cm.curOp.updateScrollPos = {scrollLeft: left == null ? cm.doc.scrollLeft : l
eft, | 3504 // operation (to be applied when the operation finishes). |
| 2740 scrollTop: top == null ? cm.doc.scrollTop : top}
; | 3505 function addToScrollPos(cm, left, top) { |
| 3506 if (left != null || top != null) resolveScrollToPos(cm); |
| 3507 if (left != null) |
| 3508 cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : c
m.curOp.scrollLeft) + left; |
| 3509 if (top != null) |
| 3510 cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.c
urOp.scrollTop) + top; |
| 2741 } | 3511 } |
| 2742 | 3512 |
| 2743 function addToScrollPos(cm, left, top) { | 3513 // Make sure that at the end of the operation the current cursor is |
| 2744 var pos = cm.curOp.updateScrollPos || (cm.curOp.updateScrollPos = {scrollLef
t: cm.doc.scrollLeft, scrollTop: cm.doc.scrollTop}); | 3514 // shown. |
| 2745 var scroll = cm.display.scroller; | 3515 function ensureCursorVisible(cm) { |
| 2746 pos.scrollTop = Math.max(0, Math.min(scroll.scrollHeight - scroll.clientHeig
ht, pos.scrollTop + top)); | 3516 resolveScrollToPos(cm); |
| 2747 pos.scrollLeft = Math.max(0, Math.min(scroll.scrollWidth - scroll.clientWidt
h, pos.scrollLeft + left)); | 3517 var cur = cm.getCursor(), from = cur, to = cur; |
| 3518 if (!cm.options.lineWrapping) { |
| 3519 from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur; |
| 3520 to = Pos(cur.line, cur.ch + 1); |
| 3521 } |
| 3522 cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollM
argin, isCursor: true}; |
| 3523 } |
| 3524 |
| 3525 // When an operation has its scrollToPos property set, and another |
| 3526 // scroll action is applied before the end of the operation, this |
| 3527 // 'simulates' scrolling that position into view in a cheap way, so |
| 3528 // that the effect of intermediate scroll commands is not ignored. |
| 3529 function resolveScrollToPos(cm) { |
| 3530 var range = cm.curOp.scrollToPos; |
| 3531 if (range) { |
| 3532 cm.curOp.scrollToPos = null; |
| 3533 var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.t
o); |
| 3534 var sPos = calculateScrollPos(cm, Math.min(from.left, to.left), |
| 3535 Math.min(from.top, to.top) - range.margin, |
| 3536 Math.max(from.right, to.right), |
| 3537 Math.max(from.bottom, to.bottom) + range.mar
gin); |
| 3538 cm.scrollTo(sPos.scrollLeft, sPos.scrollTop); |
| 3539 } |
| 2748 } | 3540 } |
| 2749 | 3541 |
| 2750 // API UTILITIES | 3542 // API UTILITIES |
| 2751 | 3543 |
| 3544 // Indent the given line. The how parameter can be "smart", |
| 3545 // "add"/null, "subtract", or "prev". When aggressive is false |
| 3546 // (typically set to true for forced single-line indents), empty |
| 3547 // lines are not indented, and places where the mode returns Pass |
| 3548 // are left alone. |
| 2752 function indentLine(cm, n, how, aggressive) { | 3549 function indentLine(cm, n, how, aggressive) { |
| 2753 var doc = cm.doc; | 3550 var doc = cm.doc, state; |
| 2754 if (how == null) how = "add"; | 3551 if (how == null) how = "add"; |
| 2755 if (how == "smart") { | 3552 if (how == "smart") { |
| 3553 // Fall back to "prev" when the mode doesn't have an indentation |
| 3554 // method. |
| 2756 if (!cm.doc.mode.indent) how = "prev"; | 3555 if (!cm.doc.mode.indent) how = "prev"; |
| 2757 else var state = getStateBefore(cm, n); | 3556 else state = getStateBefore(cm, n); |
| 2758 } | 3557 } |
| 2759 | 3558 |
| 2760 var tabSize = cm.options.tabSize; | 3559 var tabSize = cm.options.tabSize; |
| 2761 var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize)
; | 3560 var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize)
; |
| 3561 if (line.stateAfter) line.stateAfter = null; |
| 2762 var curSpaceString = line.text.match(/^\s*/)[0], indentation; | 3562 var curSpaceString = line.text.match(/^\s*/)[0], indentation; |
| 2763 if (!aggressive && !/\S/.test(line.text)) { | 3563 if (!aggressive && !/\S/.test(line.text)) { |
| 2764 indentation = 0; | 3564 indentation = 0; |
| 2765 how = "not"; | 3565 how = "not"; |
| 2766 } else if (how == "smart") { | 3566 } else if (how == "smart") { |
| 2767 indentation = cm.doc.mode.indent(state, line.text.slice(curSpaceString.len
gth), line.text); | 3567 indentation = cm.doc.mode.indent(state, line.text.slice(curSpaceString.len
gth), line.text); |
| 2768 if (indentation == Pass) { | 3568 if (indentation == Pass) { |
| 2769 if (!aggressive) return; | 3569 if (!aggressive) return; |
| 2770 how = "prev"; | 3570 how = "prev"; |
| 2771 } | 3571 } |
| 2772 } | 3572 } |
| 2773 if (how == "prev") { | 3573 if (how == "prev") { |
| 2774 if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null,
tabSize); | 3574 if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null,
tabSize); |
| 2775 else indentation = 0; | 3575 else indentation = 0; |
| 2776 } else if (how == "add") { | 3576 } else if (how == "add") { |
| 2777 indentation = curSpace + cm.options.indentUnit; | 3577 indentation = curSpace + cm.options.indentUnit; |
| 2778 } else if (how == "subtract") { | 3578 } else if (how == "subtract") { |
| 2779 indentation = curSpace - cm.options.indentUnit; | 3579 indentation = curSpace - cm.options.indentUnit; |
| 2780 } else if (typeof how == "number") { | 3580 } else if (typeof how == "number") { |
| 2781 indentation = curSpace + how; | 3581 indentation = curSpace + how; |
| 2782 } | 3582 } |
| 2783 indentation = Math.max(0, indentation); | 3583 indentation = Math.max(0, indentation); |
| 2784 | 3584 |
| 2785 var indentString = "", pos = 0; | 3585 var indentString = "", pos = 0; |
| 2786 if (cm.options.indentWithTabs) | 3586 if (cm.options.indentWithTabs) |
| 2787 for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; i
ndentString += "\t";} | 3587 for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; i
ndentString += "\t";} |
| 2788 if (pos < indentation) indentString += spaceStr(indentation - pos); | 3588 if (pos < indentation) indentString += spaceStr(indentation - pos); |
| 2789 | 3589 |
| 2790 if (indentString != curSpaceString) | 3590 if (indentString != curSpaceString) { |
| 2791 replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length
), "+input"); | 3591 replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length
), "+input"); |
| 2792 else if (doc.sel.head.line == n && doc.sel.head.ch < curSpaceString.length) | 3592 } else { |
| 2793 setSelection(doc, Pos(n, curSpaceString.length), Pos(n, curSpaceString.len
gth), 1); | 3593 // Ensure that, if the cursor was in the whitespace at the start |
| 3594 // of the line, it is moved to the end of that space. |
| 3595 for (var i = 0; i < doc.sel.ranges.length; i++) { |
| 3596 var range = doc.sel.ranges[i]; |
| 3597 if (range.head.line == n && range.head.ch < curSpaceString.length) { |
| 3598 var pos = Pos(n, curSpaceString.length); |
| 3599 replaceOneSelection(doc, i, new Range(pos, pos)); |
| 3600 break; |
| 3601 } |
| 3602 } |
| 3603 } |
| 2794 line.stateAfter = null; | 3604 line.stateAfter = null; |
| 2795 } | 3605 } |
| 2796 | 3606 |
| 2797 function changeLine(cm, handle, op) { | 3607 // Utility for applying a change to a line by handle or number, |
| 3608 // returning the number and optionally registering the line as |
| 3609 // changed. |
| 3610 function changeLine(cm, handle, changeType, op) { |
| 2798 var no = handle, line = handle, doc = cm.doc; | 3611 var no = handle, line = handle, doc = cm.doc; |
| 2799 if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle)); | 3612 if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle)); |
| 2800 else no = lineNo(handle); | 3613 else no = lineNo(handle); |
| 2801 if (no == null) return null; | 3614 if (no == null) return null; |
| 2802 if (op(line, no)) regChange(cm, no, no + 1); | 3615 if (op(line, no)) regLineChange(cm, no, changeType); |
| 2803 else return null; | 3616 else return null; |
| 2804 return line; | 3617 return line; |
| 2805 } | 3618 } |
| 2806 | 3619 |
| 3620 // Helper for deleting text near the selection(s), used to implement |
| 3621 // backspace, delete, and similar functionality. |
| 3622 function deleteNearSelection(cm, compute) { |
| 3623 var ranges = cm.doc.sel.ranges, kill = []; |
| 3624 // Build up a set of ranges to kill first, merging overlapping |
| 3625 // ranges. |
| 3626 for (var i = 0; i < ranges.length; i++) { |
| 3627 var toKill = compute(ranges[i]); |
| 3628 while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { |
| 3629 var replaced = kill.pop(); |
| 3630 if (cmp(replaced.from, toKill.from) < 0) { |
| 3631 toKill.from = replaced.from; |
| 3632 break; |
| 3633 } |
| 3634 } |
| 3635 kill.push(toKill); |
| 3636 } |
| 3637 // Next, remove those actual ranges. |
| 3638 runInOp(cm, function() { |
| 3639 for (var i = kill.length - 1; i >= 0; i--) |
| 3640 replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); |
| 3641 ensureCursorVisible(cm); |
| 3642 }); |
| 3643 } |
| 3644 |
| 3645 // Used for horizontal relative motion. Dir is -1 or 1 (left or |
| 3646 // right), unit can be "char", "column" (like char, but doesn't |
| 3647 // cross line boundaries), "word" (across next word), or "group" (to |
| 3648 // the start of next group of word or non-word-non-whitespace |
| 3649 // chars). The visually param controls whether, in right-to-left |
| 3650 // text, direction 1 means to move towards the next index in the |
| 3651 // string, or towards the character to the right of the current |
| 3652 // position. The resulting position will have a hitSide=true |
| 3653 // property if it reached the end of the document. |
| 2807 function findPosH(doc, pos, dir, unit, visually) { | 3654 function findPosH(doc, pos, dir, unit, visually) { |
| 2808 var line = pos.line, ch = pos.ch, origDir = dir; | 3655 var line = pos.line, ch = pos.ch, origDir = dir; |
| 2809 var lineObj = getLine(doc, line); | 3656 var lineObj = getLine(doc, line); |
| 2810 var possible = true; | 3657 var possible = true; |
| 2811 function findNextLine() { | 3658 function findNextLine() { |
| 2812 var l = line + dir; | 3659 var l = line + dir; |
| 2813 if (l < doc.first || l >= doc.first + doc.size) return (possible = false); | 3660 if (l < doc.first || l >= doc.first + doc.size) return (possible = false); |
| 2814 line = l; | 3661 line = l; |
| 2815 return lineObj = getLine(doc, l); | 3662 return lineObj = getLine(doc, l); |
| 2816 } | 3663 } |
| 2817 function moveOnce(boundToLine) { | 3664 function moveOnce(boundToLine) { |
| 2818 var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, tru
e); | 3665 var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, tru
e); |
| 2819 if (next == null) { | 3666 if (next == null) { |
| 2820 if (!boundToLine && findNextLine()) { | 3667 if (!boundToLine && findNextLine()) { |
| 2821 if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); | 3668 if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); |
| 2822 else ch = dir < 0 ? lineObj.text.length : 0; | 3669 else ch = dir < 0 ? lineObj.text.length : 0; |
| 2823 } else return (possible = false); | 3670 } else return (possible = false); |
| 2824 } else ch = next; | 3671 } else ch = next; |
| 2825 return true; | 3672 return true; |
| 2826 } | 3673 } |
| 2827 | 3674 |
| 2828 if (unit == "char") moveOnce(); | 3675 if (unit == "char") moveOnce(); |
| 2829 else if (unit == "column") moveOnce(true); | 3676 else if (unit == "column") moveOnce(true); |
| 2830 else if (unit == "word" || unit == "group") { | 3677 else if (unit == "word" || unit == "group") { |
| 2831 var sawType = null, group = unit == "group"; | 3678 var sawType = null, group = unit == "group"; |
| 2832 for (var first = true;; first = false) { | 3679 for (var first = true;; first = false) { |
| 2833 if (dir < 0 && !moveOnce(!first)) break; | 3680 if (dir < 0 && !moveOnce(!first)) break; |
| 2834 var cur = lineObj.text.charAt(ch) || "\n"; | 3681 var cur = lineObj.text.charAt(ch) || "\n"; |
| 2835 var type = isWordChar(cur) ? "w" | 3682 var type = isWordChar(cur) ? "w" |
| 2836 : !group ? null | 3683 : group && cur == "\n" ? "n" |
| 2837 : /\s/.test(cur) ? null | 3684 : !group || /\s/.test(cur) ? null |
| 2838 : "p"; | 3685 : "p"; |
| 3686 if (group && !first && !type) type = "s"; |
| 2839 if (sawType && sawType != type) { | 3687 if (sawType && sawType != type) { |
| 2840 if (dir < 0) {dir = 1; moveOnce();} | 3688 if (dir < 0) {dir = 1; moveOnce();} |
| 2841 break; | 3689 break; |
| 2842 } | 3690 } |
| 3691 |
| 2843 if (type) sawType = type; | 3692 if (type) sawType = type; |
| 2844 if (dir > 0 && !moveOnce(!first)) break; | 3693 if (dir > 0 && !moveOnce(!first)) break; |
| 2845 } | 3694 } |
| 2846 } | 3695 } |
| 2847 var result = skipAtomic(doc, Pos(line, ch), origDir, true); | 3696 var result = skipAtomic(doc, Pos(line, ch), origDir, true); |
| 2848 if (!possible) result.hitSide = true; | 3697 if (!possible) result.hitSide = true; |
| 2849 return result; | 3698 return result; |
| 2850 } | 3699 } |
| 2851 | 3700 |
| 3701 // For relative vertical movement. Dir may be -1 or 1. Unit can be |
| 3702 // "page" or "line". The resulting position will have a hitSide=true |
| 3703 // property if it reached the end of the document. |
| 2852 function findPosV(cm, pos, dir, unit) { | 3704 function findPosV(cm, pos, dir, unit) { |
| 2853 var doc = cm.doc, x = pos.left, y; | 3705 var doc = cm.doc, x = pos.left, y; |
| 2854 if (unit == "page") { | 3706 if (unit == "page") { |
| 2855 var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeigh
t || document.documentElement.clientHeight); | 3707 var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeigh
t || document.documentElement.clientHeight); |
| 2856 y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.displ
ay)); | 3708 y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.displ
ay)); |
| 2857 } else if (unit == "line") { | 3709 } else if (unit == "line") { |
| 2858 y = dir > 0 ? pos.bottom + 3 : pos.top - 3; | 3710 y = dir > 0 ? pos.bottom + 3 : pos.top - 3; |
| 2859 } | 3711 } |
| 2860 for (;;) { | 3712 for (;;) { |
| 2861 var target = coordsChar(cm, x, y); | 3713 var target = coordsChar(cm, x, y); |
| 2862 if (!target.outside) break; | 3714 if (!target.outside) break; |
| 2863 if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; } | 3715 if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; } |
| 2864 y += dir * 5; | 3716 y += dir * 5; |
| 2865 } | 3717 } |
| 2866 return target; | 3718 return target; |
| 2867 } | 3719 } |
| 2868 | 3720 |
| 2869 function findWordAt(line, pos) { | 3721 // Find the word at the given position (as returned by coordsChar). |
| 3722 function findWordAt(doc, pos) { |
| 3723 var line = getLine(doc, pos.line).text; |
| 2870 var start = pos.ch, end = pos.ch; | 3724 var start = pos.ch, end = pos.ch; |
| 2871 if (line) { | 3725 if (line) { |
| 2872 if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end; | 3726 if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end; |
| 2873 var startChar = line.charAt(start); | 3727 var startChar = line.charAt(start); |
| 2874 var check = isWordChar(startChar) ? isWordChar | 3728 var check = isWordChar(startChar) ? isWordChar |
| 2875 : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} | 3729 : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} |
| 2876 : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);}; | 3730 : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);}; |
| 2877 while (start > 0 && check(line.charAt(start - 1))) --start; | 3731 while (start > 0 && check(line.charAt(start - 1))) --start; |
| 2878 while (end < line.length && check(line.charAt(end))) ++end; | 3732 while (end < line.length && check(line.charAt(end))) ++end; |
| 2879 } | 3733 } |
| 2880 return {from: Pos(pos.line, start), to: Pos(pos.line, end)}; | 3734 return new Range(Pos(pos.line, start), Pos(pos.line, end)); |
| 2881 } | 3735 } |
| 2882 | 3736 |
| 2883 function selectLine(cm, line) { | 3737 // EDITOR METHODS |
| 2884 extendSelection(cm.doc, Pos(line, 0), clipPos(cm.doc, Pos(line + 1, 0))); | |
| 2885 } | |
| 2886 | 3738 |
| 2887 // PROTOTYPE | 3739 // The publicly visible API. Note that methodOp(f) means |
| 3740 // 'wrap f in an operation, performed on its `this` parameter'. |
| 2888 | 3741 |
| 2889 // The publicly visible API. Note that operation(null, f) means | 3742 // This is not the complete set of editor methods. Most of the |
| 2890 // 'wrap f in an operation, performed on its `this` parameter' | 3743 // methods defined on the Doc type are also injected into |
| 3744 // CodeMirror.prototype, for backwards compatibility and |
| 3745 // convenience. |
| 2891 | 3746 |
| 2892 CodeMirror.prototype = { | 3747 CodeMirror.prototype = { |
| 2893 constructor: CodeMirror, | 3748 constructor: CodeMirror, |
| 2894 focus: function(){window.focus(); focusInput(this); fastPoll(this);}, | 3749 focus: function(){window.focus(); focusInput(this); fastPoll(this);}, |
| 2895 | 3750 |
| 2896 setOption: function(option, value) { | 3751 setOption: function(option, value) { |
| 2897 var options = this.options, old = options[option]; | 3752 var options = this.options, old = options[option]; |
| 2898 if (options[option] == value && option != "mode") return; | 3753 if (options[option] == value && option != "mode") return; |
| 2899 options[option] = value; | 3754 options[option] = value; |
| 2900 if (optionHandlers.hasOwnProperty(option)) | 3755 if (optionHandlers.hasOwnProperty(option)) |
| 2901 operation(this, optionHandlers[option])(this, value, old); | 3756 operation(this, optionHandlers[option])(this, value, old); |
| 2902 }, | 3757 }, |
| 2903 | 3758 |
| 2904 getOption: function(option) {return this.options[option];}, | 3759 getOption: function(option) {return this.options[option];}, |
| 2905 getDoc: function() {return this.doc;}, | 3760 getDoc: function() {return this.doc;}, |
| 2906 | 3761 |
| 2907 addKeyMap: function(map, bottom) { | 3762 addKeyMap: function(map, bottom) { |
| 2908 this.state.keyMaps[bottom ? "push" : "unshift"](map); | 3763 this.state.keyMaps[bottom ? "push" : "unshift"](map); |
| 2909 }, | 3764 }, |
| 2910 removeKeyMap: function(map) { | 3765 removeKeyMap: function(map) { |
| 2911 var maps = this.state.keyMaps; | 3766 var maps = this.state.keyMaps; |
| 2912 for (var i = 0; i < maps.length; ++i) | 3767 for (var i = 0; i < maps.length; ++i) |
| 2913 if (maps[i] == map || (typeof maps[i] != "string" && maps[i].name == map
)) { | 3768 if (maps[i] == map || (typeof maps[i] != "string" && maps[i].name == map
)) { |
| 2914 maps.splice(i, 1); | 3769 maps.splice(i, 1); |
| 2915 return true; | 3770 return true; |
| 2916 } | 3771 } |
| 2917 }, | 3772 }, |
| 2918 | 3773 |
| 2919 addOverlay: operation(null, function(spec, options) { | 3774 addOverlay: methodOp(function(spec, options) { |
| 2920 var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); | 3775 var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); |
| 2921 if (mode.startState) throw new Error("Overlays may not be stateful."); | 3776 if (mode.startState) throw new Error("Overlays may not be stateful."); |
| 2922 this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && o
ptions.opaque}); | 3777 this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && o
ptions.opaque}); |
| 2923 this.state.modeGen++; | 3778 this.state.modeGen++; |
| 2924 regChange(this); | 3779 regChange(this); |
| 2925 }), | 3780 }), |
| 2926 removeOverlay: operation(null, function(spec) { | 3781 removeOverlay: methodOp(function(spec) { |
| 2927 var overlays = this.state.overlays; | 3782 var overlays = this.state.overlays; |
| 2928 for (var i = 0; i < overlays.length; ++i) { | 3783 for (var i = 0; i < overlays.length; ++i) { |
| 2929 var cur = overlays[i].modeSpec; | 3784 var cur = overlays[i].modeSpec; |
| 2930 if (cur == spec || typeof spec == "string" && cur.name == spec) { | 3785 if (cur == spec || typeof spec == "string" && cur.name == spec) { |
| 2931 overlays.splice(i, 1); | 3786 overlays.splice(i, 1); |
| 2932 this.state.modeGen++; | 3787 this.state.modeGen++; |
| 2933 regChange(this); | 3788 regChange(this); |
| 2934 return; | 3789 return; |
| 2935 } | 3790 } |
| 2936 } | 3791 } |
| 2937 }), | 3792 }), |
| 2938 | 3793 |
| 2939 indentLine: operation(null, function(n, dir, aggressive) { | 3794 indentLine: methodOp(function(n, dir, aggressive) { |
| 2940 if (typeof dir != "string" && typeof dir != "number") { | 3795 if (typeof dir != "string" && typeof dir != "number") { |
| 2941 if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; | 3796 if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; |
| 2942 else dir = dir ? "add" : "subtract"; | 3797 else dir = dir ? "add" : "subtract"; |
| 2943 } | 3798 } |
| 2944 if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive); | 3799 if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive); |
| 2945 }), | 3800 }), |
| 2946 indentSelection: operation(null, function(how) { | 3801 indentSelection: methodOp(function(how) { |
| 2947 var sel = this.doc.sel; | 3802 var ranges = this.doc.sel.ranges, end = -1; |
| 2948 if (posEq(sel.from, sel.to)) return indentLine(this, sel.from.line, how, t
rue); | 3803 for (var i = 0; i < ranges.length; i++) { |
| 2949 var e = sel.to.line - (sel.to.ch ? 0 : 1); | 3804 var range = ranges[i]; |
| 2950 for (var i = sel.from.line; i <= e; ++i) indentLine(this, i, how); | 3805 if (!range.empty()) { |
| 3806 var start = Math.max(end, range.from().line); |
| 3807 var to = range.to(); |
| 3808 end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; |
| 3809 for (var j = start; j < end; ++j) |
| 3810 indentLine(this, j, how); |
| 3811 } else if (range.head.line > end) { |
| 3812 indentLine(this, range.head.line, how, true); |
| 3813 end = range.head.line; |
| 3814 if (i == this.doc.sel.primIndex) ensureCursorVisible(this); |
| 3815 } |
| 3816 } |
| 2951 }), | 3817 }), |
| 2952 | 3818 |
| 2953 // Fetch the parser token for a given character. Useful for hacks | 3819 // Fetch the parser token for a given character. Useful for hacks |
| 2954 // that want to inspect the mode state (say, for completion). | 3820 // that want to inspect the mode state (say, for completion). |
| 2955 getTokenAt: function(pos, precise) { | 3821 getTokenAt: function(pos, precise) { |
| 2956 var doc = this.doc; | 3822 var doc = this.doc; |
| 2957 pos = clipPos(doc, pos); | 3823 pos = clipPos(doc, pos); |
| 2958 var state = getStateBefore(this, pos.line, precise), mode = this.doc.mode; | 3824 var state = getStateBefore(this, pos.line, precise), mode = this.doc.mode; |
| 2959 var line = getLine(doc, pos.line); | 3825 var line = getLine(doc, pos.line); |
| 2960 var stream = new StringStream(line.text, this.options.tabSize); | 3826 var stream = new StringStream(line.text, this.options.tabSize); |
| 2961 while (stream.pos < pos.ch && !stream.eol()) { | 3827 while (stream.pos < pos.ch && !stream.eol()) { |
| 2962 stream.start = stream.pos; | 3828 stream.start = stream.pos; |
| 2963 var style = mode.token(stream, state); | 3829 var style = mode.token(stream, state); |
| 2964 } | 3830 } |
| 2965 return {start: stream.start, | 3831 return {start: stream.start, |
| 2966 end: stream.pos, | 3832 end: stream.pos, |
| 2967 string: stream.current(), | 3833 string: stream.current(), |
| 2968 className: style || null, // Deprecated, use 'type' instead | |
| 2969 type: style || null, | 3834 type: style || null, |
| 2970 state: state}; | 3835 state: state}; |
| 2971 }, | 3836 }, |
| 2972 | 3837 |
| 2973 getTokenTypeAt: function(pos) { | 3838 getTokenTypeAt: function(pos) { |
| 2974 pos = clipPos(this.doc, pos); | 3839 pos = clipPos(this.doc, pos); |
| 2975 var styles = getLineStyles(this, getLine(this.doc, pos.line)); | 3840 var styles = getLineStyles(this, getLine(this.doc, pos.line)); |
| 2976 var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; | 3841 var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; |
| 2977 if (ch == 0) return styles[2]; | 3842 if (ch == 0) return styles[2]; |
| 2978 for (;;) { | 3843 for (;;) { |
| (...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 3017 return found; | 3882 return found; |
| 3018 }, | 3883 }, |
| 3019 | 3884 |
| 3020 getStateAfter: function(line, precise) { | 3885 getStateAfter: function(line, precise) { |
| 3021 var doc = this.doc; | 3886 var doc = this.doc; |
| 3022 line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); | 3887 line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); |
| 3023 return getStateBefore(this, line + 1, precise); | 3888 return getStateBefore(this, line + 1, precise); |
| 3024 }, | 3889 }, |
| 3025 | 3890 |
| 3026 cursorCoords: function(start, mode) { | 3891 cursorCoords: function(start, mode) { |
| 3027 var pos, sel = this.doc.sel; | 3892 var pos, range = this.doc.sel.primary(); |
| 3028 if (start == null) pos = sel.head; | 3893 if (start == null) pos = range.head; |
| 3029 else if (typeof start == "object") pos = clipPos(this.doc, start); | 3894 else if (typeof start == "object") pos = clipPos(this.doc, start); |
| 3030 else pos = start ? sel.from : sel.to; | 3895 else pos = start ? range.from() : range.to(); |
| 3031 return cursorCoords(this, pos, mode || "page"); | 3896 return cursorCoords(this, pos, mode || "page"); |
| 3032 }, | 3897 }, |
| 3033 | 3898 |
| 3034 charCoords: function(pos, mode) { | 3899 charCoords: function(pos, mode) { |
| 3035 return charCoords(this, clipPos(this.doc, pos), mode || "page"); | 3900 return charCoords(this, clipPos(this.doc, pos), mode || "page"); |
| 3036 }, | 3901 }, |
| 3037 | 3902 |
| 3038 coordsChar: function(coords, mode) { | 3903 coordsChar: function(coords, mode) { |
| 3039 coords = fromCoordSystem(this, coords, mode || "page"); | 3904 coords = fromCoordSystem(this, coords, mode || "page"); |
| 3040 return coordsChar(this, coords.left, coords.top); | 3905 return coordsChar(this, coords.left, coords.top); |
| 3041 }, | 3906 }, |
| 3042 | 3907 |
| 3043 lineAtHeight: function(height, mode) { | 3908 lineAtHeight: function(height, mode) { |
| 3044 height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top
; | 3909 height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top
; |
| 3045 return lineAtHeight(this.doc, height + this.display.viewOffset); | 3910 return lineAtHeight(this.doc, height + this.display.viewOffset); |
| 3046 }, | 3911 }, |
| 3047 heightAtLine: function(line, mode) { | 3912 heightAtLine: function(line, mode) { |
| 3048 var end = false, last = this.doc.first + this.doc.size - 1; | 3913 var end = false, last = this.doc.first + this.doc.size - 1; |
| 3049 if (line < this.doc.first) line = this.doc.first; | 3914 if (line < this.doc.first) line = this.doc.first; |
| 3050 else if (line > last) { line = last; end = true; } | 3915 else if (line > last) { line = last; end = true; } |
| 3051 var lineObj = getLine(this.doc, line); | 3916 var lineObj = getLine(this.doc, line); |
| 3052 return intoCoordSystem(this, getLine(this.doc, line), {top: 0, left: 0}, m
ode || "page").top + | 3917 return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").t
op + |
| 3053 (end ? lineObj.height : 0); | 3918 (end ? this.doc.height - heightAtLine(lineObj) : 0); |
| 3054 }, | 3919 }, |
| 3055 | 3920 |
| 3056 defaultTextHeight: function() { return textHeight(this.display); }, | 3921 defaultTextHeight: function() { return textHeight(this.display); }, |
| 3057 defaultCharWidth: function() { return charWidth(this.display); }, | 3922 defaultCharWidth: function() { return charWidth(this.display); }, |
| 3058 | 3923 |
| 3059 setGutterMarker: operation(null, function(line, gutterID, value) { | 3924 setGutterMarker: methodOp(function(line, gutterID, value) { |
| 3060 return changeLine(this, line, function(line) { | 3925 return changeLine(this, line, "gutter", function(line) { |
| 3061 var markers = line.gutterMarkers || (line.gutterMarkers = {}); | 3926 var markers = line.gutterMarkers || (line.gutterMarkers = {}); |
| 3062 markers[gutterID] = value; | 3927 markers[gutterID] = value; |
| 3063 if (!value && isEmpty(markers)) line.gutterMarkers = null; | 3928 if (!value && isEmpty(markers)) line.gutterMarkers = null; |
| 3064 return true; | 3929 return true; |
| 3065 }); | 3930 }); |
| 3066 }), | 3931 }), |
| 3067 | 3932 |
| 3068 clearGutter: operation(null, function(gutterID) { | 3933 clearGutter: methodOp(function(gutterID) { |
| 3069 var cm = this, doc = cm.doc, i = doc.first; | 3934 var cm = this, doc = cm.doc, i = doc.first; |
| 3070 doc.iter(function(line) { | 3935 doc.iter(function(line) { |
| 3071 if (line.gutterMarkers && line.gutterMarkers[gutterID]) { | 3936 if (line.gutterMarkers && line.gutterMarkers[gutterID]) { |
| 3072 line.gutterMarkers[gutterID] = null; | 3937 line.gutterMarkers[gutterID] = null; |
| 3073 regChange(cm, i, i + 1); | 3938 regLineChange(cm, i, "gutter"); |
| 3074 if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; | 3939 if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; |
| 3075 } | 3940 } |
| 3076 ++i; | 3941 ++i; |
| 3077 }); | 3942 }); |
| 3078 }), | 3943 }), |
| 3079 | 3944 |
| 3080 addLineClass: operation(null, function(handle, where, cls) { | 3945 addLineClass: methodOp(function(handle, where, cls) { |
| 3081 return changeLine(this, handle, function(line) { | 3946 return changeLine(this, handle, "class", function(line) { |
| 3082 var prop = where == "text" ? "textClass" : where == "background" ? "bgCl
ass" : "wrapClass"; | 3947 var prop = where == "text" ? "textClass" : where == "background" ? "bgCl
ass" : "wrapClass"; |
| 3083 if (!line[prop]) line[prop] = cls; | 3948 if (!line[prop]) line[prop] = cls; |
| 3084 else if (new RegExp("(?:^|\\s)" + cls + "(?:$|\\s)").test(line[prop])) r
eturn false; | 3949 else if (new RegExp("(?:^|\\s)" + cls + "(?:$|\\s)").test(line[prop])) r
eturn false; |
| 3085 else line[prop] += " " + cls; | 3950 else line[prop] += " " + cls; |
| 3086 return true; | 3951 return true; |
| 3087 }); | 3952 }); |
| 3088 }), | 3953 }), |
| 3089 | 3954 |
| 3090 removeLineClass: operation(null, function(handle, where, cls) { | 3955 removeLineClass: methodOp(function(handle, where, cls) { |
| 3091 return changeLine(this, handle, function(line) { | 3956 return changeLine(this, handle, "class", function(line) { |
| 3092 var prop = where == "text" ? "textClass" : where == "background" ? "bgCl
ass" : "wrapClass"; | 3957 var prop = where == "text" ? "textClass" : where == "background" ? "bgCl
ass" : "wrapClass"; |
| 3093 var cur = line[prop]; | 3958 var cur = line[prop]; |
| 3094 if (!cur) return false; | 3959 if (!cur) return false; |
| 3095 else if (cls == null) line[prop] = null; | 3960 else if (cls == null) line[prop] = null; |
| 3096 else { | 3961 else { |
| 3097 var found = cur.match(new RegExp("(?:^|\\s+)" + cls + "(?:$|\\s+)")); | 3962 var found = cur.match(new RegExp("(?:^|\\s+)" + cls + "(?:$|\\s+)")); |
| 3098 if (!found) return false; | 3963 if (!found) return false; |
| 3099 var end = found.index + found[0].length; | 3964 var end = found.index + found[0].length; |
| 3100 line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.l
ength ? "" : " ") + cur.slice(end) || null; | 3965 line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.l
ength ? "" : " ") + cur.slice(end) || null; |
| 3101 } | 3966 } |
| 3102 return true; | 3967 return true; |
| 3103 }); | 3968 }); |
| 3104 }), | 3969 }), |
| 3105 | 3970 |
| 3106 addLineWidget: operation(null, function(handle, node, options) { | 3971 addLineWidget: methodOp(function(handle, node, options) { |
| 3107 return addLineWidget(this, handle, node, options); | 3972 return addLineWidget(this, handle, node, options); |
| 3108 }), | 3973 }), |
| 3109 | 3974 |
| 3110 removeLineWidget: function(widget) { widget.clear(); }, | 3975 removeLineWidget: function(widget) { widget.clear(); }, |
| 3111 | 3976 |
| 3112 lineInfo: function(line) { | 3977 lineInfo: function(line) { |
| 3113 if (typeof line == "number") { | 3978 if (typeof line == "number") { |
| 3114 if (!isLine(this.doc, line)) return null; | 3979 if (!isLine(this.doc, line)) return null; |
| 3115 var n = line; | 3980 var n = line; |
| 3116 line = getLine(this.doc, line); | 3981 line = getLine(this.doc, line); |
| 3117 if (!line) return null; | 3982 if (!line) return null; |
| 3118 } else { | 3983 } else { |
| 3119 var n = lineNo(line); | 3984 var n = lineNo(line); |
| 3120 if (n == null) return null; | 3985 if (n == null) return null; |
| 3121 } | 3986 } |
| 3122 return {line: n, handle: line, text: line.text, gutterMarkers: line.gutter
Markers, | 3987 return {line: n, handle: line, text: line.text, gutterMarkers: line.gutter
Markers, |
| 3123 textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.
wrapClass, | 3988 textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.
wrapClass, |
| 3124 widgets: line.widgets}; | 3989 widgets: line.widgets}; |
| 3125 }, | 3990 }, |
| 3126 | 3991 |
| 3127 getViewport: function() { return {from: this.display.showingFrom, to: this.d
isplay.showingTo};}, | 3992 getViewport: function() { return {from: this.display.viewFrom, to: this.disp
lay.viewTo};}, |
| 3128 | 3993 |
| 3129 addWidget: function(pos, node, scroll, vert, horiz) { | 3994 addWidget: function(pos, node, scroll, vert, horiz) { |
| 3130 var display = this.display; | 3995 var display = this.display; |
| 3131 pos = cursorCoords(this, clipPos(this.doc, pos)); | 3996 pos = cursorCoords(this, clipPos(this.doc, pos)); |
| 3132 var top = pos.bottom, left = pos.left; | 3997 var top = pos.bottom, left = pos.left; |
| 3133 node.style.position = "absolute"; | 3998 node.style.position = "absolute"; |
| 3134 display.sizer.appendChild(node); | 3999 display.sizer.appendChild(node); |
| 3135 if (vert == "over") { | 4000 if (vert == "over") { |
| 3136 top = pos.top; | 4001 top = pos.top; |
| 3137 } else if (vert == "above" || vert == "near") { | 4002 } else if (vert == "above" || vert == "near") { |
| (...skipping 14 matching lines...) Expand all Loading... |
| 3152 node.style.right = "0px"; | 4017 node.style.right = "0px"; |
| 3153 } else { | 4018 } else { |
| 3154 if (horiz == "left") left = 0; | 4019 if (horiz == "left") left = 0; |
| 3155 else if (horiz == "middle") left = (display.sizer.clientWidth - node.off
setWidth) / 2; | 4020 else if (horiz == "middle") left = (display.sizer.clientWidth - node.off
setWidth) / 2; |
| 3156 node.style.left = left + "px"; | 4021 node.style.left = left + "px"; |
| 3157 } | 4022 } |
| 3158 if (scroll) | 4023 if (scroll) |
| 3159 scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offs
etHeight); | 4024 scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offs
etHeight); |
| 3160 }, | 4025 }, |
| 3161 | 4026 |
| 3162 triggerOnKeyDown: operation(null, onKeyDown), | 4027 triggerOnKeyDown: methodOp(onKeyDown), |
| 3163 triggerOnKeyPress: operation(null, onKeyPress), | 4028 triggerOnKeyPress: methodOp(onKeyPress), |
| 3164 triggerOnKeyUp: operation(null, onKeyUp), | 4029 triggerOnKeyUp: methodOp(onKeyUp), |
| 3165 | 4030 |
| 3166 execCommand: function(cmd) { | 4031 execCommand: function(cmd) { |
| 3167 if (commands.hasOwnProperty(cmd)) | 4032 if (commands.hasOwnProperty(cmd)) |
| 3168 return commands[cmd](this); | 4033 return commands[cmd](this); |
| 3169 }, | 4034 }, |
| 3170 | 4035 |
| 3171 findPosH: function(from, amount, unit, visually) { | 4036 findPosH: function(from, amount, unit, visually) { |
| 3172 var dir = 1; | 4037 var dir = 1; |
| 3173 if (amount < 0) { dir = -1; amount = -amount; } | 4038 if (amount < 0) { dir = -1; amount = -amount; } |
| 3174 for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { | 4039 for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { |
| 3175 cur = findPosH(this.doc, cur, dir, unit, visually); | 4040 cur = findPosH(this.doc, cur, dir, unit, visually); |
| 3176 if (cur.hitSide) break; | 4041 if (cur.hitSide) break; |
| 3177 } | 4042 } |
| 3178 return cur; | 4043 return cur; |
| 3179 }, | 4044 }, |
| 3180 | 4045 |
| 3181 moveH: operation(null, function(dir, unit) { | 4046 moveH: methodOp(function(dir, unit) { |
| 3182 var sel = this.doc.sel, pos; | 4047 var cm = this; |
| 3183 if (sel.shift || sel.extend || posEq(sel.from, sel.to)) | 4048 cm.extendSelectionsBy(function(range) { |
| 3184 pos = findPosH(this.doc, sel.head, dir, unit, this.options.rtlMoveVisual
ly); | 4049 if (cm.display.shift || cm.doc.extend || range.empty()) |
| 3185 else | 4050 return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisua
lly); |
| 3186 pos = dir < 0 ? sel.from : sel.to; | 4051 else |
| 3187 extendSelection(this.doc, pos, pos, dir); | 4052 return dir < 0 ? range.from() : range.to(); |
| 4053 }, sel_move); |
| 3188 }), | 4054 }), |
| 3189 | 4055 |
| 3190 deleteH: operation(null, function(dir, unit) { | 4056 deleteH: methodOp(function(dir, unit) { |
| 3191 var sel = this.doc.sel; | 4057 var sel = this.doc.sel, doc = this.doc; |
| 3192 if (!posEq(sel.from, sel.to)) replaceRange(this.doc, "", sel.from, sel.to,
"+delete"); | 4058 if (sel.somethingSelected()) |
| 3193 else replaceRange(this.doc, "", sel.from, findPosH(this.doc, sel.head, dir
, unit, false), "+delete"); | 4059 doc.replaceSelection("", null, "+delete"); |
| 3194 this.curOp.userSelChange = true; | 4060 else |
| 4061 deleteNearSelection(this, function(range) { |
| 4062 var other = findPosH(doc, range.head, dir, unit, false); |
| 4063 return dir < 0 ? {from: other, to: range.head} : {from: range.head, to
: other}; |
| 4064 }); |
| 3195 }), | 4065 }), |
| 3196 | 4066 |
| 3197 findPosV: function(from, amount, unit, goalColumn) { | 4067 findPosV: function(from, amount, unit, goalColumn) { |
| 3198 var dir = 1, x = goalColumn; | 4068 var dir = 1, x = goalColumn; |
| 3199 if (amount < 0) { dir = -1; amount = -amount; } | 4069 if (amount < 0) { dir = -1; amount = -amount; } |
| 3200 for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { | 4070 for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { |
| 3201 var coords = cursorCoords(this, cur, "div"); | 4071 var coords = cursorCoords(this, cur, "div"); |
| 3202 if (x == null) x = coords.left; | 4072 if (x == null) x = coords.left; |
| 3203 else coords.left = x; | 4073 else coords.left = x; |
| 3204 cur = findPosV(this, coords, dir, unit); | 4074 cur = findPosV(this, coords, dir, unit); |
| 3205 if (cur.hitSide) break; | 4075 if (cur.hitSide) break; |
| 3206 } | 4076 } |
| 3207 return cur; | 4077 return cur; |
| 3208 }, | 4078 }, |
| 3209 | 4079 |
| 3210 moveV: operation(null, function(dir, unit) { | 4080 moveV: methodOp(function(dir, unit) { |
| 3211 var sel = this.doc.sel, target, goal; | 4081 var cm = this, doc = this.doc, goals = []; |
| 3212 if (sel.shift || sel.extend || posEq(sel.from, sel.to)) { | 4082 var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelect
ed(); |
| 3213 var pos = cursorCoords(this, sel.head, "div"); | 4083 doc.extendSelectionsBy(function(range) { |
| 3214 if (sel.goalColumn != null) pos.left = sel.goalColumn; | 4084 if (collapse) |
| 3215 target = findPosV(this, pos, dir, unit); | 4085 return dir < 0 ? range.from() : range.to(); |
| 3216 if (unit == "page") addToScrollPos(this, 0, charCoords(this, target, "di
v").top - pos.top); | 4086 var headPos = cursorCoords(cm, range.head, "div"); |
| 3217 goal = pos.left; | 4087 if (range.goalColumn != null) headPos.left = range.goalColumn; |
| 3218 } else { | 4088 goals.push(headPos.left); |
| 3219 target = dir < 0 ? sel.from : sel.to; | 4089 var pos = findPosV(cm, headPos, dir, unit); |
| 3220 } | 4090 if (unit == "page" && range == doc.sel.primary()) |
| 3221 extendSelection(this.doc, target, target, dir); | 4091 addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top)
; |
| 3222 if (goal != null) sel.goalColumn = goal; | 4092 return pos; |
| 4093 }, sel_move); |
| 4094 if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++) |
| 4095 doc.sel.ranges[i].goalColumn = goals[i]; |
| 3223 }), | 4096 }), |
| 3224 | 4097 |
| 3225 toggleOverwrite: function(value) { | 4098 toggleOverwrite: function(value) { |
| 3226 if (value != null && value == this.state.overwrite) return; | 4099 if (value != null && value == this.state.overwrite) return; |
| 3227 if (this.state.overwrite = !this.state.overwrite) | 4100 if (this.state.overwrite = !this.state.overwrite) |
| 3228 this.display.cursor.className += " CodeMirror-overwrite"; | 4101 this.display.cursorDiv.className += " CodeMirror-overwrite"; |
| 3229 else | 4102 else |
| 3230 this.display.cursor.className = this.display.cursor.className.replace("
CodeMirror-overwrite", ""); | 4103 this.display.cursorDiv.className = this.display.cursorDiv.className.repl
ace(" CodeMirror-overwrite", ""); |
| 4104 |
| 4105 signal(this, "overwriteToggle", this, this.state.overwrite); |
| 3231 }, | 4106 }, |
| 3232 hasFocus: function() { return document.activeElement == this.display.input;
}, | 4107 hasFocus: function() { return activeElt() == this.display.input; }, |
| 3233 | 4108 |
| 3234 scrollTo: operation(null, function(x, y) { | 4109 scrollTo: methodOp(function(x, y) { |
| 3235 updateScrollPos(this, x, y); | 4110 if (x != null || y != null) resolveScrollToPos(this); |
| 4111 if (x != null) this.curOp.scrollLeft = x; |
| 4112 if (y != null) this.curOp.scrollTop = y; |
| 3236 }), | 4113 }), |
| 3237 getScrollInfo: function() { | 4114 getScrollInfo: function() { |
| 3238 var scroller = this.display.scroller, co = scrollerCutOff; | 4115 var scroller = this.display.scroller, co = scrollerCutOff; |
| 3239 return {left: scroller.scrollLeft, top: scroller.scrollTop, | 4116 return {left: scroller.scrollLeft, top: scroller.scrollTop, |
| 3240 height: scroller.scrollHeight - co, width: scroller.scrollWidth -
co, | 4117 height: scroller.scrollHeight - co, width: scroller.scrollWidth -
co, |
| 3241 clientHeight: scroller.clientHeight - co, clientWidth: scroller.cl
ientWidth - co}; | 4118 clientHeight: scroller.clientHeight - co, clientWidth: scroller.cl
ientWidth - co}; |
| 3242 }, | 4119 }, |
| 3243 | 4120 |
| 3244 scrollIntoView: operation(null, function(range, margin) { | 4121 scrollIntoView: methodOp(function(range, margin) { |
| 3245 if (range == null) range = {from: this.doc.sel.head, to: null}; | 4122 if (range == null) { |
| 3246 else if (typeof range == "number") range = {from: Pos(range, 0), to: null}
; | 4123 range = {from: this.doc.sel.primary().head, to: null}; |
| 3247 else if (range.from == null) range = {from: range, to: null}; | 4124 if (margin == null) margin = this.options.cursorScrollMargin; |
| 4125 } else if (typeof range == "number") { |
| 4126 range = {from: Pos(range, 0), to: null}; |
| 4127 } else if (range.from == null) { |
| 4128 range = {from: range, to: null}; |
| 4129 } |
| 3248 if (!range.to) range.to = range.from; | 4130 if (!range.to) range.to = range.from; |
| 3249 if (!margin) margin = 0; | 4131 range.margin = margin || 0; |
| 3250 | 4132 |
| 3251 var coords = range; | |
| 3252 if (range.from.line != null) { | 4133 if (range.from.line != null) { |
| 3253 this.curOp.scrollToPos = {from: range.from, to: range.to, margin: margin
}; | 4134 resolveScrollToPos(this); |
| 3254 coords = {from: cursorCoords(this, range.from), | 4135 this.curOp.scrollToPos = range; |
| 3255 to: cursorCoords(this, range.to)}; | 4136 } else { |
| 4137 var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.l
eft), |
| 4138 Math.min(range.from.top, range.to.top) - r
ange.margin, |
| 4139 Math.max(range.from.right, range.to.right)
, |
| 4140 Math.max(range.from.bottom, range.to.botto
m) + range.margin); |
| 4141 this.scrollTo(sPos.scrollLeft, sPos.scrollTop); |
| 3256 } | 4142 } |
| 3257 var sPos = calculateScrollPos(this, Math.min(coords.from.left, coords.to.l
eft), | |
| 3258 Math.min(coords.from.top, coords.to.top) - m
argin, | |
| 3259 Math.max(coords.from.right, coords.to.right)
, | |
| 3260 Math.max(coords.from.bottom, coords.to.botto
m) + margin); | |
| 3261 updateScrollPos(this, sPos.scrollLeft, sPos.scrollTop); | |
| 3262 }), | 4143 }), |
| 3263 | 4144 |
| 3264 setSize: operation(null, function(width, height) { | 4145 setSize: methodOp(function(width, height) { |
| 3265 function interpret(val) { | 4146 function interpret(val) { |
| 3266 return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px"
: val; | 4147 return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px"
: val; |
| 3267 } | 4148 } |
| 3268 if (width != null) this.display.wrapper.style.width = interpret(width); | 4149 if (width != null) this.display.wrapper.style.width = interpret(width); |
| 3269 if (height != null) this.display.wrapper.style.height = interpret(height); | 4150 if (height != null) this.display.wrapper.style.height = interpret(height); |
| 3270 if (this.options.lineWrapping) | 4151 if (this.options.lineWrapping) clearLineMeasurementCache(this); |
| 3271 this.display.measureLineCache.length = this.display.measureLineCachePos
= 0; | |
| 3272 this.curOp.forceUpdate = true; | 4152 this.curOp.forceUpdate = true; |
| 3273 signal(this, "refresh", this); | 4153 signal(this, "refresh", this); |
| 3274 }), | 4154 }), |
| 3275 | 4155 |
| 3276 operation: function(f){return runInOp(this, f);}, | 4156 operation: function(f){return runInOp(this, f);}, |
| 3277 | 4157 |
| 3278 refresh: operation(null, function() { | 4158 refresh: methodOp(function() { |
| 3279 var oldHeight = this.display.cachedTextHeight; | 4159 var oldHeight = this.display.cachedTextHeight; |
| 4160 regChange(this); |
| 3280 clearCaches(this); | 4161 clearCaches(this); |
| 3281 updateScrollPos(this, this.doc.scrollLeft, this.doc.scrollTop); | 4162 this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop); |
| 3282 regChange(this); | |
| 3283 if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) >
.5) | 4163 if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) >
.5) |
| 3284 estimateLineHeights(this); | 4164 estimateLineHeights(this); |
| 3285 signal(this, "refresh", this); | 4165 signal(this, "refresh", this); |
| 3286 }), | 4166 }), |
| 3287 | 4167 |
| 3288 swapDoc: operation(null, function(doc) { | 4168 swapDoc: methodOp(function(doc) { |
| 3289 var old = this.doc; | 4169 var old = this.doc; |
| 3290 old.cm = null; | 4170 old.cm = null; |
| 3291 attachDoc(this, doc); | 4171 attachDoc(this, doc); |
| 3292 clearCaches(this); | 4172 clearCaches(this); |
| 3293 resetInput(this, true); | 4173 resetInput(this); |
| 3294 updateScrollPos(this, doc.scrollLeft, doc.scrollTop); | 4174 this.scrollTo(doc.scrollLeft, doc.scrollTop); |
| 3295 signalLater(this, "swapDoc", this, old); | 4175 signalLater(this, "swapDoc", this, old); |
| 3296 return old; | 4176 return old; |
| 3297 }), | 4177 }), |
| 3298 | 4178 |
| 3299 getInputField: function(){return this.display.input;}, | 4179 getInputField: function(){return this.display.input;}, |
| 3300 getWrapperElement: function(){return this.display.wrapper;}, | 4180 getWrapperElement: function(){return this.display.wrapper;}, |
| 3301 getScrollerElement: function(){return this.display.scroller;}, | 4181 getScrollerElement: function(){return this.display.scroller;}, |
| 3302 getGutterElement: function(){return this.display.gutters;} | 4182 getGutterElement: function(){return this.display.gutters;} |
| 3303 }; | 4183 }; |
| 3304 eventMixin(CodeMirror); | 4184 eventMixin(CodeMirror); |
| 3305 | 4185 |
| 3306 // OPTION DEFAULTS | 4186 // OPTION DEFAULTS |
| 3307 | 4187 |
| 3308 var optionHandlers = CodeMirror.optionHandlers = {}; | |
| 3309 | |
| 3310 // The default configuration options. | 4188 // The default configuration options. |
| 3311 var defaults = CodeMirror.defaults = {}; | 4189 var defaults = CodeMirror.defaults = {}; |
| 4190 // Functions to run when options are changed. |
| 4191 var optionHandlers = CodeMirror.optionHandlers = {}; |
| 3312 | 4192 |
| 3313 function option(name, deflt, handle, notOnInit) { | 4193 function option(name, deflt, handle, notOnInit) { |
| 3314 CodeMirror.defaults[name] = deflt; | 4194 CodeMirror.defaults[name] = deflt; |
| 3315 if (handle) optionHandlers[name] = | 4195 if (handle) optionHandlers[name] = |
| 3316 notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);
} : handle; | 4196 notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);
} : handle; |
| 3317 } | 4197 } |
| 3318 | 4198 |
| 4199 // Passed to option handlers when there is no old value. |
| 3319 var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}}
; | 4200 var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}}
; |
| 3320 | 4201 |
| 3321 // These two are, on init, called from the constructor because they | 4202 // These two are, on init, called from the constructor because they |
| 3322 // have to be initialized before the editor can start at all. | 4203 // have to be initialized before the editor can start at all. |
| 3323 option("value", "", function(cm, val) { | 4204 option("value", "", function(cm, val) { |
| 3324 cm.setValue(val); | 4205 cm.setValue(val); |
| 3325 }, true); | 4206 }, true); |
| 3326 option("mode", null, function(cm, val) { | 4207 option("mode", null, function(cm, val) { |
| 3327 cm.doc.modeOption = val; | 4208 cm.doc.modeOption = val; |
| 3328 loadMode(cm); | 4209 loadMode(cm); |
| (...skipping 16 matching lines...) Expand all Loading... |
| 3345 option("rtlMoveVisually", !windows); | 4226 option("rtlMoveVisually", !windows); |
| 3346 option("wholeLineUpdateBefore", true); | 4227 option("wholeLineUpdateBefore", true); |
| 3347 | 4228 |
| 3348 option("theme", "default", function(cm) { | 4229 option("theme", "default", function(cm) { |
| 3349 themeChanged(cm); | 4230 themeChanged(cm); |
| 3350 guttersChanged(cm); | 4231 guttersChanged(cm); |
| 3351 }, true); | 4232 }, true); |
| 3352 option("keyMap", "default", keyMapChanged); | 4233 option("keyMap", "default", keyMapChanged); |
| 3353 option("extraKeys", null); | 4234 option("extraKeys", null); |
| 3354 | 4235 |
| 3355 option("onKeyEvent", null); | |
| 3356 option("onDragEvent", null); | |
| 3357 | |
| 3358 option("lineWrapping", false, wrappingChanged, true); | 4236 option("lineWrapping", false, wrappingChanged, true); |
| 3359 option("gutters", [], function(cm) { | 4237 option("gutters", [], function(cm) { |
| 3360 setGuttersForLineNumbers(cm.options); | 4238 setGuttersForLineNumbers(cm.options); |
| 3361 guttersChanged(cm); | 4239 guttersChanged(cm); |
| 3362 }, true); | 4240 }, true); |
| 3363 option("fixedGutter", true, function(cm, val) { | 4241 option("fixedGutter", true, function(cm, val) { |
| 3364 cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px
" : "0"; | 4242 cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px
" : "0"; |
| 3365 cm.refresh(); | 4243 cm.refresh(); |
| 3366 }, true); | 4244 }, true); |
| 3367 option("coverGutterNextToScrollbar", false, updateScrollbars, true); | 4245 option("coverGutterNextToScrollbar", false, updateScrollbars, true); |
| 3368 option("lineNumbers", false, function(cm) { | 4246 option("lineNumbers", false, function(cm) { |
| 3369 setGuttersForLineNumbers(cm.options); | 4247 setGuttersForLineNumbers(cm.options); |
| 3370 guttersChanged(cm); | 4248 guttersChanged(cm); |
| 3371 }, true); | 4249 }, true); |
| 3372 option("firstLineNumber", 1, guttersChanged, true); | 4250 option("firstLineNumber", 1, guttersChanged, true); |
| 3373 option("lineNumberFormatter", function(integer) {return integer;}, guttersChan
ged, true); | 4251 option("lineNumberFormatter", function(integer) {return integer;}, guttersChan
ged, true); |
| 3374 option("showCursorWhenSelecting", false, updateSelection, true); | 4252 option("showCursorWhenSelecting", false, updateSelection, true); |
| 3375 | 4253 |
| 3376 option("resetSelectionOnContextMenu", true); | 4254 option("resetSelectionOnContextMenu", true); |
| 3377 | 4255 |
| 3378 option("readOnly", false, function(cm, val) { | 4256 option("readOnly", false, function(cm, val) { |
| 3379 if (val == "nocursor") { | 4257 if (val == "nocursor") { |
| 3380 onBlur(cm); | 4258 onBlur(cm); |
| 3381 cm.display.input.blur(); | 4259 cm.display.input.blur(); |
| 3382 cm.display.disabled = true; | 4260 cm.display.disabled = true; |
| 3383 } else { | 4261 } else { |
| 3384 cm.display.disabled = false; | 4262 cm.display.disabled = false; |
| 3385 if (!val) resetInput(cm, true); | 4263 if (!val) resetInput(cm); |
| 3386 } | 4264 } |
| 3387 }); | 4265 }); |
| 3388 option("disableInput", false, function(cm, val) {if (!val) resetInput(cm, true
);}, true); | 4266 option("disableInput", false, function(cm, val) {if (!val) resetInput(cm);}, t
rue); |
| 3389 option("dragDrop", true); | 4267 option("dragDrop", true); |
| 3390 | 4268 |
| 3391 option("cursorBlinkRate", 530); | 4269 option("cursorBlinkRate", 530); |
| 3392 option("cursorScrollMargin", 0); | 4270 option("cursorScrollMargin", 0); |
| 3393 option("cursorHeight", 1); | 4271 option("cursorHeight", 1); |
| 3394 option("workTime", 100); | 4272 option("workTime", 100); |
| 3395 option("workDelay", 100); | 4273 option("workDelay", 100); |
| 3396 option("flattenSpans", true, resetModeState, true); | 4274 option("flattenSpans", true, resetModeState, true); |
| 3397 option("addModeClass", false, resetModeState, true); | 4275 option("addModeClass", false, resetModeState, true); |
| 3398 option("pollInterval", 100); | 4276 option("pollInterval", 100); |
| 3399 option("undoDepth", 40, function(cm, val){cm.doc.history.undoDepth = val;}); | 4277 option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;}); |
| 3400 option("historyEventDelay", 500); | 4278 option("historyEventDelay", 1250); |
| 3401 option("viewportMargin", 10, function(cm){cm.refresh();}, true); | 4279 option("viewportMargin", 10, function(cm){cm.refresh();}, true); |
| 3402 option("maxHighlightLength", 10000, resetModeState, true); | 4280 option("maxHighlightLength", 10000, resetModeState, true); |
| 3403 option("crudeMeasuringFrom", 10000); | |
| 3404 option("moveInputWithCursor", true, function(cm, val) { | 4281 option("moveInputWithCursor", true, function(cm, val) { |
| 3405 if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0
; | 4282 if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0
; |
| 3406 }); | 4283 }); |
| 3407 | 4284 |
| 3408 option("tabindex", null, function(cm, val) { | 4285 option("tabindex", null, function(cm, val) { |
| 3409 cm.display.input.tabIndex = val || ""; | 4286 cm.display.input.tabIndex = val || ""; |
| 3410 }); | 4287 }); |
| 3411 option("autofocus", null); | 4288 option("autofocus", null); |
| 3412 | 4289 |
| 3413 // MODE DEFINITION AND QUERYING | 4290 // MODE DEFINITION AND QUERYING |
| 3414 | 4291 |
| 3415 // Known modes, by name and by MIME | 4292 // Known modes, by name and by MIME |
| 3416 var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; | 4293 var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; |
| 3417 | 4294 |
| 4295 // Extra arguments are stored as the mode's dependencies, which is |
| 4296 // used by (legacy) mechanisms like loadmode.js to automatically |
| 4297 // load a mode. (Preferred mechanism is the require/define calls.) |
| 3418 CodeMirror.defineMode = function(name, mode) { | 4298 CodeMirror.defineMode = function(name, mode) { |
| 3419 if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode =
name; | 4299 if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode =
name; |
| 3420 if (arguments.length > 2) { | 4300 if (arguments.length > 2) { |
| 3421 mode.dependencies = []; | 4301 mode.dependencies = []; |
| 3422 for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(argument
s[i]); | 4302 for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(argument
s[i]); |
| 3423 } | 4303 } |
| 3424 modes[name] = mode; | 4304 modes[name] = mode; |
| 3425 }; | 4305 }; |
| 3426 | 4306 |
| 3427 CodeMirror.defineMIME = function(mime, spec) { | 4307 CodeMirror.defineMIME = function(mime, spec) { |
| 3428 mimeModes[mime] = spec; | 4308 mimeModes[mime] = spec; |
| 3429 }; | 4309 }; |
| 3430 | 4310 |
| 4311 // Given a MIME type, a {name, ...options} config object, or a name |
| 4312 // string, return a mode config object. |
| 3431 CodeMirror.resolveMode = function(spec) { | 4313 CodeMirror.resolveMode = function(spec) { |
| 3432 if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { | 4314 if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { |
| 3433 spec = mimeModes[spec]; | 4315 spec = mimeModes[spec]; |
| 3434 } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(
spec.name)) { | 4316 } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(
spec.name)) { |
| 3435 var found = mimeModes[spec.name]; | 4317 var found = mimeModes[spec.name]; |
| 4318 if (typeof found == "string") found = {name: found}; |
| 3436 spec = createObj(found, spec); | 4319 spec = createObj(found, spec); |
| 3437 spec.name = found.name; | 4320 spec.name = found.name; |
| 3438 } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec))
{ | 4321 } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec))
{ |
| 3439 return CodeMirror.resolveMode("application/xml"); | 4322 return CodeMirror.resolveMode("application/xml"); |
| 3440 } | 4323 } |
| 3441 if (typeof spec == "string") return {name: spec}; | 4324 if (typeof spec == "string") return {name: spec}; |
| 3442 else return spec || {name: "null"}; | 4325 else return spec || {name: "null"}; |
| 3443 }; | 4326 }; |
| 3444 | 4327 |
| 4328 // Given a mode spec (anything that resolveMode accepts), find and |
| 4329 // initialize an actual mode object. |
| 3445 CodeMirror.getMode = function(options, spec) { | 4330 CodeMirror.getMode = function(options, spec) { |
| 3446 var spec = CodeMirror.resolveMode(spec); | 4331 var spec = CodeMirror.resolveMode(spec); |
| 3447 var mfactory = modes[spec.name]; | 4332 var mfactory = modes[spec.name]; |
| 3448 if (!mfactory) return CodeMirror.getMode(options, "text/plain"); | 4333 if (!mfactory) return CodeMirror.getMode(options, "text/plain"); |
| 3449 var modeObj = mfactory(options, spec); | 4334 var modeObj = mfactory(options, spec); |
| 3450 if (modeExtensions.hasOwnProperty(spec.name)) { | 4335 if (modeExtensions.hasOwnProperty(spec.name)) { |
| 3451 var exts = modeExtensions[spec.name]; | 4336 var exts = modeExtensions[spec.name]; |
| 3452 for (var prop in exts) { | 4337 for (var prop in exts) { |
| 3453 if (!exts.hasOwnProperty(prop)) continue; | 4338 if (!exts.hasOwnProperty(prop)) continue; |
| 3454 if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; | 4339 if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; |
| 3455 modeObj[prop] = exts[prop]; | 4340 modeObj[prop] = exts[prop]; |
| 3456 } | 4341 } |
| 3457 } | 4342 } |
| 3458 modeObj.name = spec.name; | 4343 modeObj.name = spec.name; |
| 3459 if (spec.helperType) modeObj.helperType = spec.helperType; | 4344 if (spec.helperType) modeObj.helperType = spec.helperType; |
| 3460 if (spec.modeProps) for (var prop in spec.modeProps) | 4345 if (spec.modeProps) for (var prop in spec.modeProps) |
| 3461 modeObj[prop] = spec.modeProps[prop]; | 4346 modeObj[prop] = spec.modeProps[prop]; |
| 3462 | 4347 |
| 3463 return modeObj; | 4348 return modeObj; |
| 3464 }; | 4349 }; |
| 3465 | 4350 |
| 4351 // Minimal default mode. |
| 3466 CodeMirror.defineMode("null", function() { | 4352 CodeMirror.defineMode("null", function() { |
| 3467 return {token: function(stream) {stream.skipToEnd();}}; | 4353 return {token: function(stream) {stream.skipToEnd();}}; |
| 3468 }); | 4354 }); |
| 3469 CodeMirror.defineMIME("text/plain", "null"); | 4355 CodeMirror.defineMIME("text/plain", "null"); |
| 3470 | 4356 |
| 4357 // This can be used to attach properties to mode objects from |
| 4358 // outside the actual mode definition. |
| 3471 var modeExtensions = CodeMirror.modeExtensions = {}; | 4359 var modeExtensions = CodeMirror.modeExtensions = {}; |
| 3472 CodeMirror.extendMode = function(mode, properties) { | 4360 CodeMirror.extendMode = function(mode, properties) { |
| 3473 var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (mod
eExtensions[mode] = {}); | 4361 var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (mod
eExtensions[mode] = {}); |
| 3474 copyObj(properties, exts); | 4362 copyObj(properties, exts); |
| 3475 }; | 4363 }; |
| 3476 | 4364 |
| 3477 // EXTENSIONS | 4365 // EXTENSIONS |
| 3478 | 4366 |
| 3479 CodeMirror.defineExtension = function(name, func) { | 4367 CodeMirror.defineExtension = function(name, func) { |
| 3480 CodeMirror.prototype[name] = func; | 4368 CodeMirror.prototype[name] = func; |
| 3481 }; | 4369 }; |
| 3482 CodeMirror.defineDocExtension = function(name, func) { | 4370 CodeMirror.defineDocExtension = function(name, func) { |
| 3483 Doc.prototype[name] = func; | 4371 Doc.prototype[name] = func; |
| 3484 }; | 4372 }; |
| 3485 CodeMirror.defineOption = option; | 4373 CodeMirror.defineOption = option; |
| 3486 | 4374 |
| 3487 var initHooks = []; | 4375 var initHooks = []; |
| 3488 CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; | 4376 CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; |
| 3489 | 4377 |
| 3490 var helpers = CodeMirror.helpers = {}; | 4378 var helpers = CodeMirror.helpers = {}; |
| 3491 CodeMirror.registerHelper = function(type, name, value) { | 4379 CodeMirror.registerHelper = function(type, name, value) { |
| 3492 if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_glob
al: []}; | 4380 if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_glob
al: []}; |
| 3493 helpers[type][name] = value; | 4381 helpers[type][name] = value; |
| 3494 }; | 4382 }; |
| 3495 CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { | 4383 CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { |
| 3496 CodeMirror.registerHelper(type, name, value); | 4384 CodeMirror.registerHelper(type, name, value); |
| 3497 helpers[type]._global.push({pred: predicate, val: value}); | 4385 helpers[type]._global.push({pred: predicate, val: value}); |
| 3498 }; | 4386 }; |
| 3499 | 4387 |
| 3500 // UTILITIES | |
| 3501 | |
| 3502 CodeMirror.isWordChar = isWordChar; | |
| 3503 | |
| 3504 // MODE STATE HANDLING | 4388 // MODE STATE HANDLING |
| 3505 | 4389 |
| 3506 // Utility functions for working with state. Exported because modes | 4390 // Utility functions for working with state. Exported because nested |
| 3507 // sometimes need to do this. | 4391 // modes need to do this for their inner modes. |
| 3508 function copyState(mode, state) { | 4392 |
| 4393 var copyState = CodeMirror.copyState = function(mode, state) { |
| 3509 if (state === true) return state; | 4394 if (state === true) return state; |
| 3510 if (mode.copyState) return mode.copyState(state); | 4395 if (mode.copyState) return mode.copyState(state); |
| 3511 var nstate = {}; | 4396 var nstate = {}; |
| 3512 for (var n in state) { | 4397 for (var n in state) { |
| 3513 var val = state[n]; | 4398 var val = state[n]; |
| 3514 if (val instanceof Array) val = val.concat([]); | 4399 if (val instanceof Array) val = val.concat([]); |
| 3515 nstate[n] = val; | 4400 nstate[n] = val; |
| 3516 } | 4401 } |
| 3517 return nstate; | 4402 return nstate; |
| 3518 } | 4403 }; |
| 3519 CodeMirror.copyState = copyState; | |
| 3520 | 4404 |
| 3521 function startState(mode, a1, a2) { | 4405 var startState = CodeMirror.startState = function(mode, a1, a2) { |
| 3522 return mode.startState ? mode.startState(a1, a2) : true; | 4406 return mode.startState ? mode.startState(a1, a2) : true; |
| 3523 } | 4407 }; |
| 3524 CodeMirror.startState = startState; | |
| 3525 | 4408 |
| 4409 // Given a mode and a state (for that mode), find the inner mode and |
| 4410 // state at the position that the state refers to. |
| 3526 CodeMirror.innerMode = function(mode, state) { | 4411 CodeMirror.innerMode = function(mode, state) { |
| 3527 while (mode.innerMode) { | 4412 while (mode.innerMode) { |
| 3528 var info = mode.innerMode(state); | 4413 var info = mode.innerMode(state); |
| 3529 if (!info || info.mode == mode) break; | 4414 if (!info || info.mode == mode) break; |
| 3530 state = info.state; | 4415 state = info.state; |
| 3531 mode = info.mode; | 4416 mode = info.mode; |
| 3532 } | 4417 } |
| 3533 return info || {mode: mode, state: state}; | 4418 return info || {mode: mode, state: state}; |
| 3534 }; | 4419 }; |
| 3535 | 4420 |
| 3536 // STANDARD COMMANDS | 4421 // STANDARD COMMANDS |
| 3537 | 4422 |
| 4423 // Commands are parameter-less actions that can be performed on an |
| 4424 // editor, mostly used for keybindings. |
| 3538 var commands = CodeMirror.commands = { | 4425 var commands = CodeMirror.commands = { |
| 3539 selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.last
Line()));}, | 4426 selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.last
Line()), sel_dontScroll);}, |
| 4427 singleSelection: function(cm) { |
| 4428 cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScro
ll); |
| 4429 }, |
| 3540 killLine: function(cm) { | 4430 killLine: function(cm) { |
| 3541 var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from
, to); | 4431 deleteNearSelection(cm, function(range) { |
| 3542 if (!sel && cm.getLine(from.line).length == from.ch) | 4432 if (range.empty()) { |
| 3543 cm.replaceRange("", from, Pos(from.line + 1, 0), "+delete"); | 4433 var len = getLine(cm.doc, range.head.line).text.length; |
| 3544 else cm.replaceRange("", from, sel ? to : Pos(from.line), "+delete"); | 4434 if (range.head.ch == len && range.head.line < cm.lastLine()) |
| 4435 return {from: range.head, to: Pos(range.head.line + 1, 0)}; |
| 4436 else |
| 4437 return {from: range.head, to: Pos(range.head.line, len)}; |
| 4438 } else { |
| 4439 return {from: range.from(), to: range.to()}; |
| 4440 } |
| 4441 }); |
| 3545 }, | 4442 }, |
| 3546 deleteLine: function(cm) { | 4443 deleteLine: function(cm) { |
| 3547 var l = cm.getCursor().line; | 4444 deleteNearSelection(cm, function(range) { |
| 3548 cm.replaceRange("", Pos(l, 0), Pos(l), "+delete"); | 4445 return {from: Pos(range.from().line, 0), |
| 4446 to: clipPos(cm.doc, Pos(range.to().line + 1, 0))}; |
| 4447 }); |
| 3549 }, | 4448 }, |
| 3550 delLineLeft: function(cm) { | 4449 delLineLeft: function(cm) { |
| 3551 var cur = cm.getCursor(); | 4450 deleteNearSelection(cm, function(range) { |
| 3552 cm.replaceRange("", Pos(cur.line, 0), cur, "+delete"); | 4451 return {from: Pos(range.from().line, 0), to: range.from()}; |
| 4452 }); |
| 3553 }, | 4453 }, |
| 3554 undo: function(cm) {cm.undo();}, | 4454 undo: function(cm) {cm.undo();}, |
| 3555 redo: function(cm) {cm.redo();}, | 4455 redo: function(cm) {cm.redo();}, |
| 4456 undoSelection: function(cm) {cm.undoSelection();}, |
| 4457 redoSelection: function(cm) {cm.redoSelection();}, |
| 3556 goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));}, | 4458 goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));}, |
| 3557 goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));}, | 4459 goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));}, |
| 3558 goLineStart: function(cm) { | 4460 goLineStart: function(cm) { |
| 3559 cm.extendSelection(lineStart(cm, cm.getCursor().line)); | 4461 cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.li
ne); }, sel_move); |
| 3560 }, | 4462 }, |
| 3561 goLineStartSmart: function(cm) { | 4463 goLineStartSmart: function(cm) { |
| 3562 var cur = cm.getCursor(), start = lineStart(cm, cur.line); | 4464 cm.extendSelectionsBy(function(range) { |
| 3563 var line = cm.getLineHandle(start.line); | 4465 var start = lineStart(cm, range.head.line); |
| 3564 var order = getOrder(line); | 4466 var line = cm.getLineHandle(start.line); |
| 3565 if (!order || order[0].level == 0) { | 4467 var order = getOrder(line); |
| 3566 var firstNonWS = Math.max(0, line.text.search(/\S/)); | 4468 if (!order || order[0].level == 0) { |
| 3567 var inWS = cur.line == start.line && cur.ch <= firstNonWS && cur.ch; | 4469 var firstNonWS = Math.max(0, line.text.search(/\S/)); |
| 3568 cm.extendSelection(Pos(start.line, inWS ? 0 : firstNonWS)); | 4470 var inWS = range.head.line == start.line && range.head.ch <= firstNonW
S && range.head.ch; |
| 3569 } else cm.extendSelection(start); | 4471 return Pos(start.line, inWS ? 0 : firstNonWS); |
| 4472 } |
| 4473 return start; |
| 4474 }, sel_move); |
| 3570 }, | 4475 }, |
| 3571 goLineEnd: function(cm) { | 4476 goLineEnd: function(cm) { |
| 3572 cm.extendSelection(lineEnd(cm, cm.getCursor().line)); | 4477 cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line
); }, sel_move); |
| 3573 }, | 4478 }, |
| 3574 goLineRight: function(cm) { | 4479 goLineRight: function(cm) { |
| 3575 var top = cm.charCoords(cm.getCursor(), "div").top + 5; | 4480 cm.extendSelectionsBy(function(range) { |
| 3576 cm.extendSelection(cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 1
00, top: top}, "div")); | 4481 var top = cm.charCoords(range.head, "div").top + 5; |
| 4482 return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: t
op}, "div"); |
| 4483 }, sel_move); |
| 3577 }, | 4484 }, |
| 3578 goLineLeft: function(cm) { | 4485 goLineLeft: function(cm) { |
| 3579 var top = cm.charCoords(cm.getCursor(), "div").top + 5; | 4486 cm.extendSelectionsBy(function(range) { |
| 3580 cm.extendSelection(cm.coordsChar({left: 0, top: top}, "div")); | 4487 var top = cm.charCoords(range.head, "div").top + 5; |
| 4488 return cm.coordsChar({left: 0, top: top}, "div"); |
| 4489 }, sel_move); |
| 3581 }, | 4490 }, |
| 3582 goLineUp: function(cm) {cm.moveV(-1, "line");}, | 4491 goLineUp: function(cm) {cm.moveV(-1, "line");}, |
| 3583 goLineDown: function(cm) {cm.moveV(1, "line");}, | 4492 goLineDown: function(cm) {cm.moveV(1, "line");}, |
| 3584 goPageUp: function(cm) {cm.moveV(-1, "page");}, | 4493 goPageUp: function(cm) {cm.moveV(-1, "page");}, |
| 3585 goPageDown: function(cm) {cm.moveV(1, "page");}, | 4494 goPageDown: function(cm) {cm.moveV(1, "page");}, |
| 3586 goCharLeft: function(cm) {cm.moveH(-1, "char");}, | 4495 goCharLeft: function(cm) {cm.moveH(-1, "char");}, |
| 3587 goCharRight: function(cm) {cm.moveH(1, "char");}, | 4496 goCharRight: function(cm) {cm.moveH(1, "char");}, |
| 3588 goColumnLeft: function(cm) {cm.moveH(-1, "column");}, | 4497 goColumnLeft: function(cm) {cm.moveH(-1, "column");}, |
| 3589 goColumnRight: function(cm) {cm.moveH(1, "column");}, | 4498 goColumnRight: function(cm) {cm.moveH(1, "column");}, |
| 3590 goWordLeft: function(cm) {cm.moveH(-1, "word");}, | 4499 goWordLeft: function(cm) {cm.moveH(-1, "word");}, |
| 3591 goGroupRight: function(cm) {cm.moveH(1, "group");}, | 4500 goGroupRight: function(cm) {cm.moveH(1, "group");}, |
| 3592 goGroupLeft: function(cm) {cm.moveH(-1, "group");}, | 4501 goGroupLeft: function(cm) {cm.moveH(-1, "group");}, |
| 3593 goWordRight: function(cm) {cm.moveH(1, "word");}, | 4502 goWordRight: function(cm) {cm.moveH(1, "word");}, |
| 3594 delCharBefore: function(cm) {cm.deleteH(-1, "char");}, | 4503 delCharBefore: function(cm) {cm.deleteH(-1, "char");}, |
| 3595 delCharAfter: function(cm) {cm.deleteH(1, "char");}, | 4504 delCharAfter: function(cm) {cm.deleteH(1, "char");}, |
| 3596 delWordBefore: function(cm) {cm.deleteH(-1, "word");}, | 4505 delWordBefore: function(cm) {cm.deleteH(-1, "word");}, |
| 3597 delWordAfter: function(cm) {cm.deleteH(1, "word");}, | 4506 delWordAfter: function(cm) {cm.deleteH(1, "word");}, |
| 3598 delGroupBefore: function(cm) {cm.deleteH(-1, "group");}, | 4507 delGroupBefore: function(cm) {cm.deleteH(-1, "group");}, |
| 3599 delGroupAfter: function(cm) {cm.deleteH(1, "group");}, | 4508 delGroupAfter: function(cm) {cm.deleteH(1, "group");}, |
| 3600 indentAuto: function(cm) {cm.indentSelection("smart");}, | 4509 indentAuto: function(cm) {cm.indentSelection("smart");}, |
| 3601 indentMore: function(cm) {cm.indentSelection("add");}, | 4510 indentMore: function(cm) {cm.indentSelection("add");}, |
| 3602 indentLess: function(cm) {cm.indentSelection("subtract");}, | 4511 indentLess: function(cm) {cm.indentSelection("subtract");}, |
| 3603 insertTab: function(cm) { | 4512 insertTab: function(cm) {cm.replaceSelection("\t");}, |
| 3604 cm.replaceSelection("\t", "end", "+input"); | |
| 3605 }, | |
| 3606 defaultTab: function(cm) { | 4513 defaultTab: function(cm) { |
| 3607 if (cm.somethingSelected()) cm.indentSelection("add"); | 4514 if (cm.somethingSelected()) cm.indentSelection("add"); |
| 3608 else cm.replaceSelection("\t", "end", "+input"); | 4515 else cm.execCommand("insertTab"); |
| 3609 }, | 4516 }, |
| 3610 transposeChars: function(cm) { | 4517 transposeChars: function(cm) { |
| 3611 var cur = cm.getCursor(), line = cm.getLine(cur.line); | 4518 runInOp(cm, function() { |
| 3612 if (cur.ch > 0 && cur.ch < line.length - 1) | 4519 var ranges = cm.listSelections(); |
| 3613 cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1), | 4520 for (var i = 0; i < ranges.length; i++) { |
| 3614 Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1)); | 4521 var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; |
| 4522 if (cur.ch > 0 && cur.ch < line.length - 1) |
| 4523 cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1), |
| 4524 Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1)
); |
| 4525 } |
| 4526 }); |
| 3615 }, | 4527 }, |
| 3616 newlineAndIndent: function(cm) { | 4528 newlineAndIndent: function(cm) { |
| 3617 operation(cm, function() { | 4529 runInOp(cm, function() { |
| 3618 cm.replaceSelection("\n", "end", "+input"); | 4530 var len = cm.listSelections().length; |
| 3619 cm.indentLine(cm.getCursor().line, null, true); | 4531 for (var i = 0; i < len; i++) { |
| 3620 })(); | 4532 var range = cm.listSelections()[i]; |
| 4533 cm.replaceRange("\n", range.anchor, range.head, "+input"); |
| 4534 cm.indentLine(range.from().line + 1, null, true); |
| 4535 ensureCursorVisible(cm); |
| 4536 } |
| 4537 }); |
| 3621 }, | 4538 }, |
| 3622 toggleOverwrite: function(cm) {cm.toggleOverwrite();} | 4539 toggleOverwrite: function(cm) {cm.toggleOverwrite();} |
| 3623 }; | 4540 }; |
| 3624 | 4541 |
| 3625 // STANDARD KEYMAPS | 4542 // STANDARD KEYMAPS |
| 3626 | 4543 |
| 3627 var keyMap = CodeMirror.keyMap = {}; | 4544 var keyMap = CodeMirror.keyMap = {}; |
| 3628 keyMap.basic = { | 4545 keyMap.basic = { |
| 3629 "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goL
ineDown", | 4546 "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goL
ineDown", |
| 3630 "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageD
own": "goPageDown", | 4547 "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageD
own": "goPageDown", |
| 3631 "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "
delCharBefore", | 4548 "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "
delCharBefore", |
| 3632 "Tab": "defaultTab", "Shift-Tab": "indentAuto", | 4549 "Tab": "defaultTab", "Shift-Tab": "indentAuto", |
| 3633 "Enter": "newlineAndIndent", "Insert": "toggleOverwrite" | 4550 "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", |
| 4551 "Esc": "singleSelection" |
| 3634 }; | 4552 }; |
| 3635 // Note that the save and find-related commands aren't defined by | 4553 // Note that the save and find-related commands aren't defined by |
| 3636 // default. Unknown commands are simply ignored. | 4554 // default. User code or addons can define them. Unknown commands |
| 4555 // are simply ignored. |
| 3637 keyMap.pcDefault = { | 4556 keyMap.pcDefault = { |
| 3638 "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl
-Z": "redo", "Ctrl-Y": "redo", | 4557 "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl
-Z": "redo", "Ctrl-Y": "redo", |
| 3639 "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "
Ctrl-Down": "goDocEnd", | 4558 "Ctrl-Home": "goDocStart", "Ctrl-Up": "goDocStart", "Ctrl-End": "goDocEnd",
"Ctrl-Down": "goDocEnd", |
| 3640 "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLin
eStart", "Alt-Right": "goLineEnd", | 4559 "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLin
eStart", "Alt-Right": "goLineEnd", |
| 3641 "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S"
: "save", "Ctrl-F": "find", | 4560 "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S"
: "save", "Ctrl-F": "find", |
| 3642 "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace",
"Shift-Ctrl-R": "replaceAll", | 4561 "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace",
"Shift-Ctrl-R": "replaceAll", |
| 3643 "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", | 4562 "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", |
| 4563 "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSe
lection", |
| 3644 fallthrough: "basic" | 4564 fallthrough: "basic" |
| 3645 }; | 4565 }; |
| 3646 keyMap.macDefault = { | 4566 keyMap.macDefault = { |
| 3647 "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z":
"redo", "Cmd-Y": "redo", | 4567 "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z":
"redo", "Cmd-Y": "redo", |
| 3648 "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-
Left": "goGroupLeft", | 4568 "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-
Left": "goGroupLeft", |
| 3649 "Alt-Right": "goGroupRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLine
End", "Alt-Backspace": "delGroupBefore", | 4569 "Alt-Right": "goGroupRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLine
End", "Alt-Backspace": "delGroupBefore", |
| 3650 "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S
": "save", "Cmd-F": "find", | 4570 "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S
": "save", "Cmd-F": "find", |
| 3651 "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shi
ft-Cmd-Alt-F": "replaceAll", | 4571 "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shi
ft-Cmd-Alt-F": "replaceAll", |
| 3652 "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delLineLeft"
, | 4572 "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delLineLeft"
, |
| 4573 "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", |
| 3653 fallthrough: ["basic", "emacsy"] | 4574 fallthrough: ["basic", "emacsy"] |
| 3654 }; | 4575 }; |
| 3655 keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; | 4576 // Very basic readline/emacs-style bindings, which are standard on Mac. |
| 3656 keyMap.emacsy = { | 4577 keyMap.emacsy = { |
| 3657 "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl
-N": "goLineDown", | 4578 "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl
-N": "goLineDown", |
| 3658 "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctr
l-E": "goLineEnd", | 4579 "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctr
l-E": "goLineEnd", |
| 3659 "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter"
, "Ctrl-H": "delCharBefore", | 4580 "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter"
, "Ctrl-H": "delCharBefore", |
| 3660 "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLi
ne", "Ctrl-T": "transposeChars" | 4581 "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLi
ne", "Ctrl-T": "transposeChars" |
| 3661 }; | 4582 }; |
| 4583 keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; |
| 3662 | 4584 |
| 3663 // KEYMAP DISPATCH | 4585 // KEYMAP DISPATCH |
| 3664 | 4586 |
| 3665 function getKeyMap(val) { | 4587 function getKeyMap(val) { |
| 3666 if (typeof val == "string") return keyMap[val]; | 4588 if (typeof val == "string") return keyMap[val]; |
| 3667 else return val; | 4589 else return val; |
| 3668 } | 4590 } |
| 3669 | 4591 |
| 3670 function lookupKey(name, maps, handle) { | 4592 // Given an array of keymaps and a key name, call handle on any |
| 4593 // bindings found, until that returns a truthy value, at which point |
| 4594 // we consider the key handled. Implements things like binding a key |
| 4595 // to false stopping further handling and keymap fallthrough. |
| 4596 var lookupKey = CodeMirror.lookupKey = function(name, maps, handle) { |
| 3671 function lookup(map) { | 4597 function lookup(map) { |
| 3672 map = getKeyMap(map); | 4598 map = getKeyMap(map); |
| 3673 var found = map[name]; | 4599 var found = map[name]; |
| 3674 if (found === false) return "stop"; | 4600 if (found === false) return "stop"; |
| 3675 if (found != null && handle(found)) return true; | 4601 if (found != null && handle(found)) return true; |
| 3676 if (map.nofallthrough) return "stop"; | 4602 if (map.nofallthrough) return "stop"; |
| 3677 | 4603 |
| 3678 var fallthrough = map.fallthrough; | 4604 var fallthrough = map.fallthrough; |
| 3679 if (fallthrough == null) return false; | 4605 if (fallthrough == null) return false; |
| 3680 if (Object.prototype.toString.call(fallthrough) != "[object Array]") | 4606 if (Object.prototype.toString.call(fallthrough) != "[object Array]") |
| 3681 return lookup(fallthrough); | 4607 return lookup(fallthrough); |
| 3682 for (var i = 0, e = fallthrough.length; i < e; ++i) { | 4608 for (var i = 0; i < fallthrough.length; ++i) { |
| 3683 var done = lookup(fallthrough[i]); | 4609 var done = lookup(fallthrough[i]); |
| 3684 if (done) return done; | 4610 if (done) return done; |
| 3685 } | 4611 } |
| 3686 return false; | 4612 return false; |
| 3687 } | 4613 } |
| 3688 | 4614 |
| 3689 for (var i = 0; i < maps.length; ++i) { | 4615 for (var i = 0; i < maps.length; ++i) { |
| 3690 var done = lookup(maps[i]); | 4616 var done = lookup(maps[i]); |
| 3691 if (done) return done != "stop"; | 4617 if (done) return done != "stop"; |
| 3692 } | 4618 } |
| 3693 } | 4619 }; |
| 3694 function isModifierKey(event) { | 4620 |
| 4621 // Modifier key presses don't count as 'real' key presses for the |
| 4622 // purpose of keymap fallthrough. |
| 4623 var isModifierKey = CodeMirror.isModifierKey = function(event) { |
| 3695 var name = keyNames[event.keyCode]; | 4624 var name = keyNames[event.keyCode]; |
| 3696 return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; | 4625 return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; |
| 3697 } | 4626 }; |
| 3698 function keyName(event, noShift) { | 4627 |
| 3699 if (opera && event.keyCode == 34 && event["char"]) return false; | 4628 // Look up the name of a key as indicated by an event object. |
| 4629 var keyName = CodeMirror.keyName = function(event, noShift) { |
| 4630 if (presto && event.keyCode == 34 && event["char"]) return false; |
| 3700 var name = keyNames[event.keyCode]; | 4631 var name = keyNames[event.keyCode]; |
| 3701 if (name == null || event.altGraphKey) return false; | 4632 if (name == null || event.altGraphKey) return false; |
| 3702 if (event.altKey) name = "Alt-" + name; | 4633 if (event.altKey) name = "Alt-" + name; |
| 3703 if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name; | 4634 if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name; |
| 3704 if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name; | 4635 if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name; |
| 3705 if (!noShift && event.shiftKey) name = "Shift-" + name; | 4636 if (!noShift && event.shiftKey) name = "Shift-" + name; |
| 3706 return name; | 4637 return name; |
| 3707 } | 4638 }; |
| 3708 CodeMirror.lookupKey = lookupKey; | |
| 3709 CodeMirror.isModifierKey = isModifierKey; | |
| 3710 CodeMirror.keyName = keyName; | |
| 3711 | 4639 |
| 3712 // FROMTEXTAREA | 4640 // FROMTEXTAREA |
| 3713 | 4641 |
| 3714 CodeMirror.fromTextArea = function(textarea, options) { | 4642 CodeMirror.fromTextArea = function(textarea, options) { |
| 3715 if (!options) options = {}; | 4643 if (!options) options = {}; |
| 3716 options.value = textarea.value; | 4644 options.value = textarea.value; |
| 3717 if (!options.tabindex && textarea.tabindex) | 4645 if (!options.tabindex && textarea.tabindex) |
| 3718 options.tabindex = textarea.tabindex; | 4646 options.tabindex = textarea.tabindex; |
| 3719 if (!options.placeholder && textarea.placeholder) | 4647 if (!options.placeholder && textarea.placeholder) |
| 3720 options.placeholder = textarea.placeholder; | 4648 options.placeholder = textarea.placeholder; |
| 3721 // Set autofocus to true if this textarea is focused, or if it has | 4649 // Set autofocus to true if this textarea is focused, or if it has |
| 3722 // autofocus and no other element is focused. | 4650 // autofocus and no other element is focused. |
| 3723 if (options.autofocus == null) { | 4651 if (options.autofocus == null) { |
| 3724 var hasFocus = document.body; | 4652 var hasFocus = activeElt(); |
| 3725 // doc.activeElement occasionally throws on IE | |
| 3726 try { hasFocus = document.activeElement; } catch(e) {} | |
| 3727 options.autofocus = hasFocus == textarea || | 4653 options.autofocus = hasFocus == textarea || |
| 3728 textarea.getAttribute("autofocus") != null && hasFocus == document.body; | 4654 textarea.getAttribute("autofocus") != null && hasFocus == document.body; |
| 3729 } | 4655 } |
| 3730 | 4656 |
| 3731 function save() {textarea.value = cm.getValue();} | 4657 function save() {textarea.value = cm.getValue();} |
| 3732 if (textarea.form) { | 4658 if (textarea.form) { |
| 3733 on(textarea.form, "submit", save); | 4659 on(textarea.form, "submit", save); |
| 3734 // Deplorable hack to make the submit method do the right thing. | 4660 // Deplorable hack to make the submit method do the right thing. |
| 3735 if (!options.leaveSubmitMethodAlone) { | 4661 if (!options.leaveSubmitMethodAlone) { |
| 3736 var form = textarea.form, realSubmit = form.submit; | 4662 var form = textarea.form, realSubmit = form.submit; |
| (...skipping 25 matching lines...) Expand all Loading... |
| 3762 } | 4688 } |
| 3763 }; | 4689 }; |
| 3764 return cm; | 4690 return cm; |
| 3765 }; | 4691 }; |
| 3766 | 4692 |
| 3767 // STRING STREAM | 4693 // STRING STREAM |
| 3768 | 4694 |
| 3769 // Fed to the mode parsers, provides helper functions to make | 4695 // Fed to the mode parsers, provides helper functions to make |
| 3770 // parsers more succinct. | 4696 // parsers more succinct. |
| 3771 | 4697 |
| 3772 // The character stream used by a mode's parser. | 4698 var StringStream = CodeMirror.StringStream = function(string, tabSize) { |
| 3773 function StringStream(string, tabSize) { | |
| 3774 this.pos = this.start = 0; | 4699 this.pos = this.start = 0; |
| 3775 this.string = string; | 4700 this.string = string; |
| 3776 this.tabSize = tabSize || 8; | 4701 this.tabSize = tabSize || 8; |
| 3777 this.lastColumnPos = this.lastColumnValue = 0; | 4702 this.lastColumnPos = this.lastColumnValue = 0; |
| 3778 this.lineStart = 0; | 4703 this.lineStart = 0; |
| 3779 } | 4704 }; |
| 3780 | 4705 |
| 3781 StringStream.prototype = { | 4706 StringStream.prototype = { |
| 3782 eol: function() {return this.pos >= this.string.length;}, | 4707 eol: function() {return this.pos >= this.string.length;}, |
| 3783 sol: function() {return this.pos == this.lineStart;}, | 4708 sol: function() {return this.pos == this.lineStart;}, |
| 3784 peek: function() {return this.string.charAt(this.pos) || undefined;}, | 4709 peek: function() {return this.string.charAt(this.pos) || undefined;}, |
| 3785 next: function() { | 4710 next: function() { |
| 3786 if (this.pos < this.string.length) | 4711 if (this.pos < this.string.length) |
| 3787 return this.string.charAt(this.pos++); | 4712 return this.string.charAt(this.pos++); |
| 3788 }, | 4713 }, |
| 3789 eat: function(match) { | 4714 eat: function(match) { |
| (...skipping 44 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 3834 return match; | 4759 return match; |
| 3835 } | 4760 } |
| 3836 }, | 4761 }, |
| 3837 current: function(){return this.string.slice(this.start, this.pos);}, | 4762 current: function(){return this.string.slice(this.start, this.pos);}, |
| 3838 hideFirstChars: function(n, inner) { | 4763 hideFirstChars: function(n, inner) { |
| 3839 this.lineStart += n; | 4764 this.lineStart += n; |
| 3840 try { return inner(); } | 4765 try { return inner(); } |
| 3841 finally { this.lineStart -= n; } | 4766 finally { this.lineStart -= n; } |
| 3842 } | 4767 } |
| 3843 }; | 4768 }; |
| 3844 CodeMirror.StringStream = StringStream; | |
| 3845 | 4769 |
| 3846 // TEXTMARKERS | 4770 // TEXTMARKERS |
| 3847 | 4771 |
| 3848 function TextMarker(doc, type) { | 4772 // Created with markText and setBookmark methods. A TextMarker is a |
| 4773 // handle that can be used to clear or find a marked position in the |
| 4774 // document. Line objects hold arrays (markedSpans) containing |
| 4775 // {from, to, marker} object pointing to such marker objects, and |
| 4776 // indicating that such a marker is present on that line. Multiple |
| 4777 // lines may point to the same marker when it spans across lines. |
| 4778 // The spans will have null for their from/to properties when the |
| 4779 // marker continues beyond the start/end of the line. Markers have |
| 4780 // links back to the lines they currently touch. |
| 4781 |
| 4782 var TextMarker = CodeMirror.TextMarker = function(doc, type) { |
| 3849 this.lines = []; | 4783 this.lines = []; |
| 3850 this.type = type; | 4784 this.type = type; |
| 3851 this.doc = doc; | 4785 this.doc = doc; |
| 3852 } | 4786 }; |
| 3853 CodeMirror.TextMarker = TextMarker; | |
| 3854 eventMixin(TextMarker); | 4787 eventMixin(TextMarker); |
| 3855 | 4788 |
| 4789 // Clear the marker. |
| 3856 TextMarker.prototype.clear = function() { | 4790 TextMarker.prototype.clear = function() { |
| 3857 if (this.explicitlyCleared) return; | 4791 if (this.explicitlyCleared) return; |
| 3858 var cm = this.doc.cm, withOp = cm && !cm.curOp; | 4792 var cm = this.doc.cm, withOp = cm && !cm.curOp; |
| 3859 if (withOp) startOperation(cm); | 4793 if (withOp) startOperation(cm); |
| 3860 if (hasHandler(this, "clear")) { | 4794 if (hasHandler(this, "clear")) { |
| 3861 var found = this.find(); | 4795 var found = this.find(); |
| 3862 if (found) signalLater(this, "clear", found.from, found.to); | 4796 if (found) signalLater(this, "clear", found.from, found.to); |
| 3863 } | 4797 } |
| 3864 var min = null, max = null; | 4798 var min = null, max = null; |
| 3865 for (var i = 0; i < this.lines.length; ++i) { | 4799 for (var i = 0; i < this.lines.length; ++i) { |
| 3866 var line = this.lines[i]; | 4800 var line = this.lines[i]; |
| 3867 var span = getMarkedSpanFor(line.markedSpans, this); | 4801 var span = getMarkedSpanFor(line.markedSpans, this); |
| 3868 if (span.to != null) max = lineNo(line); | 4802 if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text"); |
| 4803 else if (cm) { |
| 4804 if (span.to != null) max = lineNo(line); |
| 4805 if (span.from != null) min = lineNo(line); |
| 4806 } |
| 3869 line.markedSpans = removeMarkedSpan(line.markedSpans, span); | 4807 line.markedSpans = removeMarkedSpan(line.markedSpans, span); |
| 3870 if (span.from != null) | 4808 if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) &
& cm) |
| 3871 min = lineNo(line); | |
| 3872 else if (this.collapsed && !lineIsHidden(this.doc, line) && cm) | |
| 3873 updateLineHeight(line, textHeight(cm.display)); | 4809 updateLineHeight(line, textHeight(cm.display)); |
| 3874 } | 4810 } |
| 3875 if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < th
is.lines.length; ++i) { | 4811 if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < th
is.lines.length; ++i) { |
| 3876 var visual = visualLine(cm.doc, this.lines[i]), len = lineLength(cm.doc, v
isual); | 4812 var visual = visualLine(this.lines[i]), len = lineLength(visual); |
| 3877 if (len > cm.display.maxLineLength) { | 4813 if (len > cm.display.maxLineLength) { |
| 3878 cm.display.maxLine = visual; | 4814 cm.display.maxLine = visual; |
| 3879 cm.display.maxLineLength = len; | 4815 cm.display.maxLineLength = len; |
| 3880 cm.display.maxLineChanged = true; | 4816 cm.display.maxLineChanged = true; |
| 3881 } | 4817 } |
| 3882 } | 4818 } |
| 3883 | 4819 |
| 3884 if (min != null && cm) regChange(cm, min, max + 1); | 4820 if (min != null && cm && this.collapsed) regChange(cm, min, max + 1); |
| 3885 this.lines.length = 0; | 4821 this.lines.length = 0; |
| 3886 this.explicitlyCleared = true; | 4822 this.explicitlyCleared = true; |
| 3887 if (this.atomic && this.doc.cantEdit) { | 4823 if (this.atomic && this.doc.cantEdit) { |
| 3888 this.doc.cantEdit = false; | 4824 this.doc.cantEdit = false; |
| 3889 if (cm) reCheckSelection(cm); | 4825 if (cm) reCheckSelection(cm.doc); |
| 3890 } | 4826 } |
| 4827 if (cm) signalLater(cm, "markerCleared", cm, this); |
| 3891 if (withOp) endOperation(cm); | 4828 if (withOp) endOperation(cm); |
| 3892 }; | 4829 }; |
| 3893 | 4830 |
| 3894 TextMarker.prototype.find = function(bothSides) { | 4831 // Find the position of the marker in the document. Returns a {from, |
| 4832 // to} object by default. Side can be passed to get a specific side |
| 4833 // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the |
| 4834 // Pos objects returned contain a line object, rather than a line |
| 4835 // number (used to prevent looking up the same line twice). |
| 4836 TextMarker.prototype.find = function(side, lineObj) { |
| 4837 if (side == null && this.type == "bookmark") side = 1; |
| 3895 var from, to; | 4838 var from, to; |
| 3896 for (var i = 0; i < this.lines.length; ++i) { | 4839 for (var i = 0; i < this.lines.length; ++i) { |
| 3897 var line = this.lines[i]; | 4840 var line = this.lines[i]; |
| 3898 var span = getMarkedSpanFor(line.markedSpans, this); | 4841 var span = getMarkedSpanFor(line.markedSpans, this); |
| 3899 if (span.from != null || span.to != null) { | 4842 if (span.from != null) { |
| 3900 var found = lineNo(line); | 4843 from = Pos(lineObj ? line : lineNo(line), span.from); |
| 3901 if (span.from != null) from = Pos(found, span.from); | 4844 if (side == -1) return from; |
| 3902 if (span.to != null) to = Pos(found, span.to); | 4845 } |
| 4846 if (span.to != null) { |
| 4847 to = Pos(lineObj ? line : lineNo(line), span.to); |
| 4848 if (side == 1) return to; |
| 3903 } | 4849 } |
| 3904 } | 4850 } |
| 3905 if (this.type == "bookmark" && !bothSides) return from; | |
| 3906 return from && {from: from, to: to}; | 4851 return from && {from: from, to: to}; |
| 3907 }; | 4852 }; |
| 3908 | 4853 |
| 4854 // Signals that the marker's widget changed, and surrounding layout |
| 4855 // should be recomputed. |
| 3909 TextMarker.prototype.changed = function() { | 4856 TextMarker.prototype.changed = function() { |
| 3910 var pos = this.find(), cm = this.doc.cm; | 4857 var pos = this.find(-1, true), widget = this, cm = this.doc.cm; |
| 3911 if (!pos || !cm) return; | 4858 if (!pos || !cm) return; |
| 3912 if (this.type != "bookmark") pos = pos.from; | 4859 runInOp(cm, function() { |
| 3913 var line = getLine(this.doc, pos.line); | 4860 var line = pos.line, lineN = lineNo(pos.line); |
| 3914 clearCachedMeasurement(cm, line); | 4861 var view = findViewForLine(cm, lineN); |
| 3915 if (pos.line >= cm.display.showingFrom && pos.line < cm.display.showingTo) { | 4862 if (view) { |
| 3916 for (var node = cm.display.lineDiv.firstChild; node; node = node.nextSibli
ng) if (node.lineObj == line) { | 4863 clearLineMeasurementCacheFor(view); |
| 3917 if (node.offsetHeight != line.height) updateLineHeight(line, node.offset
Height); | 4864 cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; |
| 3918 break; | |
| 3919 } | 4865 } |
| 3920 runInOp(cm, function() { | 4866 cm.curOp.updateMaxLine = true; |
| 3921 cm.curOp.selectionChanged = cm.curOp.forceUpdate = cm.curOp.updateMaxLin
e = true; | 4867 if (!lineIsHidden(widget.doc, line) && widget.height != null) { |
| 3922 }); | 4868 var oldHeight = widget.height; |
| 3923 } | 4869 widget.height = null; |
| 4870 var dHeight = widgetHeight(widget) - oldHeight; |
| 4871 if (dHeight) |
| 4872 updateLineHeight(line, line.height + dHeight); |
| 4873 } |
| 4874 }); |
| 3924 }; | 4875 }; |
| 3925 | 4876 |
| 3926 TextMarker.prototype.attachLine = function(line) { | 4877 TextMarker.prototype.attachLine = function(line) { |
| 3927 if (!this.lines.length && this.doc.cm) { | 4878 if (!this.lines.length && this.doc.cm) { |
| 3928 var op = this.doc.cm.curOp; | 4879 var op = this.doc.cm.curOp; |
| 3929 if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) | 4880 if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) |
| 3930 (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); | 4881 (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); |
| 3931 } | 4882 } |
| 3932 this.lines.push(line); | 4883 this.lines.push(line); |
| 3933 }; | 4884 }; |
| 3934 TextMarker.prototype.detachLine = function(line) { | 4885 TextMarker.prototype.detachLine = function(line) { |
| 3935 this.lines.splice(indexOf(this.lines, line), 1); | 4886 this.lines.splice(indexOf(this.lines, line), 1); |
| 3936 if (!this.lines.length && this.doc.cm) { | 4887 if (!this.lines.length && this.doc.cm) { |
| 3937 var op = this.doc.cm.curOp; | 4888 var op = this.doc.cm.curOp; |
| 3938 (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); | 4889 (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); |
| 3939 } | 4890 } |
| 3940 }; | 4891 }; |
| 3941 | 4892 |
| 4893 // Collapsed markers have unique ids, in order to be able to order |
| 4894 // them, which is needed for uniquely determining an outer marker |
| 4895 // when they overlap (they may nest, but not partially overlap). |
| 3942 var nextMarkerId = 0; | 4896 var nextMarkerId = 0; |
| 3943 | 4897 |
| 4898 // Create a marker, wire it up to the right lines, and |
| 3944 function markText(doc, from, to, options, type) { | 4899 function markText(doc, from, to, options, type) { |
| 4900 // Shared markers (across linked documents) are handled separately |
| 4901 // (markTextShared will call out to this again, once per |
| 4902 // document). |
| 3945 if (options && options.shared) return markTextShared(doc, from, to, options,
type); | 4903 if (options && options.shared) return markTextShared(doc, from, to, options,
type); |
| 4904 // Ensure we are in an operation. |
| 3946 if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, t
o, options, type); | 4905 if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, t
o, options, type); |
| 3947 | 4906 |
| 3948 var marker = new TextMarker(doc, type); | 4907 var marker = new TextMarker(doc, type), diff = cmp(from, to); |
| 3949 if (options) copyObj(options, marker); | 4908 if (options) copyObj(options, marker); |
| 3950 if (posLess(to, from) || posEq(from, to) && marker.clearWhenEmpty !== false) | 4909 // Don't connect empty markers unless clearWhenEmpty is false |
| 4910 if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) |
| 3951 return marker; | 4911 return marker; |
| 3952 if (marker.replacedWith) { | 4912 if (marker.replacedWith) { |
| 4913 // Showing up as a widget implies collapsed (widget replaces text) |
| 3953 marker.collapsed = true; | 4914 marker.collapsed = true; |
| 3954 marker.replacedWith = elt("span", [marker.replacedWith], "CodeMirror-widge
t"); | 4915 marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget"
); |
| 3955 if (!options.handleMouseEvents) marker.replacedWith.ignoreEvents = true; | 4916 if (!options.handleMouseEvents) marker.widgetNode.ignoreEvents = true; |
| 4917 if (options.insertLeft) marker.widgetNode.insertLeft = true; |
| 3956 } | 4918 } |
| 3957 if (marker.collapsed) { | 4919 if (marker.collapsed) { |
| 3958 if (conflictingCollapsedRange(doc, from.line, from, to, marker) || | 4920 if (conflictingCollapsedRange(doc, from.line, from, to, marker) || |
| 3959 from.line != to.line && conflictingCollapsedRange(doc, to.line, from,
to, marker)) | 4921 from.line != to.line && conflictingCollapsedRange(doc, to.line, from,
to, marker)) |
| 3960 throw new Error("Inserting collapsed marker partially overlapping an exi
sting one"); | 4922 throw new Error("Inserting collapsed marker partially overlapping an exi
sting one"); |
| 3961 sawCollapsedSpans = true; | 4923 sawCollapsedSpans = true; |
| 3962 } | 4924 } |
| 3963 | 4925 |
| 3964 if (marker.addToHistory) | 4926 if (marker.addToHistory) |
| 3965 addToHistory(doc, {from: from, to: to, origin: "markText"}, | 4927 addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel,
NaN); |
| 3966 {head: doc.sel.head, anchor: doc.sel.anchor}, NaN); | |
| 3967 | 4928 |
| 3968 var curLine = from.line, cm = doc.cm, updateMaxLine; | 4929 var curLine = from.line, cm = doc.cm, updateMaxLine; |
| 3969 doc.iter(curLine, to.line + 1, function(line) { | 4930 doc.iter(curLine, to.line + 1, function(line) { |
| 3970 if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(doc,
line) == cm.display.maxLine) | 4931 if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line)
== cm.display.maxLine) |
| 3971 updateMaxLine = true; | 4932 updateMaxLine = true; |
| 3972 var span = {from: null, to: null, marker: marker}; | |
| 3973 if (curLine == from.line) span.from = from.ch; | |
| 3974 if (curLine == to.line) span.to = to.ch; | |
| 3975 if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0); | 4933 if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0); |
| 3976 addMarkedSpan(line, span); | 4934 addMarkedSpan(line, new MarkedSpan(marker, |
| 4935 curLine == from.line ? from.ch : null, |
| 4936 curLine == to.line ? to.ch : null)); |
| 3977 ++curLine; | 4937 ++curLine; |
| 3978 }); | 4938 }); |
| 4939 // lineIsHidden depends on the presence of the spans, so needs a second pass |
| 3979 if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) { | 4940 if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) { |
| 3980 if (lineIsHidden(doc, line)) updateLineHeight(line, 0); | 4941 if (lineIsHidden(doc, line)) updateLineHeight(line, 0); |
| 3981 }); | 4942 }); |
| 3982 | 4943 |
| 3983 if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker
.clear(); }); | 4944 if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker
.clear(); }); |
| 3984 | 4945 |
| 3985 if (marker.readOnly) { | 4946 if (marker.readOnly) { |
| 3986 sawReadOnlySpans = true; | 4947 sawReadOnlySpans = true; |
| 3987 if (doc.history.done.length || doc.history.undone.length) | 4948 if (doc.history.done.length || doc.history.undone.length) |
| 3988 doc.clearHistory(); | 4949 doc.clearHistory(); |
| 3989 } | 4950 } |
| 3990 if (marker.collapsed) { | 4951 if (marker.collapsed) { |
| 3991 marker.id = ++nextMarkerId; | 4952 marker.id = ++nextMarkerId; |
| 3992 marker.atomic = true; | 4953 marker.atomic = true; |
| 3993 } | 4954 } |
| 3994 if (cm) { | 4955 if (cm) { |
| 4956 // Sync editor state |
| 3995 if (updateMaxLine) cm.curOp.updateMaxLine = true; | 4957 if (updateMaxLine) cm.curOp.updateMaxLine = true; |
| 3996 if (marker.className || marker.title || marker.startStyle || marker.endSty
le || marker.collapsed) | 4958 if (marker.collapsed) |
| 3997 regChange(cm, from.line, to.line + 1); | 4959 regChange(cm, from.line, to.line + 1); |
| 3998 if (marker.atomic) reCheckSelection(cm); | 4960 else if (marker.className || marker.title || marker.startStyle || marker.e
ndStyle) |
| 4961 for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text"); |
| 4962 if (marker.atomic) reCheckSelection(cm.doc); |
| 4963 signalLater(cm, "markerAdded", cm, marker); |
| 3999 } | 4964 } |
| 4000 return marker; | 4965 return marker; |
| 4001 } | 4966 } |
| 4002 | 4967 |
| 4003 // SHARED TEXTMARKERS | 4968 // SHARED TEXTMARKERS |
| 4004 | 4969 |
| 4005 function SharedTextMarker(markers, primary) { | 4970 // A shared marker spans multiple linked documents. It is |
| 4971 // implemented as a meta-marker-object controlling multiple normal |
| 4972 // markers. |
| 4973 var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary
) { |
| 4006 this.markers = markers; | 4974 this.markers = markers; |
| 4007 this.primary = primary; | 4975 this.primary = primary; |
| 4008 for (var i = 0, me = this; i < markers.length; ++i) { | 4976 for (var i = 0, me = this; i < markers.length; ++i) { |
| 4009 markers[i].parent = this; | 4977 markers[i].parent = this; |
| 4010 on(markers[i], "clear", function(){me.clear();}); | 4978 on(markers[i], "clear", function(){me.clear();}); |
| 4011 } | 4979 } |
| 4012 } | 4980 }; |
| 4013 CodeMirror.SharedTextMarker = SharedTextMarker; | |
| 4014 eventMixin(SharedTextMarker); | 4981 eventMixin(SharedTextMarker); |
| 4015 | 4982 |
| 4016 SharedTextMarker.prototype.clear = function() { | 4983 SharedTextMarker.prototype.clear = function() { |
| 4017 if (this.explicitlyCleared) return; | 4984 if (this.explicitlyCleared) return; |
| 4018 this.explicitlyCleared = true; | 4985 this.explicitlyCleared = true; |
| 4019 for (var i = 0; i < this.markers.length; ++i) | 4986 for (var i = 0; i < this.markers.length; ++i) |
| 4020 this.markers[i].clear(); | 4987 this.markers[i].clear(); |
| 4021 signalLater(this, "clear"); | 4988 signalLater(this, "clear"); |
| 4022 }; | 4989 }; |
| 4023 SharedTextMarker.prototype.find = function() { | 4990 SharedTextMarker.prototype.find = function(side, lineObj) { |
| 4024 return this.primary.find(); | 4991 return this.primary.find(side, lineObj); |
| 4025 }; | 4992 }; |
| 4026 | 4993 |
| 4027 function markTextShared(doc, from, to, options, type) { | 4994 function markTextShared(doc, from, to, options, type) { |
| 4028 options = copyObj(options); | 4995 options = copyObj(options); |
| 4029 options.shared = false; | 4996 options.shared = false; |
| 4030 var markers = [markText(doc, from, to, options, type)], primary = markers[0]
; | 4997 var markers = [markText(doc, from, to, options, type)], primary = markers[0]
; |
| 4031 var widget = options.replacedWith; | 4998 var widget = options.widgetNode; |
| 4032 linkedDocs(doc, function(doc) { | 4999 linkedDocs(doc, function(doc) { |
| 4033 if (widget) options.replacedWith = widget.cloneNode(true); | 5000 if (widget) options.widgetNode = widget.cloneNode(true); |
| 4034 markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options,
type)); | 5001 markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options,
type)); |
| 4035 for (var i = 0; i < doc.linked.length; ++i) | 5002 for (var i = 0; i < doc.linked.length; ++i) |
| 4036 if (doc.linked[i].isParent) return; | 5003 if (doc.linked[i].isParent) return; |
| 4037 primary = lst(markers); | 5004 primary = lst(markers); |
| 4038 }); | 5005 }); |
| 4039 return new SharedTextMarker(markers, primary); | 5006 return new SharedTextMarker(markers, primary); |
| 4040 } | 5007 } |
| 4041 | 5008 |
| 4042 // TEXTMARKER SPANS | 5009 // TEXTMARKER SPANS |
| 4043 | 5010 |
| 5011 function MarkedSpan(marker, from, to) { |
| 5012 this.marker = marker; |
| 5013 this.from = from; this.to = to; |
| 5014 } |
| 5015 |
| 5016 // Search an array of spans for a span matching the given marker. |
| 4044 function getMarkedSpanFor(spans, marker) { | 5017 function getMarkedSpanFor(spans, marker) { |
| 4045 if (spans) for (var i = 0; i < spans.length; ++i) { | 5018 if (spans) for (var i = 0; i < spans.length; ++i) { |
| 4046 var span = spans[i]; | 5019 var span = spans[i]; |
| 4047 if (span.marker == marker) return span; | 5020 if (span.marker == marker) return span; |
| 4048 } | 5021 } |
| 4049 } | 5022 } |
| 5023 // Remove a span from an array, returning undefined if no spans are |
| 5024 // left (we don't store arrays for lines without spans). |
| 4050 function removeMarkedSpan(spans, span) { | 5025 function removeMarkedSpan(spans, span) { |
| 4051 for (var r, i = 0; i < spans.length; ++i) | 5026 for (var r, i = 0; i < spans.length; ++i) |
| 4052 if (spans[i] != span) (r || (r = [])).push(spans[i]); | 5027 if (spans[i] != span) (r || (r = [])).push(spans[i]); |
| 4053 return r; | 5028 return r; |
| 4054 } | 5029 } |
| 5030 // Add a span to a line. |
| 4055 function addMarkedSpan(line, span) { | 5031 function addMarkedSpan(line, span) { |
| 4056 line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [spa
n]; | 5032 line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [spa
n]; |
| 4057 span.marker.attachLine(line); | 5033 span.marker.attachLine(line); |
| 4058 } | 5034 } |
| 4059 | 5035 |
| 5036 // Used for the algorithm that adjusts markers for a change in the |
| 5037 // document. These functions cut an array of spans at a given |
| 5038 // character position, returning an array of remaining chunks (or |
| 5039 // undefined if nothing remains). |
| 4060 function markedSpansBefore(old, startCh, isInsert) { | 5040 function markedSpansBefore(old, startCh, isInsert) { |
| 4061 if (old) for (var i = 0, nw; i < old.length; ++i) { | 5041 if (old) for (var i = 0, nw; i < old.length; ++i) { |
| 4062 var span = old[i], marker = span.marker; | 5042 var span = old[i], marker = span.marker; |
| 4063 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from
<= startCh : span.from < startCh); | 5043 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from
<= startCh : span.from < startCh); |
| 4064 if (startsBefore || span.from == startCh && marker.type == "bookmark" && (
!isInsert || !span.marker.insertLeft)) { | 5044 if (startsBefore || span.from == startCh && marker.type == "bookmark" && (
!isInsert || !span.marker.insertLeft)) { |
| 4065 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= s
tartCh : span.to > startCh); | 5045 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= s
tartCh : span.to > startCh); |
| 4066 (nw || (nw = [])).push({from: span.from, | 5046 (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? nul
l : span.to)); |
| 4067 to: endsAfter ? null : span.to, | |
| 4068 marker: marker}); | |
| 4069 } | 5047 } |
| 4070 } | 5048 } |
| 4071 return nw; | 5049 return nw; |
| 4072 } | 5050 } |
| 4073 | |
| 4074 function markedSpansAfter(old, endCh, isInsert) { | 5051 function markedSpansAfter(old, endCh, isInsert) { |
| 4075 if (old) for (var i = 0, nw; i < old.length; ++i) { | 5052 if (old) for (var i = 0, nw; i < old.length; ++i) { |
| 4076 var span = old[i], marker = span.marker; | 5053 var span = old[i], marker = span.marker; |
| 4077 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= end
Ch : span.to > endCh); | 5054 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= end
Ch : span.to > endCh); |
| 4078 if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isIn
sert || span.marker.insertLeft)) { | 5055 if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isIn
sert || span.marker.insertLeft)) { |
| 4079 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.fro
m <= endCh : span.from < endCh); | 5056 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.fro
m <= endCh : span.from < endCh); |
| 4080 (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh, | 5057 (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span
.from - endCh, |
| 4081 to: span.to == null ? null : span.to - endCh, | 5058 span.to == null ? null : span.to -
endCh)); |
| 4082 marker: marker}); | |
| 4083 } | 5059 } |
| 4084 } | 5060 } |
| 4085 return nw; | 5061 return nw; |
| 4086 } | 5062 } |
| 4087 | 5063 |
| 5064 // Given a change object, compute the new set of marker spans that |
| 5065 // cover the line in which the change took place. Removes spans |
| 5066 // entirely within the change, reconnects spans belonging to the |
| 5067 // same marker that appear on both sides of the change, and cuts off |
| 5068 // spans partially within the change. Returns an array of span |
| 5069 // arrays with one element for each line in (after) the change. |
| 4088 function stretchSpansOverChange(doc, change) { | 5070 function stretchSpansOverChange(doc, change) { |
| 4089 var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.lin
e).markedSpans; | 5071 var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.lin
e).markedSpans; |
| 4090 var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).ma
rkedSpans; | 5072 var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).ma
rkedSpans; |
| 4091 if (!oldFirst && !oldLast) return null; | 5073 if (!oldFirst && !oldLast) return null; |
| 4092 | 5074 |
| 4093 var startCh = change.from.ch, endCh = change.to.ch, isInsert = posEq(change.
from, change.to); | 5075 var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.fr
om, change.to) == 0; |
| 4094 // Get the spans that 'stick out' on both sides | 5076 // Get the spans that 'stick out' on both sides |
| 4095 var first = markedSpansBefore(oldFirst, startCh, isInsert); | 5077 var first = markedSpansBefore(oldFirst, startCh, isInsert); |
| 4096 var last = markedSpansAfter(oldLast, endCh, isInsert); | 5078 var last = markedSpansAfter(oldLast, endCh, isInsert); |
| 4097 | 5079 |
| 4098 // Next, merge those two ends | 5080 // Next, merge those two ends |
| 4099 var sameLine = change.text.length == 1, offset = lst(change.text).length + (
sameLine ? startCh : 0); | 5081 var sameLine = change.text.length == 1, offset = lst(change.text).length + (
sameLine ? startCh : 0); |
| 4100 if (first) { | 5082 if (first) { |
| 4101 // Fix up .to properties of first | 5083 // Fix up .to properties of first |
| 4102 for (var i = 0; i < first.length; ++i) { | 5084 for (var i = 0; i < first.length; ++i) { |
| 4103 var span = first[i]; | 5085 var span = first[i]; |
| (...skipping 25 matching lines...) Expand all Loading... |
| 4129 if (first) first = clearEmptySpans(first); | 5111 if (first) first = clearEmptySpans(first); |
| 4130 if (last && last != first) last = clearEmptySpans(last); | 5112 if (last && last != first) last = clearEmptySpans(last); |
| 4131 | 5113 |
| 4132 var newMarkers = [first]; | 5114 var newMarkers = [first]; |
| 4133 if (!sameLine) { | 5115 if (!sameLine) { |
| 4134 // Fill gap with whole-line-spans | 5116 // Fill gap with whole-line-spans |
| 4135 var gap = change.text.length - 2, gapMarkers; | 5117 var gap = change.text.length - 2, gapMarkers; |
| 4136 if (gap > 0 && first) | 5118 if (gap > 0 && first) |
| 4137 for (var i = 0; i < first.length; ++i) | 5119 for (var i = 0; i < first.length; ++i) |
| 4138 if (first[i].to == null) | 5120 if (first[i].to == null) |
| 4139 (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker
: first[i].marker}); | 5121 (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marke
r, null, null)); |
| 4140 for (var i = 0; i < gap; ++i) | 5122 for (var i = 0; i < gap; ++i) |
| 4141 newMarkers.push(gapMarkers); | 5123 newMarkers.push(gapMarkers); |
| 4142 newMarkers.push(last); | 5124 newMarkers.push(last); |
| 4143 } | 5125 } |
| 4144 return newMarkers; | 5126 return newMarkers; |
| 4145 } | 5127 } |
| 4146 | 5128 |
| 5129 // Remove spans that are empty and don't have a clearWhenEmpty |
| 5130 // option of false. |
| 4147 function clearEmptySpans(spans) { | 5131 function clearEmptySpans(spans) { |
| 4148 for (var i = 0; i < spans.length; ++i) { | 5132 for (var i = 0; i < spans.length; ++i) { |
| 4149 var span = spans[i]; | 5133 var span = spans[i]; |
| 4150 if (span.from != null && span.from == span.to && span.marker.clearWhenEmpt
y !== false) | 5134 if (span.from != null && span.from == span.to && span.marker.clearWhenEmpt
y !== false) |
| 4151 spans.splice(i--, 1); | 5135 spans.splice(i--, 1); |
| 4152 } | 5136 } |
| 4153 if (!spans.length) return null; | 5137 if (!spans.length) return null; |
| 4154 return spans; | 5138 return spans; |
| 4155 } | 5139 } |
| 4156 | 5140 |
| 5141 // Used for un/re-doing changes from the history. Combines the |
| 5142 // result of computing the existing spans with the set of spans that |
| 5143 // existed in the history (so that deleting around a span and then |
| 5144 // undoing brings back the span). |
| 4157 function mergeOldSpans(doc, change) { | 5145 function mergeOldSpans(doc, change) { |
| 4158 var old = getOldSpans(doc, change); | 5146 var old = getOldSpans(doc, change); |
| 4159 var stretched = stretchSpansOverChange(doc, change); | 5147 var stretched = stretchSpansOverChange(doc, change); |
| 4160 if (!old) return stretched; | 5148 if (!old) return stretched; |
| 4161 if (!stretched) return old; | 5149 if (!stretched) return old; |
| 4162 | 5150 |
| 4163 for (var i = 0; i < old.length; ++i) { | 5151 for (var i = 0; i < old.length; ++i) { |
| 4164 var oldCur = old[i], stretchCur = stretched[i]; | 5152 var oldCur = old[i], stretchCur = stretched[i]; |
| 4165 if (oldCur && stretchCur) { | 5153 if (oldCur && stretchCur) { |
| 4166 spans: for (var j = 0; j < stretchCur.length; ++j) { | 5154 spans: for (var j = 0; j < stretchCur.length; ++j) { |
| 4167 var span = stretchCur[j]; | 5155 var span = stretchCur[j]; |
| 4168 for (var k = 0; k < oldCur.length; ++k) | 5156 for (var k = 0; k < oldCur.length; ++k) |
| 4169 if (oldCur[k].marker == span.marker) continue spans; | 5157 if (oldCur[k].marker == span.marker) continue spans; |
| 4170 oldCur.push(span); | 5158 oldCur.push(span); |
| 4171 } | 5159 } |
| 4172 } else if (stretchCur) { | 5160 } else if (stretchCur) { |
| 4173 old[i] = stretchCur; | 5161 old[i] = stretchCur; |
| 4174 } | 5162 } |
| 4175 } | 5163 } |
| 4176 return old; | 5164 return old; |
| 4177 } | 5165 } |
| 4178 | 5166 |
| 5167 // Used to 'clip' out readOnly ranges when making a change. |
| 4179 function removeReadOnlyRanges(doc, from, to) { | 5168 function removeReadOnlyRanges(doc, from, to) { |
| 4180 var markers = null; | 5169 var markers = null; |
| 4181 doc.iter(from.line, to.line + 1, function(line) { | 5170 doc.iter(from.line, to.line + 1, function(line) { |
| 4182 if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) { | 5171 if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) { |
| 4183 var mark = line.markedSpans[i].marker; | 5172 var mark = line.markedSpans[i].marker; |
| 4184 if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) | 5173 if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) |
| 4185 (markers || (markers = [])).push(mark); | 5174 (markers || (markers = [])).push(mark); |
| 4186 } | 5175 } |
| 4187 }); | 5176 }); |
| 4188 if (!markers) return null; | 5177 if (!markers) return null; |
| 4189 var parts = [{from: from, to: to}]; | 5178 var parts = [{from: from, to: to}]; |
| 4190 for (var i = 0; i < markers.length; ++i) { | 5179 for (var i = 0; i < markers.length; ++i) { |
| 4191 var mk = markers[i], m = mk.find(); | 5180 var mk = markers[i], m = mk.find(0); |
| 4192 for (var j = 0; j < parts.length; ++j) { | 5181 for (var j = 0; j < parts.length; ++j) { |
| 4193 var p = parts[j]; | 5182 var p = parts[j]; |
| 4194 if (posLess(p.to, m.from) || posLess(m.to, p.from)) continue; | 5183 if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue; |
| 4195 var newParts = [j, 1]; | 5184 var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to
); |
| 4196 if (posLess(p.from, m.from) || !mk.inclusiveLeft && posEq(p.from, m.from
)) | 5185 if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) |
| 4197 newParts.push({from: p.from, to: m.from}); | 5186 newParts.push({from: p.from, to: m.from}); |
| 4198 if (posLess(m.to, p.to) || !mk.inclusiveRight && posEq(p.to, m.to)) | 5187 if (dto > 0 || !mk.inclusiveRight && !dto) |
| 4199 newParts.push({from: m.to, to: p.to}); | 5188 newParts.push({from: m.to, to: p.to}); |
| 4200 parts.splice.apply(parts, newParts); | 5189 parts.splice.apply(parts, newParts); |
| 4201 j += newParts.length - 1; | 5190 j += newParts.length - 1; |
| 4202 } | 5191 } |
| 4203 } | 5192 } |
| 4204 return parts; | 5193 return parts; |
| 4205 } | 5194 } |
| 4206 | 5195 |
| 5196 // Connect or disconnect spans from a line. |
| 5197 function detachMarkedSpans(line) { |
| 5198 var spans = line.markedSpans; |
| 5199 if (!spans) return; |
| 5200 for (var i = 0; i < spans.length; ++i) |
| 5201 spans[i].marker.detachLine(line); |
| 5202 line.markedSpans = null; |
| 5203 } |
| 5204 function attachMarkedSpans(line, spans) { |
| 5205 if (!spans) return; |
| 5206 for (var i = 0; i < spans.length; ++i) |
| 5207 spans[i].marker.attachLine(line); |
| 5208 line.markedSpans = spans; |
| 5209 } |
| 5210 |
| 5211 // Helpers used when computing which overlapping collapsed span |
| 5212 // counts as the larger one. |
| 4207 function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; } | 5213 function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; } |
| 4208 function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; } | 5214 function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; } |
| 4209 | 5215 |
| 5216 // Returns a number indicating which of two overlapping collapsed |
| 5217 // spans is larger (and thus includes the other). Falls back to |
| 5218 // comparing ids when the spans cover exactly the same range. |
| 4210 function compareCollapsedMarkers(a, b) { | 5219 function compareCollapsedMarkers(a, b) { |
| 4211 var lenDiff = a.lines.length - b.lines.length; | 5220 var lenDiff = a.lines.length - b.lines.length; |
| 4212 if (lenDiff != 0) return lenDiff; | 5221 if (lenDiff != 0) return lenDiff; |
| 4213 var aPos = a.find(), bPos = b.find(); | 5222 var aPos = a.find(), bPos = b.find(); |
| 4214 var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); | 5223 var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); |
| 4215 if (fromCmp) return -fromCmp; | 5224 if (fromCmp) return -fromCmp; |
| 4216 var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); | 5225 var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); |
| 4217 if (toCmp) return toCmp; | 5226 if (toCmp) return toCmp; |
| 4218 return b.id - a.id; | 5227 return b.id - a.id; |
| 4219 } | 5228 } |
| 4220 | 5229 |
| 5230 // Find out whether a line ends or starts in a collapsed span. If |
| 5231 // so, return the marker for that span. |
| 4221 function collapsedSpanAtSide(line, start) { | 5232 function collapsedSpanAtSide(line, start) { |
| 4222 var sps = sawCollapsedSpans && line.markedSpans, found; | 5233 var sps = sawCollapsedSpans && line.markedSpans, found; |
| 4223 if (sps) for (var sp, i = 0; i < sps.length; ++i) { | 5234 if (sps) for (var sp, i = 0; i < sps.length; ++i) { |
| 4224 sp = sps[i]; | 5235 sp = sps[i]; |
| 4225 if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && | 5236 if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && |
| 4226 (!found || compareCollapsedMarkers(found, sp.marker) < 0)) | 5237 (!found || compareCollapsedMarkers(found, sp.marker) < 0)) |
| 4227 found = sp.marker; | 5238 found = sp.marker; |
| 4228 } | 5239 } |
| 4229 return found; | 5240 return found; |
| 4230 } | 5241 } |
| 4231 function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true);
} | 5242 function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true);
} |
| 4232 function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); } | 5243 function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); } |
| 4233 | 5244 |
| 5245 // Test whether there exists a collapsed span that partially |
| 5246 // overlaps (covers the start or end, but not both) of a new span. |
| 5247 // Such overlap is not allowed. |
| 4234 function conflictingCollapsedRange(doc, lineNo, from, to, marker) { | 5248 function conflictingCollapsedRange(doc, lineNo, from, to, marker) { |
| 4235 var line = getLine(doc, lineNo); | 5249 var line = getLine(doc, lineNo); |
| 4236 var sps = sawCollapsedSpans && line.markedSpans; | 5250 var sps = sawCollapsedSpans && line.markedSpans; |
| 4237 if (sps) for (var i = 0; i < sps.length; ++i) { | 5251 if (sps) for (var i = 0; i < sps.length; ++i) { |
| 4238 var sp = sps[i]; | 5252 var sp = sps[i]; |
| 4239 if (!sp.marker.collapsed) continue; | 5253 if (!sp.marker.collapsed) continue; |
| 4240 var found = sp.marker.find(true); | 5254 var found = sp.marker.find(0); |
| 4241 var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(ma
rker); | 5255 var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(ma
rker); |
| 4242 var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker
); | 5256 var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker
); |
| 4243 if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue; | 5257 if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue; |
| 4244 if (fromCmp <= 0 && (cmp(found.to, from) || extraRight(sp.marker) - extraL
eft(marker)) > 0 || | 5258 if (fromCmp <= 0 && (cmp(found.to, from) || extraRight(sp.marker) - extraL
eft(marker)) > 0 || |
| 4245 fromCmp >= 0 && (cmp(found.from, to) || extraLeft(sp.marker) - extraRi
ght(marker)) < 0) | 5259 fromCmp >= 0 && (cmp(found.from, to) || extraLeft(sp.marker) - extraRi
ght(marker)) < 0) |
| 4246 return true; | 5260 return true; |
| 4247 } | 5261 } |
| 4248 } | 5262 } |
| 4249 | 5263 |
| 4250 function visualLine(doc, line) { | 5264 // A visual line is a line as drawn on the screen. Folding, for |
| 5265 // example, can cause multiple logical lines to appear on the same |
| 5266 // visual line. This finds the start of the visual line that the |
| 5267 // given line is part of (usually that is the line itself). |
| 5268 function visualLine(line) { |
| 4251 var merged; | 5269 var merged; |
| 4252 while (merged = collapsedSpanAtStart(line)) | 5270 while (merged = collapsedSpanAtStart(line)) |
| 4253 line = getLine(doc, merged.find().from.line); | 5271 line = merged.find(-1, true).line; |
| 4254 return line; | 5272 return line; |
| 4255 } | 5273 } |
| 4256 | 5274 |
| 5275 // Returns an array of logical lines that continue the visual line |
| 5276 // started by the argument, or undefined if there are no such lines. |
| 5277 function visualLineContinued(line) { |
| 5278 var merged, lines; |
| 5279 while (merged = collapsedSpanAtEnd(line)) { |
| 5280 line = merged.find(1, true).line; |
| 5281 (lines || (lines = [])).push(line); |
| 5282 } |
| 5283 return lines; |
| 5284 } |
| 5285 |
| 5286 // Get the line number of the start of the visual line that the |
| 5287 // given line number is part of. |
| 5288 function visualLineNo(doc, lineN) { |
| 5289 var line = getLine(doc, lineN), vis = visualLine(line); |
| 5290 if (line == vis) return lineN; |
| 5291 return lineNo(vis); |
| 5292 } |
| 5293 // Get the line number of the start of the next visual line after |
| 5294 // the given line. |
| 5295 function visualLineEndNo(doc, lineN) { |
| 5296 if (lineN > doc.lastLine()) return lineN; |
| 5297 var line = getLine(doc, lineN), merged; |
| 5298 if (!lineIsHidden(doc, line)) return lineN; |
| 5299 while (merged = collapsedSpanAtEnd(line)) |
| 5300 line = merged.find(1, true).line; |
| 5301 return lineNo(line) + 1; |
| 5302 } |
| 5303 |
| 5304 // Compute whether a line is hidden. Lines count as hidden when they |
| 5305 // are part of a visual line that starts with another line, or when |
| 5306 // they are entirely covered by collapsed, non-widget span. |
| 4257 function lineIsHidden(doc, line) { | 5307 function lineIsHidden(doc, line) { |
| 4258 var sps = sawCollapsedSpans && line.markedSpans; | 5308 var sps = sawCollapsedSpans && line.markedSpans; |
| 4259 if (sps) for (var sp, i = 0; i < sps.length; ++i) { | 5309 if (sps) for (var sp, i = 0; i < sps.length; ++i) { |
| 4260 sp = sps[i]; | 5310 sp = sps[i]; |
| 4261 if (!sp.marker.collapsed) continue; | 5311 if (!sp.marker.collapsed) continue; |
| 4262 if (sp.from == null) return true; | 5312 if (sp.from == null) return true; |
| 4263 if (sp.marker.replacedWith) continue; | 5313 if (sp.marker.widgetNode) continue; |
| 4264 if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line
, sp)) | 5314 if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line
, sp)) |
| 4265 return true; | 5315 return true; |
| 4266 } | 5316 } |
| 4267 } | 5317 } |
| 4268 function lineIsHiddenInner(doc, line, span) { | 5318 function lineIsHiddenInner(doc, line, span) { |
| 4269 if (span.to == null) { | 5319 if (span.to == null) { |
| 4270 var end = span.marker.find().to, endLine = getLine(doc, end.line); | 5320 var end = span.marker.find(1, true); |
| 4271 return lineIsHiddenInner(doc, endLine, getMarkedSpanFor(endLine.markedSpan
s, span.marker)); | 5321 return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSp
ans, span.marker)); |
| 4272 } | 5322 } |
| 4273 if (span.marker.inclusiveRight && span.to == line.text.length) | 5323 if (span.marker.inclusiveRight && span.to == line.text.length) |
| 4274 return true; | 5324 return true; |
| 4275 for (var sp, i = 0; i < line.markedSpans.length; ++i) { | 5325 for (var sp, i = 0; i < line.markedSpans.length; ++i) { |
| 4276 sp = line.markedSpans[i]; | 5326 sp = line.markedSpans[i]; |
| 4277 if (sp.marker.collapsed && !sp.marker.replacedWith && sp.from == span.to &
& | 5327 if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && |
| 4278 (sp.to == null || sp.to != span.from) && | 5328 (sp.to == null || sp.to != span.from) && |
| 4279 (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && | 5329 (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && |
| 4280 lineIsHiddenInner(doc, line, sp)) return true; | 5330 lineIsHiddenInner(doc, line, sp)) return true; |
| 4281 } | 5331 } |
| 4282 } | 5332 } |
| 4283 | 5333 |
| 4284 function detachMarkedSpans(line) { | 5334 // LINE WIDGETS |
| 4285 var spans = line.markedSpans; | |
| 4286 if (!spans) return; | |
| 4287 for (var i = 0; i < spans.length; ++i) | |
| 4288 spans[i].marker.detachLine(line); | |
| 4289 line.markedSpans = null; | |
| 4290 } | |
| 4291 | 5335 |
| 4292 function attachMarkedSpans(line, spans) { | 5336 // Line widgets are block elements displayed above or below a line. |
| 4293 if (!spans) return; | |
| 4294 for (var i = 0; i < spans.length; ++i) | |
| 4295 spans[i].marker.attachLine(line); | |
| 4296 line.markedSpans = spans; | |
| 4297 } | |
| 4298 | |
| 4299 // LINE WIDGETS | |
| 4300 | 5337 |
| 4301 var LineWidget = CodeMirror.LineWidget = function(cm, node, options) { | 5338 var LineWidget = CodeMirror.LineWidget = function(cm, node, options) { |
| 4302 if (options) for (var opt in options) if (options.hasOwnProperty(opt)) | 5339 if (options) for (var opt in options) if (options.hasOwnProperty(opt)) |
| 4303 this[opt] = options[opt]; | 5340 this[opt] = options[opt]; |
| 4304 this.cm = cm; | 5341 this.cm = cm; |
| 4305 this.node = node; | 5342 this.node = node; |
| 4306 }; | 5343 }; |
| 4307 eventMixin(LineWidget); | 5344 eventMixin(LineWidget); |
| 4308 function widgetOperation(f) { | 5345 |
| 4309 return function() { | 5346 function adjustScrollWhenAboveVisible(cm, line, diff) { |
| 4310 var withOp = !this.cm.curOp; | 5347 if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollT
op)) |
| 4311 if (withOp) startOperation(this.cm); | 5348 addToScrollPos(cm, null, diff); |
| 4312 try {var result = f.apply(this, arguments);} | |
| 4313 finally {if (withOp) endOperation(this.cm);} | |
| 4314 return result; | |
| 4315 }; | |
| 4316 } | 5349 } |
| 4317 LineWidget.prototype.clear = widgetOperation(function() { | 5350 |
| 4318 var ws = this.line.widgets, no = lineNo(this.line); | 5351 LineWidget.prototype.clear = function() { |
| 5352 var cm = this.cm, ws = this.line.widgets, line = this.line, no = lineNo(line
); |
| 4319 if (no == null || !ws) return; | 5353 if (no == null || !ws) return; |
| 4320 for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1); | 5354 for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1); |
| 4321 if (!ws.length) this.line.widgets = null; | 5355 if (!ws.length) line.widgets = null; |
| 4322 var aboveVisible = heightAtLine(this.cm, this.line) < this.cm.doc.scrollTop; | 5356 var height = widgetHeight(this); |
| 4323 updateLineHeight(this.line, Math.max(0, this.line.height - widgetHeight(this
))); | 5357 runInOp(cm, function() { |
| 4324 if (aboveVisible) addToScrollPos(this.cm, 0, -this.height); | 5358 adjustScrollWhenAboveVisible(cm, line, -height); |
| 4325 regChange(this.cm, no, no + 1); | 5359 regLineChange(cm, no, "widget"); |
| 4326 }); | 5360 updateLineHeight(line, Math.max(0, line.height - height)); |
| 4327 LineWidget.prototype.changed = widgetOperation(function() { | 5361 }); |
| 4328 var oldH = this.height; | 5362 }; |
| 5363 LineWidget.prototype.changed = function() { |
| 5364 var oldH = this.height, cm = this.cm, line = this.line; |
| 4329 this.height = null; | 5365 this.height = null; |
| 4330 var diff = widgetHeight(this) - oldH; | 5366 var diff = widgetHeight(this) - oldH; |
| 4331 if (!diff) return; | 5367 if (!diff) return; |
| 4332 updateLineHeight(this.line, this.line.height + diff); | 5368 runInOp(cm, function() { |
| 4333 var no = lineNo(this.line); | 5369 cm.curOp.forceUpdate = true; |
| 4334 regChange(this.cm, no, no + 1); | 5370 adjustScrollWhenAboveVisible(cm, line, diff); |
| 4335 }); | 5371 updateLineHeight(line, line.height + diff); |
| 5372 }); |
| 5373 }; |
| 4336 | 5374 |
| 4337 function widgetHeight(widget) { | 5375 function widgetHeight(widget) { |
| 4338 if (widget.height != null) return widget.height; | 5376 if (widget.height != null) return widget.height; |
| 4339 if (!widget.node.parentNode || widget.node.parentNode.nodeType != 1) | 5377 if (!contains(document.body, widget.node)) |
| 4340 removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node],
null, "position: relative")); | 5378 removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node],
null, "position: relative")); |
| 4341 return widget.height = widget.node.offsetHeight; | 5379 return widget.height = widget.node.offsetHeight; |
| 4342 } | 5380 } |
| 4343 | 5381 |
| 4344 function addLineWidget(cm, handle, node, options) { | 5382 function addLineWidget(cm, handle, node, options) { |
| 4345 var widget = new LineWidget(cm, node, options); | 5383 var widget = new LineWidget(cm, node, options); |
| 4346 if (widget.noHScroll) cm.display.alignWidgets = true; | 5384 if (widget.noHScroll) cm.display.alignWidgets = true; |
| 4347 changeLine(cm, handle, function(line) { | 5385 changeLine(cm, handle, "widget", function(line) { |
| 4348 var widgets = line.widgets || (line.widgets = []); | 5386 var widgets = line.widgets || (line.widgets = []); |
| 4349 if (widget.insertAt == null) widgets.push(widget); | 5387 if (widget.insertAt == null) widgets.push(widget); |
| 4350 else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insert
At)), 0, widget); | 5388 else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insert
At)), 0, widget); |
| 4351 widget.line = line; | 5389 widget.line = line; |
| 4352 if (!lineIsHidden(cm.doc, line) || widget.showIfHidden) { | 5390 if (!lineIsHidden(cm.doc, line)) { |
| 4353 var aboveVisible = heightAtLine(cm, line) < cm.doc.scrollTop; | 5391 var aboveVisible = heightAtLine(line) < cm.doc.scrollTop; |
| 4354 updateLineHeight(line, line.height + widgetHeight(widget)); | 5392 updateLineHeight(line, line.height + widgetHeight(widget)); |
| 4355 if (aboveVisible) addToScrollPos(cm, 0, widget.height); | 5393 if (aboveVisible) addToScrollPos(cm, null, widget.height); |
| 5394 cm.curOp.forceUpdate = true; |
| 4356 } | 5395 } |
| 4357 return true; | 5396 return true; |
| 4358 }); | 5397 }); |
| 4359 return widget; | 5398 return widget; |
| 4360 } | 5399 } |
| 4361 | 5400 |
| 4362 // LINE DATA STRUCTURE | 5401 // LINE DATA STRUCTURE |
| 4363 | 5402 |
| 4364 // Line objects. These hold state related to a line, including | 5403 // Line objects. These hold state related to a line, including |
| 4365 // highlighting info (the styles array). | 5404 // highlighting info (the styles array). |
| 4366 var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) { | 5405 var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) { |
| 4367 this.text = text; | 5406 this.text = text; |
| 4368 attachMarkedSpans(this, markedSpans); | 5407 attachMarkedSpans(this, markedSpans); |
| 4369 this.height = estimateHeight ? estimateHeight(this) : 1; | 5408 this.height = estimateHeight ? estimateHeight(this) : 1; |
| 4370 }; | 5409 }; |
| 4371 eventMixin(Line); | 5410 eventMixin(Line); |
| 4372 Line.prototype.lineNo = function() { return lineNo(this); }; | 5411 Line.prototype.lineNo = function() { return lineNo(this); }; |
| 4373 | 5412 |
| 5413 // Change the content (text, markers) of a line. Automatically |
| 5414 // invalidates cached information and tries to re-estimate the |
| 5415 // line's height. |
| 4374 function updateLine(line, text, markedSpans, estimateHeight) { | 5416 function updateLine(line, text, markedSpans, estimateHeight) { |
| 4375 line.text = text; | 5417 line.text = text; |
| 4376 if (line.stateAfter) line.stateAfter = null; | 5418 if (line.stateAfter) line.stateAfter = null; |
| 4377 if (line.styles) line.styles = null; | 5419 if (line.styles) line.styles = null; |
| 4378 if (line.order != null) line.order = null; | 5420 if (line.order != null) line.order = null; |
| 4379 detachMarkedSpans(line); | 5421 detachMarkedSpans(line); |
| 4380 attachMarkedSpans(line, markedSpans); | 5422 attachMarkedSpans(line, markedSpans); |
| 4381 var estHeight = estimateHeight ? estimateHeight(line) : 1; | 5423 var estHeight = estimateHeight ? estimateHeight(line) : 1; |
| 4382 if (estHeight != line.height) updateLineHeight(line, estHeight); | 5424 if (estHeight != line.height) updateLineHeight(line, estHeight); |
| 4383 } | 5425 } |
| 4384 | 5426 |
| 5427 // Detach a line from the document tree and its markers. |
| 4385 function cleanUpLine(line) { | 5428 function cleanUpLine(line) { |
| 4386 line.parent = null; | 5429 line.parent = null; |
| 4387 detachMarkedSpans(line); | 5430 detachMarkedSpans(line); |
| 4388 } | 5431 } |
| 4389 | 5432 |
| 4390 // Run the given mode's parser over a line, update the styles | 5433 // Run the given mode's parser over a line, calling f for each token. |
| 4391 // array, which contains alternating fragments of text and CSS | |
| 4392 // classes. | |
| 4393 function runMode(cm, text, mode, state, f, forceToEnd) { | 5434 function runMode(cm, text, mode, state, f, forceToEnd) { |
| 4394 var flattenSpans = mode.flattenSpans; | 5435 var flattenSpans = mode.flattenSpans; |
| 4395 if (flattenSpans == null) flattenSpans = cm.options.flattenSpans; | 5436 if (flattenSpans == null) flattenSpans = cm.options.flattenSpans; |
| 4396 var curStart = 0, curStyle = null; | 5437 var curStart = 0, curStyle = null; |
| 4397 var stream = new StringStream(text, cm.options.tabSize), style; | 5438 var stream = new StringStream(text, cm.options.tabSize), style; |
| 4398 if (text == "" && mode.blankLine) mode.blankLine(state); | 5439 if (text == "" && mode.blankLine) mode.blankLine(state); |
| 4399 while (!stream.eol()) { | 5440 while (!stream.eol()) { |
| 4400 if (stream.pos > cm.options.maxHighlightLength) { | 5441 if (stream.pos > cm.options.maxHighlightLength) { |
| 4401 flattenSpans = false; | 5442 flattenSpans = false; |
| 4402 if (forceToEnd) processLine(cm, text, state, stream.pos); | 5443 if (forceToEnd) processLine(cm, text, state, stream.pos); |
| (...skipping 13 matching lines...) Expand all Loading... |
| 4416 stream.start = stream.pos; | 5457 stream.start = stream.pos; |
| 4417 } | 5458 } |
| 4418 while (curStart < stream.pos) { | 5459 while (curStart < stream.pos) { |
| 4419 // Webkit seems to refuse to render text nodes longer than 57444 character
s | 5460 // Webkit seems to refuse to render text nodes longer than 57444 character
s |
| 4420 var pos = Math.min(stream.pos, curStart + 50000); | 5461 var pos = Math.min(stream.pos, curStart + 50000); |
| 4421 f(pos, curStyle); | 5462 f(pos, curStyle); |
| 4422 curStart = pos; | 5463 curStart = pos; |
| 4423 } | 5464 } |
| 4424 } | 5465 } |
| 4425 | 5466 |
| 5467 // Compute a style array (an array starting with a mode generation |
| 5468 // -- for invalidation -- followed by pairs of end positions and |
| 5469 // style strings), which is used to highlight the tokens on the |
| 5470 // line. |
| 4426 function highlightLine(cm, line, state, forceToEnd) { | 5471 function highlightLine(cm, line, state, forceToEnd) { |
| 4427 // A styles array always starts with a number identifying the | 5472 // A styles array always starts with a number identifying the |
| 4428 // mode/overlays that it is based on (for easy invalidation). | 5473 // mode/overlays that it is based on (for easy invalidation). |
| 4429 var st = [cm.state.modeGen]; | 5474 var st = [cm.state.modeGen]; |
| 4430 // Compute the base array of styles | 5475 // Compute the base array of styles |
| 4431 runMode(cm, line.text, cm.doc.mode, state, function(end, style) { | 5476 runMode(cm, line.text, cm.doc.mode, state, function(end, style) { |
| 4432 st.push(end, style); | 5477 st.push(end, style); |
| 4433 }, forceToEnd); | 5478 }, forceToEnd); |
| 4434 | 5479 |
| 4435 // Run overlays, adjust style array. | 5480 // Run overlays, adjust style array. |
| (...skipping 25 matching lines...) Expand all Loading... |
| 4461 return st; | 5506 return st; |
| 4462 } | 5507 } |
| 4463 | 5508 |
| 4464 function getLineStyles(cm, line) { | 5509 function getLineStyles(cm, line) { |
| 4465 if (!line.styles || line.styles[0] != cm.state.modeGen) | 5510 if (!line.styles || line.styles[0] != cm.state.modeGen) |
| 4466 line.styles = highlightLine(cm, line, line.stateAfter = getStateBefore(cm,
lineNo(line))); | 5511 line.styles = highlightLine(cm, line, line.stateAfter = getStateBefore(cm,
lineNo(line))); |
| 4467 return line.styles; | 5512 return line.styles; |
| 4468 } | 5513 } |
| 4469 | 5514 |
| 4470 // Lightweight form of highlight -- proceed over this line and | 5515 // Lightweight form of highlight -- proceed over this line and |
| 4471 // update state, but don't save a style array. | 5516 // update state, but don't save a style array. Used for lines that |
| 5517 // aren't currently visible. |
| 4472 function processLine(cm, text, state, startAt) { | 5518 function processLine(cm, text, state, startAt) { |
| 4473 var mode = cm.doc.mode; | 5519 var mode = cm.doc.mode; |
| 4474 var stream = new StringStream(text, cm.options.tabSize); | 5520 var stream = new StringStream(text, cm.options.tabSize); |
| 4475 stream.start = stream.pos = startAt || 0; | 5521 stream.start = stream.pos = startAt || 0; |
| 4476 if (text == "" && mode.blankLine) mode.blankLine(state); | 5522 if (text == "" && mode.blankLine) mode.blankLine(state); |
| 4477 while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) { | 5523 while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) { |
| 4478 mode.token(stream, state); | 5524 mode.token(stream, state); |
| 4479 stream.start = stream.pos; | 5525 stream.start = stream.pos; |
| 4480 } | 5526 } |
| 4481 } | 5527 } |
| 4482 | 5528 |
| 5529 // Convert a style as returned by a mode (either null, or a string |
| 5530 // containing one or more styles) to a CSS style. This is cached, |
| 5531 // and also looks for line-wide styles. |
| 4483 var styleToClassCache = {}, styleToClassCacheWithMode = {}; | 5532 var styleToClassCache = {}, styleToClassCacheWithMode = {}; |
| 4484 function interpretTokenStyle(style, builder) { | 5533 function interpretTokenStyle(style, builder) { |
| 4485 if (!style) return null; | 5534 if (!style) return null; |
| 4486 for (;;) { | 5535 for (;;) { |
| 4487 var lineClass = style.match(/(?:^|\s+)line-(background-)?(\S+)/); | 5536 var lineClass = style.match(/(?:^|\s+)line-(background-)?(\S+)/); |
| 4488 if (!lineClass) break; | 5537 if (!lineClass) break; |
| 4489 style = style.slice(0, lineClass.index) + style.slice(lineClass.index + li
neClass[0].length); | 5538 style = style.slice(0, lineClass.index) + style.slice(lineClass.index + li
neClass[0].length); |
| 4490 var prop = lineClass[1] ? "bgClass" : "textClass"; | 5539 var prop = lineClass[1] ? "bgClass" : "textClass"; |
| 4491 if (builder[prop] == null) | 5540 if (builder[prop] == null) |
| 4492 builder[prop] = lineClass[2]; | 5541 builder[prop] = lineClass[2]; |
| 4493 else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(builde
r[prop])) | 5542 else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(builde
r[prop])) |
| 4494 builder[prop] += " " + lineClass[2]; | 5543 builder[prop] += " " + lineClass[2]; |
| 4495 } | 5544 } |
| 4496 if (/^\s*$/.test(style)) return null; | 5545 if (/^\s*$/.test(style)) return null; |
| 4497 var cache = builder.cm.options.addModeClass ? styleToClassCacheWithMode : st
yleToClassCache; | 5546 var cache = builder.cm.options.addModeClass ? styleToClassCacheWithMode : st
yleToClassCache; |
| 4498 return cache[style] || | 5547 return cache[style] || |
| 4499 (cache[style] = style.replace(/\S+/g, "cm-$&")); | 5548 (cache[style] = style.replace(/\S+/g, "cm-$&")); |
| 4500 } | 5549 } |
| 4501 | 5550 |
| 4502 function buildLineContent(cm, realLine, measure, copyWidgets) { | 5551 // Render the DOM representation of the text of a line. Also builds |
| 4503 var merged, line = realLine, empty = true; | 5552 // up a 'line map', which points at the DOM nodes that represent |
| 4504 while (merged = collapsedSpanAtStart(line)) | 5553 // specific stretches of text, and is used by the measuring code. |
| 4505 line = getLine(cm.doc, merged.find().from.line); | 5554 // The returned object contains the DOM node, this map, and |
| 5555 // information about line-wide styles that were set by the mode. |
| 5556 function buildLineContent(cm, lineView) { |
| 5557 // The padding-right forces the element to have a 'border', which |
| 5558 // is needed on Webkit to be able to get line-level bounding |
| 5559 // rectangles for it (in measureChar). |
| 5560 var content = elt("span", null, null, webkit ? "padding-right: .1px" : null)
; |
| 5561 var builder = {pre: elt("pre", [content]), content: content, col: 0, pos: 0,
cm: cm}; |
| 5562 lineView.measure = {}; |
| 4506 | 5563 |
| 4507 var builder = {pre: elt("pre"), col: 0, pos: 0, | 5564 // Iterate over the logical lines that make up this visual line. |
| 4508 measure: null, measuredSomething: false, cm: cm, | 5565 for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { |
| 4509 copyWidgets: copyWidgets}; | 5566 var line = i ? lineView.rest[i - 1] : lineView.line, order; |
| 5567 builder.pos = 0; |
| 5568 builder.addToken = buildToken; |
| 5569 // Optionally wire in some hacks into the token-rendering |
| 5570 // algorithm, to deal with browser quirks. |
| 5571 if ((ie || webkit) && cm.getOption("lineWrapping")) |
| 5572 builder.addToken = buildTokenSplitSpaces(builder.addToken); |
| 5573 if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line))) |
| 5574 builder.addToken = buildTokenBadBidi(builder.addToken, order); |
| 5575 builder.map = []; |
| 5576 insertLineContent(line, builder, getLineStyles(cm, line)); |
| 4510 | 5577 |
| 4511 do { | 5578 // Ensure at least a single node is present, for measuring. |
| 4512 if (line.text) empty = false; | 5579 if (builder.map.length == 0) |
| 4513 builder.measure = line == realLine && measure; | 5580 builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.d
isplay.measure))); |
| 4514 builder.pos = 0; | |
| 4515 builder.addToken = builder.measure ? buildTokenMeasure : buildToken; | |
| 4516 if ((old_ie || webkit) && cm.getOption("lineWrapping")) | |
| 4517 builder.addToken = buildTokenSplitSpaces(builder.addToken); | |
| 4518 var next = insertLineContent(line, builder, getLineStyles(cm, line)); | |
| 4519 if (measure && line == realLine && !builder.measuredSomething) { | |
| 4520 measure[0] = builder.pre.appendChild(zeroWidthElement(cm.display.measure
)); | |
| 4521 builder.measuredSomething = true; | |
| 4522 } | |
| 4523 if (next) line = getLine(cm.doc, next.to.line); | |
| 4524 } while (next); | |
| 4525 | 5581 |
| 4526 if (measure && !builder.measuredSomething && !measure[0]) | 5582 // Store the map and a cache object for the current logical line |
| 4527 measure[0] = builder.pre.appendChild(empty ? elt("span", "\u00a0") : zeroW
idthElement(cm.display.measure)); | 5583 if (i == 0) { |
| 4528 if (!builder.pre.firstChild && !lineIsHidden(cm.doc, realLine)) | 5584 lineView.measure.map = builder.map; |
| 4529 builder.pre.appendChild(document.createTextNode("\u00a0")); | 5585 lineView.measure.cache = {}; |
| 4530 | 5586 } else { |
| 4531 var order; | 5587 (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map
); |
| 4532 // Work around problem with the reported dimensions of single-char | 5588 (lineView.measure.caches || (lineView.measure.caches = [])).push({}); |
| 4533 // direction spans on IE (issue #1129). See also the comment in | |
| 4534 // cursorCoords. | |
| 4535 if (measure && ie && (order = getOrder(line))) { | |
| 4536 var l = order.length - 1; | |
| 4537 if (order[l].from == order[l].to) --l; | |
| 4538 var last = order[l], prev = order[l - 1]; | |
| 4539 if (last.from + 1 == last.to && prev && last.level < prev.level) { | |
| 4540 var span = measure[builder.pos - 1]; | |
| 4541 if (span) span.parentNode.insertBefore(span.measureRight = zeroWidthElem
ent(cm.display.measure), | |
| 4542 span.nextSibling); | |
| 4543 } | 5589 } |
| 4544 } | 5590 } |
| 4545 | 5591 |
| 4546 var textClass = builder.textClass ? builder.textClass + " " + (realLine.text
Class || "") : realLine.textClass; | 5592 signal(cm, "renderLine", cm, lineView.line, builder.pre); |
| 4547 if (textClass) builder.pre.className = textClass; | |
| 4548 | |
| 4549 signal(cm, "renderLine", cm, realLine, builder.pre); | |
| 4550 return builder; | 5593 return builder; |
| 4551 } | 5594 } |
| 4552 | 5595 |
| 4553 function defaultSpecialCharPlaceholder(ch) { | 5596 function defaultSpecialCharPlaceholder(ch) { |
| 4554 var token = elt("span", "\u2022", "cm-invalidchar"); | 5597 var token = elt("span", "\u2022", "cm-invalidchar"); |
| 4555 token.title = "\\u" + ch.charCodeAt(0).toString(16); | 5598 token.title = "\\u" + ch.charCodeAt(0).toString(16); |
| 4556 return token; | 5599 return token; |
| 4557 } | 5600 } |
| 4558 | 5601 |
| 5602 // Build up the DOM representation for a single token, and add it to |
| 5603 // the line map. Takes care to render special characters separately. |
| 4559 function buildToken(builder, text, style, startStyle, endStyle, title) { | 5604 function buildToken(builder, text, style, startStyle, endStyle, title) { |
| 4560 if (!text) return; | 5605 if (!text) return; |
| 4561 var special = builder.cm.options.specialChars; | 5606 var special = builder.cm.options.specialChars, mustWrap = false; |
| 4562 if (!special.test(text)) { | 5607 if (!special.test(text)) { |
| 4563 builder.col += text.length; | 5608 builder.col += text.length; |
| 4564 var content = document.createTextNode(text); | 5609 var content = document.createTextNode(text); |
| 5610 builder.map.push(builder.pos, builder.pos + text.length, content); |
| 5611 if (ie_upto8) mustWrap = true; |
| 5612 builder.pos += text.length; |
| 4565 } else { | 5613 } else { |
| 4566 var content = document.createDocumentFragment(), pos = 0; | 5614 var content = document.createDocumentFragment(), pos = 0; |
| 4567 while (true) { | 5615 while (true) { |
| 4568 special.lastIndex = pos; | 5616 special.lastIndex = pos; |
| 4569 var m = special.exec(text); | 5617 var m = special.exec(text); |
| 4570 var skipped = m ? m.index - pos : text.length - pos; | 5618 var skipped = m ? m.index - pos : text.length - pos; |
| 4571 if (skipped) { | 5619 if (skipped) { |
| 4572 content.appendChild(document.createTextNode(text.slice(pos, pos + skip
ped))); | 5620 var txt = document.createTextNode(text.slice(pos, pos + skipped)); |
| 5621 if (ie_upto8) content.appendChild(elt("span", [txt])); |
| 5622 else content.appendChild(txt); |
| 5623 builder.map.push(builder.pos, builder.pos + skipped, txt); |
| 4573 builder.col += skipped; | 5624 builder.col += skipped; |
| 5625 builder.pos += skipped; |
| 4574 } | 5626 } |
| 4575 if (!m) break; | 5627 if (!m) break; |
| 4576 pos += skipped + 1; | 5628 pos += skipped + 1; |
| 4577 if (m[0] == "\t") { | 5629 if (m[0] == "\t") { |
| 4578 var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder
.col % tabSize; | 5630 var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder
.col % tabSize; |
| 4579 content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); | 5631 var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"
)); |
| 4580 builder.col += tabWidth; | 5632 builder.col += tabWidth; |
| 4581 } else { | 5633 } else { |
| 4582 var token = builder.cm.options.specialCharPlaceholder(m[0]); | 5634 var txt = builder.cm.options.specialCharPlaceholder(m[0]); |
| 4583 content.appendChild(token); | 5635 if (ie_upto8) content.appendChild(elt("span", [txt])); |
| 5636 else content.appendChild(txt); |
| 4584 builder.col += 1; | 5637 builder.col += 1; |
| 4585 } | 5638 } |
| 5639 builder.map.push(builder.pos, builder.pos + 1, txt); |
| 5640 builder.pos++; |
| 4586 } | 5641 } |
| 4587 } | 5642 } |
| 4588 if (style || startStyle || endStyle || builder.measure) { | 5643 if (style || startStyle || endStyle || mustWrap) { |
| 4589 var fullStyle = style || ""; | 5644 var fullStyle = style || ""; |
| 4590 if (startStyle) fullStyle += startStyle; | 5645 if (startStyle) fullStyle += startStyle; |
| 4591 if (endStyle) fullStyle += endStyle; | 5646 if (endStyle) fullStyle += endStyle; |
| 4592 var token = elt("span", [content], fullStyle); | 5647 var token = elt("span", [content], fullStyle); |
| 4593 if (title) token.title = title; | 5648 if (title) token.title = title; |
| 4594 return builder.pre.appendChild(token); | 5649 return builder.content.appendChild(token); |
| 4595 } | 5650 } |
| 4596 builder.pre.appendChild(content); | 5651 builder.content.appendChild(content); |
| 4597 } | |
| 4598 | |
| 4599 function buildTokenMeasure(builder, text, style, startStyle, endStyle) { | |
| 4600 var wrapping = builder.cm.options.lineWrapping; | |
| 4601 for (var i = 0; i < text.length; ++i) { | |
| 4602 var start = i == 0, to = i + 1; | |
| 4603 while (to < text.length && isExtendingChar(text.charAt(to))) ++to; | |
| 4604 var ch = text.slice(i, to); | |
| 4605 i = to - 1; | |
| 4606 if (i && wrapping && spanAffectsWrapping(text, i)) | |
| 4607 builder.pre.appendChild(elt("wbr")); | |
| 4608 var old = builder.measure[builder.pos]; | |
| 4609 var span = builder.measure[builder.pos] = | |
| 4610 buildToken(builder, ch, style, | |
| 4611 start && startStyle, i == text.length - 1 && endStyle); | |
| 4612 if (old) span.leftSide = old.leftSide || old; | |
| 4613 // In IE single-space nodes wrap differently than spaces | |
| 4614 // embedded in larger text nodes, except when set to | |
| 4615 // white-space: normal (issue #1268). | |
| 4616 if (old_ie && wrapping && ch == " " && i && !/\s/.test(text.charAt(i - 1))
&& | |
| 4617 i < text.length - 1 && !/\s/.test(text.charAt(i + 1))) | |
| 4618 span.style.whiteSpace = "normal"; | |
| 4619 builder.pos += ch.length; | |
| 4620 } | |
| 4621 if (text.length) builder.measuredSomething = true; | |
| 4622 } | 5652 } |
| 4623 | 5653 |
| 4624 function buildTokenSplitSpaces(inner) { | 5654 function buildTokenSplitSpaces(inner) { |
| 4625 function split(old) { | 5655 function split(old) { |
| 4626 var out = " "; | 5656 var out = " "; |
| 4627 for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0"; | 5657 for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0"; |
| 4628 out += " "; | 5658 out += " "; |
| 4629 return out; | 5659 return out; |
| 4630 } | 5660 } |
| 4631 return function(builder, text, style, startStyle, endStyle, title) { | 5661 return function(builder, text, style, startStyle, endStyle, title) { |
| 4632 return inner(builder, text.replace(/ {3,}/g, split), style, startStyle, en
dStyle, title); | 5662 inner(builder, text.replace(/ {3,}/g, split), style, startStyle, endStyle,
title); |
| 5663 }; |
| 5664 } |
| 5665 |
| 5666 // Work around nonsense dimensions being reported for stretches of |
| 5667 // right-to-left text. |
| 5668 function buildTokenBadBidi(inner, order) { |
| 5669 return function(builder, text, style, startStyle, endStyle, title) { |
| 5670 style = style ? style + " cm-force-border" : "cm-force-border"; |
| 5671 var start = builder.pos, end = start + text.length; |
| 5672 for (;;) { |
| 5673 // Find the part that overlaps with the start of this text |
| 5674 for (var i = 0; i < order.length; i++) { |
| 5675 var part = order[i]; |
| 5676 if (part.to > start && part.from <= start) break; |
| 5677 } |
| 5678 if (part.to >= end) return inner(builder, text, style, startStyle, endSt
yle, title); |
| 5679 inner(builder, text.slice(0, part.to - start), style, startStyle, null,
title); |
| 5680 startStyle = null; |
| 5681 text = text.slice(part.to - start); |
| 5682 start = part.to; |
| 5683 } |
| 4633 }; | 5684 }; |
| 4634 } | 5685 } |
| 4635 | 5686 |
| 4636 function buildCollapsedSpan(builder, size, marker, ignoreWidget) { | 5687 function buildCollapsedSpan(builder, size, marker, ignoreWidget) { |
| 4637 var widget = !ignoreWidget && marker.replacedWith; | 5688 var widget = !ignoreWidget && marker.widgetNode; |
| 4638 if (widget) { | 5689 if (widget) { |
| 4639 if (builder.copyWidgets) widget = widget.cloneNode(true); | 5690 builder.map.push(builder.pos, builder.pos + size, widget); |
| 4640 builder.pre.appendChild(widget); | 5691 builder.content.appendChild(widget); |
| 4641 if (builder.measure) { | |
| 4642 if (size) { | |
| 4643 builder.measure[builder.pos] = widget; | |
| 4644 } else { | |
| 4645 var elt = zeroWidthElement(builder.cm.display.measure); | |
| 4646 if (marker.type == "bookmark" && !marker.insertLeft) | |
| 4647 builder.measure[builder.pos] = builder.pre.appendChild(elt); | |
| 4648 else if (builder.measure[builder.pos]) | |
| 4649 return; | |
| 4650 else | |
| 4651 builder.measure[builder.pos] = builder.pre.insertBefore(elt, widget)
; | |
| 4652 } | |
| 4653 builder.measuredSomething = true; | |
| 4654 } | |
| 4655 } | 5692 } |
| 4656 builder.pos += size; | 5693 builder.pos += size; |
| 4657 } | 5694 } |
| 4658 | 5695 |
| 4659 // Outputs a number of spans to make up a line, taking highlighting | 5696 // Outputs a number of spans to make up a line, taking highlighting |
| 4660 // and marked text into account. | 5697 // and marked text into account. |
| 4661 function insertLineContent(line, builder, styles) { | 5698 function insertLineContent(line, builder, styles) { |
| 4662 var spans = line.markedSpans, allText = line.text, at = 0; | 5699 var spans = line.markedSpans, allText = line.text, at = 0; |
| 4663 if (!spans) { | 5700 if (!spans) { |
| 4664 for (var i = 1; i < styles.length; i+=2) | 5701 for (var i = 1; i < styles.length; i+=2) |
| (...skipping 14 matching lines...) Expand all Loading... |
| 4679 if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanE
ndStyle = ""; } | 5716 if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanE
ndStyle = ""; } |
| 4680 if (m.className) spanStyle += " " + m.className; | 5717 if (m.className) spanStyle += " " + m.className; |
| 4681 if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startS
tyle; | 5718 if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startS
tyle; |
| 4682 if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endSt
yle; | 5719 if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endSt
yle; |
| 4683 if (m.title && !title) title = m.title; | 5720 if (m.title && !title) title = m.title; |
| 4684 if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.
marker, m) < 0)) | 5721 if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.
marker, m) < 0)) |
| 4685 collapsed = sp; | 5722 collapsed = sp; |
| 4686 } else if (sp.from > pos && nextChange > sp.from) { | 5723 } else if (sp.from > pos && nextChange > sp.from) { |
| 4687 nextChange = sp.from; | 5724 nextChange = sp.from; |
| 4688 } | 5725 } |
| 4689 if (m.type == "bookmark" && sp.from == pos && m.replacedWith) foundBoo
kmarks.push(m); | 5726 if (m.type == "bookmark" && sp.from == pos && m.widgetNode) foundBookm
arks.push(m); |
| 4690 } | 5727 } |
| 4691 if (collapsed && (collapsed.from || 0) == pos) { | 5728 if (collapsed && (collapsed.from || 0) == pos) { |
| 4692 buildCollapsedSpan(builder, (collapsed.to == null ? len : collapsed.to
) - pos, | 5729 buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapse
d.to) - pos, |
| 4693 collapsed.marker, collapsed.from == null); | 5730 collapsed.marker, collapsed.from == null); |
| 4694 if (collapsed.to == null) return collapsed.marker.find(); | 5731 if (collapsed.to == null) return; |
| 4695 } | 5732 } |
| 4696 if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookma
rks.length; ++j) | 5733 if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookma
rks.length; ++j) |
| 4697 buildCollapsedSpan(builder, 0, foundBookmarks[j]); | 5734 buildCollapsedSpan(builder, 0, foundBookmarks[j]); |
| 4698 } | 5735 } |
| 4699 if (pos >= len) break; | 5736 if (pos >= len) break; |
| 4700 | 5737 |
| 4701 var upto = Math.min(len, nextChange); | 5738 var upto = Math.min(len, nextChange); |
| 4702 while (true) { | 5739 while (true) { |
| 4703 if (text) { | 5740 if (text) { |
| 4704 var end = pos + text.length; | 5741 var end = pos + text.length; |
| 4705 if (!collapsed) { | 5742 if (!collapsed) { |
| 4706 var tokenText = end > upto ? text.slice(0, upto - pos) : text; | 5743 var tokenText = end > upto ? text.slice(0, upto - pos) : text; |
| 4707 builder.addToken(builder, tokenText, style ? style + spanStyle : spa
nStyle, | 5744 builder.addToken(builder, tokenText, style ? style + spanStyle : spa
nStyle, |
| 4708 spanStartStyle, pos + tokenText.length == nextChang
e ? spanEndStyle : "", title); | 5745 spanStartStyle, pos + tokenText.length == nextChang
e ? spanEndStyle : "", title); |
| 4709 } | 5746 } |
| 4710 if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} | 5747 if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} |
| 4711 pos = end; | 5748 pos = end; |
| 4712 spanStartStyle = ""; | 5749 spanStartStyle = ""; |
| 4713 } | 5750 } |
| 4714 text = allText.slice(at, at = styles[i++]); | 5751 text = allText.slice(at, at = styles[i++]); |
| 4715 style = interpretTokenStyle(styles[i++], builder); | 5752 style = interpretTokenStyle(styles[i++], builder); |
| 4716 } | 5753 } |
| 4717 } | 5754 } |
| 4718 } | 5755 } |
| 4719 | 5756 |
| 4720 // DOCUMENT DATA STRUCTURE | 5757 // DOCUMENT DATA STRUCTURE |
| 4721 | 5758 |
| 4722 function updateDoc(doc, change, markedSpans, selAfter, estimateHeight) { | 5759 // By default, updates that start and end at the beginning of a line |
| 5760 // are treated specially, in order to make the association of line |
| 5761 // widgets and marker elements with the text behave more intuitive. |
| 5762 function isWholeLineUpdate(doc, change) { |
| 5763 return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && |
| 5764 (!doc.cm || doc.cm.options.wholeLineUpdateBefore); |
| 5765 } |
| 5766 |
| 5767 // Perform a change on the document data structure. |
| 5768 function updateDoc(doc, change, markedSpans, estimateHeight) { |
| 4723 function spansFor(n) {return markedSpans ? markedSpans[n] : null;} | 5769 function spansFor(n) {return markedSpans ? markedSpans[n] : null;} |
| 4724 function update(line, text, spans) { | 5770 function update(line, text, spans) { |
| 4725 updateLine(line, text, spans, estimateHeight); | 5771 updateLine(line, text, spans, estimateHeight); |
| 4726 signalLater(line, "change", line, change); | 5772 signalLater(line, "change", line, change); |
| 4727 } | 5773 } |
| 4728 | 5774 |
| 4729 var from = change.from, to = change.to, text = change.text; | 5775 var from = change.from, to = change.to, text = change.text; |
| 4730 var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); | 5776 var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); |
| 4731 var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to
.line - from.line; | 5777 var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to
.line - from.line; |
| 4732 | 5778 |
| 4733 // First adjust the line structure | 5779 // Adjust the line structure |
| 4734 if (from.ch == 0 && to.ch == 0 && lastText == "" && | 5780 if (isWholeLineUpdate(doc, change)) { |
| 4735 (!doc.cm || doc.cm.options.wholeLineUpdateBefore)) { | |
| 4736 // This is a whole-line replace. Treated specially to make | 5781 // This is a whole-line replace. Treated specially to make |
| 4737 // sure line objects move the way they are supposed to. | 5782 // sure line objects move the way they are supposed to. |
| 4738 for (var i = 0, e = text.length - 1, added = []; i < e; ++i) | 5783 for (var i = 0, added = []; i < text.length - 1; ++i) |
| 4739 added.push(new Line(text[i], spansFor(i), estimateHeight)); | 5784 added.push(new Line(text[i], spansFor(i), estimateHeight)); |
| 4740 update(lastLine, lastLine.text, lastSpans); | 5785 update(lastLine, lastLine.text, lastSpans); |
| 4741 if (nlines) doc.remove(from.line, nlines); | 5786 if (nlines) doc.remove(from.line, nlines); |
| 4742 if (added.length) doc.insert(from.line, added); | 5787 if (added.length) doc.insert(from.line, added); |
| 4743 } else if (firstLine == lastLine) { | 5788 } else if (firstLine == lastLine) { |
| 4744 if (text.length == 1) { | 5789 if (text.length == 1) { |
| 4745 update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLin
e.text.slice(to.ch), lastSpans); | 5790 update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLin
e.text.slice(to.ch), lastSpans); |
| 4746 } else { | 5791 } else { |
| 4747 for (var added = [], i = 1, e = text.length - 1; i < e; ++i) | 5792 for (var added = [], i = 1; i < text.length - 1; ++i) |
| 4748 added.push(new Line(text[i], spansFor(i), estimateHeight)); | 5793 added.push(new Line(text[i], spansFor(i), estimateHeight)); |
| 4749 added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, e
stimateHeight)); | 5794 added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, e
stimateHeight)); |
| 4750 update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0
)); | 5795 update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0
)); |
| 4751 doc.insert(from.line + 1, added); | 5796 doc.insert(from.line + 1, added); |
| 4752 } | 5797 } |
| 4753 } else if (text.length == 1) { | 5798 } else if (text.length == 1) { |
| 4754 update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.te
xt.slice(to.ch), spansFor(0)); | 5799 update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.te
xt.slice(to.ch), spansFor(0)); |
| 4755 doc.remove(from.line + 1, nlines); | 5800 doc.remove(from.line + 1, nlines); |
| 4756 } else { | 5801 } else { |
| 4757 update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
; | 5802 update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
; |
| 4758 update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); | 5803 update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); |
| 4759 for (var i = 1, e = text.length - 1, added = []; i < e; ++i) | 5804 for (var i = 1, added = []; i < text.length - 1; ++i) |
| 4760 added.push(new Line(text[i], spansFor(i), estimateHeight)); | 5805 added.push(new Line(text[i], spansFor(i), estimateHeight)); |
| 4761 if (nlines > 1) doc.remove(from.line + 1, nlines - 1); | 5806 if (nlines > 1) doc.remove(from.line + 1, nlines - 1); |
| 4762 doc.insert(from.line + 1, added); | 5807 doc.insert(from.line + 1, added); |
| 4763 } | 5808 } |
| 4764 | 5809 |
| 4765 signalLater(doc, "change", doc, change); | 5810 signalLater(doc, "change", doc, change); |
| 4766 setSelection(doc, selAfter.anchor, selAfter.head, null, true); | |
| 4767 } | 5811 } |
| 4768 | 5812 |
| 5813 // The document is represented as a BTree consisting of leaves, with |
| 5814 // chunk of lines in them, and branches, with up to ten leaves or |
| 5815 // other branch nodes below them. The top node is always a branch |
| 5816 // node, and is the document object itself (meaning it has |
| 5817 // additional methods and properties). |
| 5818 // |
| 5819 // All nodes have parent links. The tree is used both to go from |
| 5820 // line numbers to line objects, and to go from objects to numbers. |
| 5821 // It also indexes by height, and is used to convert between height |
| 5822 // and line object, and to find the total height of the document. |
| 5823 // |
| 5824 // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html |
| 5825 |
| 4769 function LeafChunk(lines) { | 5826 function LeafChunk(lines) { |
| 4770 this.lines = lines; | 5827 this.lines = lines; |
| 4771 this.parent = null; | 5828 this.parent = null; |
| 4772 for (var i = 0, e = lines.length, height = 0; i < e; ++i) { | 5829 for (var i = 0, height = 0; i < lines.length; ++i) { |
| 4773 lines[i].parent = this; | 5830 lines[i].parent = this; |
| 4774 height += lines[i].height; | 5831 height += lines[i].height; |
| 4775 } | 5832 } |
| 4776 this.height = height; | 5833 this.height = height; |
| 4777 } | 5834 } |
| 4778 | 5835 |
| 4779 LeafChunk.prototype = { | 5836 LeafChunk.prototype = { |
| 4780 chunkSize: function() { return this.lines.length; }, | 5837 chunkSize: function() { return this.lines.length; }, |
| 5838 // Remove the n lines at offset 'at'. |
| 4781 removeInner: function(at, n) { | 5839 removeInner: function(at, n) { |
| 4782 for (var i = at, e = at + n; i < e; ++i) { | 5840 for (var i = at, e = at + n; i < e; ++i) { |
| 4783 var line = this.lines[i]; | 5841 var line = this.lines[i]; |
| 4784 this.height -= line.height; | 5842 this.height -= line.height; |
| 4785 cleanUpLine(line); | 5843 cleanUpLine(line); |
| 4786 signalLater(line, "delete"); | 5844 signalLater(line, "delete"); |
| 4787 } | 5845 } |
| 4788 this.lines.splice(at, n); | 5846 this.lines.splice(at, n); |
| 4789 }, | 5847 }, |
| 5848 // Helper used to collapse a small branch into a single leaf. |
| 4790 collapse: function(lines) { | 5849 collapse: function(lines) { |
| 4791 lines.splice.apply(lines, [lines.length, 0].concat(this.lines)); | 5850 lines.push.apply(lines, this.lines); |
| 4792 }, | 5851 }, |
| 5852 // Insert the given array of lines at offset 'at', count them as |
| 5853 // having the given height. |
| 4793 insertInner: function(at, lines, height) { | 5854 insertInner: function(at, lines, height) { |
| 4794 this.height += height; | 5855 this.height += height; |
| 4795 this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice
(at)); | 5856 this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice
(at)); |
| 4796 for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this; | 5857 for (var i = 0; i < lines.length; ++i) lines[i].parent = this; |
| 4797 }, | 5858 }, |
| 5859 // Used to iterate over a part of the tree. |
| 4798 iterN: function(at, n, op) { | 5860 iterN: function(at, n, op) { |
| 4799 for (var e = at + n; at < e; ++at) | 5861 for (var e = at + n; at < e; ++at) |
| 4800 if (op(this.lines[at])) return true; | 5862 if (op(this.lines[at])) return true; |
| 4801 } | 5863 } |
| 4802 }; | 5864 }; |
| 4803 | 5865 |
| 4804 function BranchChunk(children) { | 5866 function BranchChunk(children) { |
| 4805 this.children = children; | 5867 this.children = children; |
| 4806 var size = 0, height = 0; | 5868 var size = 0, height = 0; |
| 4807 for (var i = 0, e = children.length; i < e; ++i) { | 5869 for (var i = 0; i < children.length; ++i) { |
| 4808 var ch = children[i]; | 5870 var ch = children[i]; |
| 4809 size += ch.chunkSize(); height += ch.height; | 5871 size += ch.chunkSize(); height += ch.height; |
| 4810 ch.parent = this; | 5872 ch.parent = this; |
| 4811 } | 5873 } |
| 4812 this.size = size; | 5874 this.size = size; |
| 4813 this.height = height; | 5875 this.height = height; |
| 4814 this.parent = null; | 5876 this.parent = null; |
| 4815 } | 5877 } |
| 4816 | 5878 |
| 4817 BranchChunk.prototype = { | 5879 BranchChunk.prototype = { |
| 4818 chunkSize: function() { return this.size; }, | 5880 chunkSize: function() { return this.size; }, |
| 4819 removeInner: function(at, n) { | 5881 removeInner: function(at, n) { |
| 4820 this.size -= n; | 5882 this.size -= n; |
| 4821 for (var i = 0; i < this.children.length; ++i) { | 5883 for (var i = 0; i < this.children.length; ++i) { |
| 4822 var child = this.children[i], sz = child.chunkSize(); | 5884 var child = this.children[i], sz = child.chunkSize(); |
| 4823 if (at < sz) { | 5885 if (at < sz) { |
| 4824 var rm = Math.min(n, sz - at), oldHeight = child.height; | 5886 var rm = Math.min(n, sz - at), oldHeight = child.height; |
| 4825 child.removeInner(at, rm); | 5887 child.removeInner(at, rm); |
| 4826 this.height -= oldHeight - child.height; | 5888 this.height -= oldHeight - child.height; |
| 4827 if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } | 5889 if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } |
| 4828 if ((n -= rm) == 0) break; | 5890 if ((n -= rm) == 0) break; |
| 4829 at = 0; | 5891 at = 0; |
| 4830 } else at -= sz; | 5892 } else at -= sz; |
| 4831 } | 5893 } |
| 4832 if (this.size - n < 25) { | 5894 // If the result is smaller than 25 lines, ensure that it is a |
| 5895 // single leaf node. |
| 5896 if (this.size - n < 25 && |
| 5897 (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))
) { |
| 4833 var lines = []; | 5898 var lines = []; |
| 4834 this.collapse(lines); | 5899 this.collapse(lines); |
| 4835 this.children = [new LeafChunk(lines)]; | 5900 this.children = [new LeafChunk(lines)]; |
| 4836 this.children[0].parent = this; | 5901 this.children[0].parent = this; |
| 4837 } | 5902 } |
| 4838 }, | 5903 }, |
| 4839 collapse: function(lines) { | 5904 collapse: function(lines) { |
| 4840 for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].col
lapse(lines); | 5905 for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(l
ines); |
| 4841 }, | 5906 }, |
| 4842 insertInner: function(at, lines, height) { | 5907 insertInner: function(at, lines, height) { |
| 4843 this.size += lines.length; | 5908 this.size += lines.length; |
| 4844 this.height += height; | 5909 this.height += height; |
| 4845 for (var i = 0, e = this.children.length; i < e; ++i) { | 5910 for (var i = 0; i < this.children.length; ++i) { |
| 4846 var child = this.children[i], sz = child.chunkSize(); | 5911 var child = this.children[i], sz = child.chunkSize(); |
| 4847 if (at <= sz) { | 5912 if (at <= sz) { |
| 4848 child.insertInner(at, lines, height); | 5913 child.insertInner(at, lines, height); |
| 4849 if (child.lines && child.lines.length > 50) { | 5914 if (child.lines && child.lines.length > 50) { |
| 4850 while (child.lines.length > 50) { | 5915 while (child.lines.length > 50) { |
| 4851 var spilled = child.lines.splice(child.lines.length - 25, 25); | 5916 var spilled = child.lines.splice(child.lines.length - 25, 25); |
| 4852 var newleaf = new LeafChunk(spilled); | 5917 var newleaf = new LeafChunk(spilled); |
| 4853 child.height -= newleaf.height; | 5918 child.height -= newleaf.height; |
| 4854 this.children.splice(i + 1, 0, newleaf); | 5919 this.children.splice(i + 1, 0, newleaf); |
| 4855 newleaf.parent = this; | 5920 newleaf.parent = this; |
| 4856 } | 5921 } |
| 4857 this.maybeSpill(); | 5922 this.maybeSpill(); |
| 4858 } | 5923 } |
| 4859 break; | 5924 break; |
| 4860 } | 5925 } |
| 4861 at -= sz; | 5926 at -= sz; |
| 4862 } | 5927 } |
| 4863 }, | 5928 }, |
| 5929 // When a node has grown, check whether it should be split. |
| 4864 maybeSpill: function() { | 5930 maybeSpill: function() { |
| 4865 if (this.children.length <= 10) return; | 5931 if (this.children.length <= 10) return; |
| 4866 var me = this; | 5932 var me = this; |
| 4867 do { | 5933 do { |
| 4868 var spilled = me.children.splice(me.children.length - 5, 5); | 5934 var spilled = me.children.splice(me.children.length - 5, 5); |
| 4869 var sibling = new BranchChunk(spilled); | 5935 var sibling = new BranchChunk(spilled); |
| 4870 if (!me.parent) { // Become the parent node | 5936 if (!me.parent) { // Become the parent node |
| 4871 var copy = new BranchChunk(me.children); | 5937 var copy = new BranchChunk(me.children); |
| 4872 copy.parent = me; | 5938 copy.parent = me; |
| 4873 me.children = [copy, sibling]; | 5939 me.children = [copy, sibling]; |
| 4874 me = copy; | 5940 me = copy; |
| 4875 } else { | 5941 } else { |
| 4876 me.size -= sibling.size; | 5942 me.size -= sibling.size; |
| 4877 me.height -= sibling.height; | 5943 me.height -= sibling.height; |
| 4878 var myIndex = indexOf(me.parent.children, me); | 5944 var myIndex = indexOf(me.parent.children, me); |
| 4879 me.parent.children.splice(myIndex + 1, 0, sibling); | 5945 me.parent.children.splice(myIndex + 1, 0, sibling); |
| 4880 } | 5946 } |
| 4881 sibling.parent = me.parent; | 5947 sibling.parent = me.parent; |
| 4882 } while (me.children.length > 10); | 5948 } while (me.children.length > 10); |
| 4883 me.parent.maybeSpill(); | 5949 me.parent.maybeSpill(); |
| 4884 }, | 5950 }, |
| 4885 iterN: function(at, n, op) { | 5951 iterN: function(at, n, op) { |
| 4886 for (var i = 0, e = this.children.length; i < e; ++i) { | 5952 for (var i = 0; i < this.children.length; ++i) { |
| 4887 var child = this.children[i], sz = child.chunkSize(); | 5953 var child = this.children[i], sz = child.chunkSize(); |
| 4888 if (at < sz) { | 5954 if (at < sz) { |
| 4889 var used = Math.min(n, sz - at); | 5955 var used = Math.min(n, sz - at); |
| 4890 if (child.iterN(at, used, op)) return true; | 5956 if (child.iterN(at, used, op)) return true; |
| 4891 if ((n -= used) == 0) break; | 5957 if ((n -= used) == 0) break; |
| 4892 at = 0; | 5958 at = 0; |
| 4893 } else at -= sz; | 5959 } else at -= sz; |
| 4894 } | 5960 } |
| 4895 } | 5961 } |
| 4896 }; | 5962 }; |
| 4897 | 5963 |
| 4898 var nextDocId = 0; | 5964 var nextDocId = 0; |
| 4899 var Doc = CodeMirror.Doc = function(text, mode, firstLine) { | 5965 var Doc = CodeMirror.Doc = function(text, mode, firstLine) { |
| 4900 if (!(this instanceof Doc)) return new Doc(text, mode, firstLine); | 5966 if (!(this instanceof Doc)) return new Doc(text, mode, firstLine); |
| 4901 if (firstLine == null) firstLine = 0; | 5967 if (firstLine == null) firstLine = 0; |
| 4902 | 5968 |
| 4903 BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); | 5969 BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); |
| 4904 this.first = firstLine; | 5970 this.first = firstLine; |
| 4905 this.scrollTop = this.scrollLeft = 0; | 5971 this.scrollTop = this.scrollLeft = 0; |
| 4906 this.cantEdit = false; | 5972 this.cantEdit = false; |
| 4907 this.history = makeHistory(); | |
| 4908 this.cleanGeneration = 1; | 5973 this.cleanGeneration = 1; |
| 4909 this.frontier = firstLine; | 5974 this.frontier = firstLine; |
| 4910 var start = Pos(firstLine, 0); | 5975 var start = Pos(firstLine, 0); |
| 4911 this.sel = {from: start, to: start, head: start, anchor: start, shift: false
, extend: false, goalColumn: null}; | 5976 this.sel = simpleSelection(start); |
| 5977 this.history = new History(null); |
| 4912 this.id = ++nextDocId; | 5978 this.id = ++nextDocId; |
| 4913 this.modeOption = mode; | 5979 this.modeOption = mode; |
| 4914 | 5980 |
| 4915 if (typeof text == "string") text = splitLines(text); | 5981 if (typeof text == "string") text = splitLines(text); |
| 4916 updateDoc(this, {from: start, to: start, text: text}, null, {head: start, an
chor: start}); | 5982 updateDoc(this, {from: start, to: start, text: text}); |
| 5983 setSelection(this, simpleSelection(start), sel_dontScroll); |
| 4917 }; | 5984 }; |
| 4918 | 5985 |
| 4919 Doc.prototype = createObj(BranchChunk.prototype, { | 5986 Doc.prototype = createObj(BranchChunk.prototype, { |
| 4920 constructor: Doc, | 5987 constructor: Doc, |
| 5988 // Iterate over the document. Supports two forms -- with only one |
| 5989 // argument, it calls that for each line in the document. With |
| 5990 // three, it iterates over the range given by the first two (with |
| 5991 // the second being non-inclusive). |
| 4921 iter: function(from, to, op) { | 5992 iter: function(from, to, op) { |
| 4922 if (op) this.iterN(from - this.first, to - from, op); | 5993 if (op) this.iterN(from - this.first, to - from, op); |
| 4923 else this.iterN(this.first, this.first + this.size, from); | 5994 else this.iterN(this.first, this.first + this.size, from); |
| 4924 }, | 5995 }, |
| 4925 | 5996 |
| 5997 // Non-public interface for adding and removing lines. |
| 4926 insert: function(at, lines) { | 5998 insert: function(at, lines) { |
| 4927 var height = 0; | 5999 var height = 0; |
| 4928 for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height; | 6000 for (var i = 0; i < lines.length; ++i) height += lines[i].height; |
| 4929 this.insertInner(at - this.first, lines, height); | 6001 this.insertInner(at - this.first, lines, height); |
| 4930 }, | 6002 }, |
| 4931 remove: function(at, n) { this.removeInner(at - this.first, n); }, | 6003 remove: function(at, n) { this.removeInner(at - this.first, n); }, |
| 4932 | 6004 |
| 6005 // From here, the methods are part of the public interface. Most |
| 6006 // are also available from CodeMirror (editor) instances. |
| 6007 |
| 4933 getValue: function(lineSep) { | 6008 getValue: function(lineSep) { |
| 4934 var lines = getLines(this, this.first, this.first + this.size); | 6009 var lines = getLines(this, this.first, this.first + this.size); |
| 4935 if (lineSep === false) return lines; | 6010 if (lineSep === false) return lines; |
| 4936 return lines.join(lineSep || "\n"); | 6011 return lines.join(lineSep || "\n"); |
| 4937 }, | 6012 }, |
| 4938 setValue: function(code) { | 6013 setValue: docMethodOp(function(code) { |
| 4939 var top = Pos(this.first, 0), last = this.first + this.size - 1; | 6014 var top = Pos(this.first, 0), last = this.first + this.size - 1; |
| 4940 makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length
), | 6015 makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length
), |
| 4941 text: splitLines(code), origin: "setValue"}, | 6016 text: splitLines(code), origin: "setValue"}, true); |
| 4942 {head: top, anchor: top}, true); | 6017 setSelection(this, simpleSelection(top)); |
| 4943 }, | 6018 }), |
| 4944 replaceRange: function(code, from, to, origin) { | 6019 replaceRange: function(code, from, to, origin) { |
| 4945 from = clipPos(this, from); | 6020 from = clipPos(this, from); |
| 4946 to = to ? clipPos(this, to) : from; | 6021 to = to ? clipPos(this, to) : from; |
| 4947 replaceRange(this, code, from, to, origin); | 6022 replaceRange(this, code, from, to, origin); |
| 4948 }, | 6023 }, |
| 4949 getRange: function(from, to, lineSep) { | 6024 getRange: function(from, to, lineSep) { |
| 4950 var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); | 6025 var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); |
| 4951 if (lineSep === false) return lines; | 6026 if (lineSep === false) return lines; |
| 4952 return lines.join(lineSep || "\n"); | 6027 return lines.join(lineSep || "\n"); |
| 4953 }, | 6028 }, |
| 4954 | 6029 |
| 4955 getLine: function(line) {var l = this.getLineHandle(line); return l && l.tex
t;}, | 6030 getLine: function(line) {var l = this.getLineHandle(line); return l && l.tex
t;}, |
| 4956 setLine: function(line, text) { | |
| 4957 if (isLine(this, line)) | |
| 4958 replaceRange(this, text, Pos(line, 0), clipPos(this, Pos(line))); | |
| 4959 }, | |
| 4960 removeLine: function(line) { | |
| 4961 if (line) replaceRange(this, "", clipPos(this, Pos(line - 1)), clipPos(thi
s, Pos(line))); | |
| 4962 else replaceRange(this, "", Pos(0, 0), clipPos(this, Pos(1, 0))); | |
| 4963 }, | |
| 4964 | 6031 |
| 4965 getLineHandle: function(line) {if (isLine(this, line)) return getLine(this,
line);}, | 6032 getLineHandle: function(line) {if (isLine(this, line)) return getLine(this,
line);}, |
| 4966 getLineNumber: function(line) {return lineNo(line);}, | 6033 getLineNumber: function(line) {return lineNo(line);}, |
| 4967 | 6034 |
| 4968 getLineHandleVisualStart: function(line) { | 6035 getLineHandleVisualStart: function(line) { |
| 4969 if (typeof line == "number") line = getLine(this, line); | 6036 if (typeof line == "number") line = getLine(this, line); |
| 4970 return visualLine(this, line); | 6037 return visualLine(line); |
| 4971 }, | 6038 }, |
| 4972 | 6039 |
| 4973 lineCount: function() {return this.size;}, | 6040 lineCount: function() {return this.size;}, |
| 4974 firstLine: function() {return this.first;}, | 6041 firstLine: function() {return this.first;}, |
| 4975 lastLine: function() {return this.first + this.size - 1;}, | 6042 lastLine: function() {return this.first + this.size - 1;}, |
| 4976 | 6043 |
| 4977 clipPos: function(pos) {return clipPos(this, pos);}, | 6044 clipPos: function(pos) {return clipPos(this, pos);}, |
| 4978 | 6045 |
| 4979 getCursor: function(start) { | 6046 getCursor: function(start) { |
| 4980 var sel = this.sel, pos; | 6047 var range = this.sel.primary(), pos; |
| 4981 if (start == null || start == "head") pos = sel.head; | 6048 if (start == null || start == "head") pos = range.head; |
| 4982 else if (start == "anchor") pos = sel.anchor; | 6049 else if (start == "anchor") pos = range.anchor; |
| 4983 else if (start == "end" || start === false) pos = sel.to; | 6050 else if (start == "end" || start == "to" || start === false) pos = range.t
o(); |
| 4984 else pos = sel.from; | 6051 else pos = range.from(); |
| 4985 return copyPos(pos); | 6052 return pos; |
| 4986 }, | 6053 }, |
| 4987 somethingSelected: function() {return !posEq(this.sel.head, this.sel.anchor)
;}, | 6054 listSelections: function() { return this.sel.ranges; }, |
| 6055 somethingSelected: function() {return this.sel.somethingSelected();}, |
| 4988 | 6056 |
| 4989 setCursor: docOperation(function(line, ch, extend) { | 6057 setCursor: docMethodOp(function(line, ch, options) { |
| 4990 var pos = clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : lin
e); | 6058 setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line,
ch || 0) : line), null, options); |
| 4991 if (extend) extendSelection(this, pos); | |
| 4992 else setSelection(this, pos, pos); | |
| 4993 }), | 6059 }), |
| 4994 setSelection: docOperation(function(anchor, head, bias) { | 6060 setSelection: docMethodOp(function(anchor, head, options) { |
| 4995 setSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), b
ias); | 6061 setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anch
or), options); |
| 4996 }), | 6062 }), |
| 4997 extendSelection: docOperation(function(from, to, bias) { | 6063 extendSelection: docMethodOp(function(head, other, options) { |
| 4998 extendSelection(this, clipPos(this, from), to && clipPos(this, to), bias); | 6064 extendSelection(this, clipPos(this, head), other && clipPos(this, other),
options); |
| 6065 }), |
| 6066 extendSelections: docMethodOp(function(heads, options) { |
| 6067 extendSelections(this, clipPosArray(this, heads, options)); |
| 6068 }), |
| 6069 extendSelectionsBy: docMethodOp(function(f, options) { |
| 6070 extendSelections(this, map(this.sel.ranges, f), options); |
| 6071 }), |
| 6072 setSelections: docMethodOp(function(ranges, primary, options) { |
| 6073 if (!ranges.length) return; |
| 6074 for (var i = 0, out = []; i < ranges.length; i++) |
| 6075 out[i] = new Range(clipPos(this, ranges[i].anchor), |
| 6076 clipPos(this, ranges[i].head)); |
| 6077 if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIn
dex); |
| 6078 setSelection(this, normalizeSelection(out, primary), options); |
| 6079 }), |
| 6080 addSelection: docMethodOp(function(anchor, head, options) { |
| 6081 var ranges = this.sel.ranges.slice(0); |
| 6082 ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)
)); |
| 6083 setSelection(this, normalizeSelection(ranges, ranges.length - 1), options)
; |
| 4999 }), | 6084 }), |
| 5000 | 6085 |
| 5001 getSelection: function(lineSep) {return this.getRange(this.sel.from, this.se
l.to, lineSep);}, | 6086 getSelection: function(lineSep) { |
| 5002 replaceSelection: function(code, collapse, origin) { | 6087 var ranges = this.sel.ranges, lines; |
| 5003 makeChange(this, {from: this.sel.from, to: this.sel.to, text: splitLines(c
ode), origin: origin}, collapse || "around"); | 6088 for (var i = 0; i < ranges.length; i++) { |
| 6089 var sel = getBetween(this, ranges[i].from(), ranges[i].to()); |
| 6090 lines = lines ? lines.concat(sel) : sel; |
| 6091 } |
| 6092 if (lineSep === false) return lines; |
| 6093 else return lines.join(lineSep || "\n"); |
| 5004 }, | 6094 }, |
| 5005 undo: docOperation(function() {makeChangeFromHistory(this, "undo");}), | 6095 getSelections: function(lineSep) { |
| 5006 redo: docOperation(function() {makeChangeFromHistory(this, "redo");}), | 6096 var parts = [], ranges = this.sel.ranges; |
| 6097 for (var i = 0; i < ranges.length; i++) { |
| 6098 var sel = getBetween(this, ranges[i].from(), ranges[i].to()); |
| 6099 if (lineSep !== false) sel = sel.join(lineSep || "\n"); |
| 6100 parts[i] = sel; |
| 6101 } |
| 6102 return parts; |
| 6103 }, |
| 6104 replaceSelection: docMethodOp(function(code, collapse, origin) { |
| 6105 var dup = []; |
| 6106 for (var i = 0; i < this.sel.ranges.length; i++) |
| 6107 dup[i] = code; |
| 6108 this.replaceSelections(dup, collapse, origin || "+input"); |
| 6109 }), |
| 6110 replaceSelections: function(code, collapse, origin) { |
| 6111 var changes = [], sel = this.sel; |
| 6112 for (var i = 0; i < sel.ranges.length; i++) { |
| 6113 var range = sel.ranges[i]; |
| 6114 changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[
i]), origin: origin}; |
| 6115 } |
| 6116 var newSel = collapse && collapse != "end" && computeReplacedSel(this, cha
nges, collapse); |
| 6117 for (var i = changes.length - 1; i >= 0; i--) |
| 6118 makeChange(this, changes[i]); |
| 6119 if (newSel) setSelectionReplaceHistory(this, newSel); |
| 6120 else if (this.cm) ensureCursorVisible(this.cm); |
| 6121 }, |
| 6122 undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), |
| 6123 redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), |
| 6124 undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", t
rue);}), |
| 6125 redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", t
rue);}), |
| 5007 | 6126 |
| 5008 setExtending: function(val) {this.sel.extend = val;}, | 6127 setExtending: function(val) {this.extend = val;}, |
| 6128 getExtending: function() {return this.extend;}, |
| 5009 | 6129 |
| 5010 historySize: function() { | 6130 historySize: function() { |
| 5011 var hist = this.history; | 6131 var hist = this.history, done = 0, undone = 0; |
| 5012 return {undo: hist.done.length, redo: hist.undone.length}; | 6132 for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++don
e; |
| 6133 for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) +
+undone; |
| 6134 return {undo: done, redo: undone}; |
| 5013 }, | 6135 }, |
| 5014 clearHistory: function() {this.history = makeHistory(this.history.maxGenerat
ion);}, | 6136 clearHistory: function() {this.history = new History(this.history.maxGenerat
ion);}, |
| 5015 | 6137 |
| 5016 markClean: function() { | 6138 markClean: function() { |
| 5017 this.cleanGeneration = this.changeGeneration(true); | 6139 this.cleanGeneration = this.changeGeneration(true); |
| 5018 }, | 6140 }, |
| 5019 changeGeneration: function(forceSplit) { | 6141 changeGeneration: function(forceSplit) { |
| 5020 if (forceSplit) | 6142 if (forceSplit) |
| 5021 this.history.lastOp = this.history.lastOrigin = null; | 6143 this.history.lastOp = this.history.lastOrigin = null; |
| 5022 return this.history.generation; | 6144 return this.history.generation; |
| 5023 }, | 6145 }, |
| 5024 isClean: function (gen) { | 6146 isClean: function (gen) { |
| 5025 return this.history.generation == (gen || this.cleanGeneration); | 6147 return this.history.generation == (gen || this.cleanGeneration); |
| 5026 }, | 6148 }, |
| 5027 | 6149 |
| 5028 getHistory: function() { | 6150 getHistory: function() { |
| 5029 return {done: copyHistoryArray(this.history.done), | 6151 return {done: copyHistoryArray(this.history.done), |
| 5030 undone: copyHistoryArray(this.history.undone)}; | 6152 undone: copyHistoryArray(this.history.undone)}; |
| 5031 }, | 6153 }, |
| 5032 setHistory: function(histData) { | 6154 setHistory: function(histData) { |
| 5033 var hist = this.history = makeHistory(this.history.maxGeneration); | 6155 var hist = this.history = new History(this.history.maxGeneration); |
| 5034 hist.done = histData.done.slice(0); | 6156 hist.done = copyHistoryArray(histData.done.slice(0), null, true); |
| 5035 hist.undone = histData.undone.slice(0); | 6157 hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); |
| 5036 }, | 6158 }, |
| 5037 | 6159 |
| 5038 markText: function(from, to, options) { | 6160 markText: function(from, to, options) { |
| 5039 return markText(this, clipPos(this, from), clipPos(this, to), options, "ra
nge"); | 6161 return markText(this, clipPos(this, from), clipPos(this, to), options, "ra
nge"); |
| 5040 }, | 6162 }, |
| 5041 setBookmark: function(pos, options) { | 6163 setBookmark: function(pos, options) { |
| 5042 var realOpts = {replacedWith: options && (options.nodeType == null ? optio
ns.widget : options), | 6164 var realOpts = {replacedWith: options && (options.nodeType == null ? optio
ns.widget : options), |
| 5043 insertLeft: options && options.insertLeft, | 6165 insertLeft: options && options.insertLeft, |
| 5044 clearWhenEmpty: false}; | 6166 clearWhenEmpty: false, shared: options && options.shared}; |
| 5045 pos = clipPos(this, pos); | 6167 pos = clipPos(this, pos); |
| 5046 return markText(this, pos, pos, realOpts, "bookmark"); | 6168 return markText(this, pos, pos, realOpts, "bookmark"); |
| 5047 }, | 6169 }, |
| 5048 findMarksAt: function(pos) { | 6170 findMarksAt: function(pos) { |
| 5049 pos = clipPos(this, pos); | 6171 pos = clipPos(this, pos); |
| 5050 var markers = [], spans = getLine(this, pos.line).markedSpans; | 6172 var markers = [], spans = getLine(this, pos.line).markedSpans; |
| 5051 if (spans) for (var i = 0; i < spans.length; ++i) { | 6173 if (spans) for (var i = 0; i < spans.length; ++i) { |
| 5052 var span = spans[i]; | 6174 var span = spans[i]; |
| 5053 if ((span.from == null || span.from <= pos.ch) && | 6175 if ((span.from == null || span.from <= pos.ch) && |
| 5054 (span.to == null || span.to >= pos.ch)) | 6176 (span.to == null || span.to >= pos.ch)) |
| 5055 markers.push(span.marker.parent || span.marker); | 6177 markers.push(span.marker.parent || span.marker); |
| 5056 } | 6178 } |
| 5057 return markers; | 6179 return markers; |
| 5058 }, | 6180 }, |
| 6181 findMarks: function(from, to) { |
| 6182 from = clipPos(this, from); to = clipPos(this, to); |
| 6183 var found = [], lineNo = from.line; |
| 6184 this.iter(from.line, to.line + 1, function(line) { |
| 6185 var spans = line.markedSpans; |
| 6186 if (spans) for (var i = 0; i < spans.length; i++) { |
| 6187 var span = spans[i]; |
| 6188 if (!(lineNo == from.line && from.ch > span.to || |
| 6189 span.from == null && lineNo != from.line|| |
| 6190 lineNo == to.line && span.from > to.ch)) |
| 6191 found.push(span.marker.parent || span.marker); |
| 6192 } |
| 6193 ++lineNo; |
| 6194 }); |
| 6195 return found; |
| 6196 }, |
| 5059 getAllMarks: function() { | 6197 getAllMarks: function() { |
| 5060 var markers = []; | 6198 var markers = []; |
| 5061 this.iter(function(line) { | 6199 this.iter(function(line) { |
| 5062 var sps = line.markedSpans; | 6200 var sps = line.markedSpans; |
| 5063 if (sps) for (var i = 0; i < sps.length; ++i) | 6201 if (sps) for (var i = 0; i < sps.length; ++i) |
| 5064 if (sps[i].from != null) markers.push(sps[i].marker); | 6202 if (sps[i].from != null) markers.push(sps[i].marker); |
| 5065 }); | 6203 }); |
| 5066 return markers; | 6204 return markers; |
| 5067 }, | 6205 }, |
| 5068 | 6206 |
| (...skipping 13 matching lines...) Expand all Loading... |
| 5082 if (coords.line < this.first || coords.ch < 0) return 0; | 6220 if (coords.line < this.first || coords.ch < 0) return 0; |
| 5083 this.iter(this.first, coords.line, function (line) { | 6221 this.iter(this.first, coords.line, function (line) { |
| 5084 index += line.text.length + 1; | 6222 index += line.text.length + 1; |
| 5085 }); | 6223 }); |
| 5086 return index; | 6224 return index; |
| 5087 }, | 6225 }, |
| 5088 | 6226 |
| 5089 copy: function(copyHistory) { | 6227 copy: function(copyHistory) { |
| 5090 var doc = new Doc(getLines(this, this.first, this.first + this.size), this
.modeOption, this.first); | 6228 var doc = new Doc(getLines(this, this.first, this.first + this.size), this
.modeOption, this.first); |
| 5091 doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; | 6229 doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; |
| 5092 doc.sel = {from: this.sel.from, to: this.sel.to, head: this.sel.head, anch
or: this.sel.anchor, | 6230 doc.sel = this.sel; |
| 5093 shift: this.sel.shift, extend: false, goalColumn: this.sel.goal
Column}; | 6231 doc.extend = false; |
| 5094 if (copyHistory) { | 6232 if (copyHistory) { |
| 5095 doc.history.undoDepth = this.history.undoDepth; | 6233 doc.history.undoDepth = this.history.undoDepth; |
| 5096 doc.setHistory(this.getHistory()); | 6234 doc.setHistory(this.getHistory()); |
| 5097 } | 6235 } |
| 5098 return doc; | 6236 return doc; |
| 5099 }, | 6237 }, |
| 5100 | 6238 |
| 5101 linkedDoc: function(options) { | 6239 linkedDoc: function(options) { |
| 5102 if (!options) options = {}; | 6240 if (!options) options = {}; |
| 5103 var from = this.first, to = this.first + this.size; | 6241 var from = this.first, to = this.first + this.size; |
| (...skipping 11 matching lines...) Expand all Loading... |
| 5115 var link = this.linked[i]; | 6253 var link = this.linked[i]; |
| 5116 if (link.doc != other) continue; | 6254 if (link.doc != other) continue; |
| 5117 this.linked.splice(i, 1); | 6255 this.linked.splice(i, 1); |
| 5118 other.unlinkDoc(this); | 6256 other.unlinkDoc(this); |
| 5119 break; | 6257 break; |
| 5120 } | 6258 } |
| 5121 // If the histories were shared, split them again | 6259 // If the histories were shared, split them again |
| 5122 if (other.history == this.history) { | 6260 if (other.history == this.history) { |
| 5123 var splitIds = [other.id]; | 6261 var splitIds = [other.id]; |
| 5124 linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true); | 6262 linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true); |
| 5125 other.history = makeHistory(); | 6263 other.history = new History(null); |
| 5126 other.history.done = copyHistoryArray(this.history.done, splitIds); | 6264 other.history.done = copyHistoryArray(this.history.done, splitIds); |
| 5127 other.history.undone = copyHistoryArray(this.history.undone, splitIds); | 6265 other.history.undone = copyHistoryArray(this.history.undone, splitIds); |
| 5128 } | 6266 } |
| 5129 }, | 6267 }, |
| 5130 iterLinkedDocs: function(f) {linkedDocs(this, f);}, | 6268 iterLinkedDocs: function(f) {linkedDocs(this, f);}, |
| 5131 | 6269 |
| 5132 getMode: function() {return this.mode;}, | 6270 getMode: function() {return this.mode;}, |
| 5133 getEditor: function() {return this.cm;} | 6271 getEditor: function() {return this.cm;} |
| 5134 }); | 6272 }); |
| 5135 | 6273 |
| 6274 // Public alias. |
| 5136 Doc.prototype.eachLine = Doc.prototype.iter; | 6275 Doc.prototype.eachLine = Doc.prototype.iter; |
| 5137 | 6276 |
| 5138 // The Doc methods that should be available on CodeMirror instances | 6277 // Set up methods on CodeMirror's prototype to redirect to the editor's docume
nt. |
| 5139 var dontDelegate = "iter insert remove copy getEditor".split(" "); | 6278 var dontDelegate = "iter insert remove copy getEditor".split(" "); |
| 5140 for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && inde
xOf(dontDelegate, prop) < 0) | 6279 for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && inde
xOf(dontDelegate, prop) < 0) |
| 5141 CodeMirror.prototype[prop] = (function(method) { | 6280 CodeMirror.prototype[prop] = (function(method) { |
| 5142 return function() {return method.apply(this.doc, arguments);}; | 6281 return function() {return method.apply(this.doc, arguments);}; |
| 5143 })(Doc.prototype[prop]); | 6282 })(Doc.prototype[prop]); |
| 5144 | 6283 |
| 5145 eventMixin(Doc); | 6284 eventMixin(Doc); |
| 5146 | 6285 |
| 6286 // Call f for all linked documents. |
| 5147 function linkedDocs(doc, f, sharedHistOnly) { | 6287 function linkedDocs(doc, f, sharedHistOnly) { |
| 5148 function propagate(doc, skip, sharedHist) { | 6288 function propagate(doc, skip, sharedHist) { |
| 5149 if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) { | 6289 if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) { |
| 5150 var rel = doc.linked[i]; | 6290 var rel = doc.linked[i]; |
| 5151 if (rel.doc == skip) continue; | 6291 if (rel.doc == skip) continue; |
| 5152 var shared = sharedHist && rel.sharedHist; | 6292 var shared = sharedHist && rel.sharedHist; |
| 5153 if (sharedHistOnly && !shared) continue; | 6293 if (sharedHistOnly && !shared) continue; |
| 5154 f(rel.doc, shared); | 6294 f(rel.doc, shared); |
| 5155 propagate(rel.doc, doc, shared); | 6295 propagate(rel.doc, doc, shared); |
| 5156 } | 6296 } |
| 5157 } | 6297 } |
| 5158 propagate(doc, null, true); | 6298 propagate(doc, null, true); |
| 5159 } | 6299 } |
| 5160 | 6300 |
| 6301 // Attach a document to an editor. |
| 5161 function attachDoc(cm, doc) { | 6302 function attachDoc(cm, doc) { |
| 5162 if (doc.cm) throw new Error("This document is already in use."); | 6303 if (doc.cm) throw new Error("This document is already in use."); |
| 5163 cm.doc = doc; | 6304 cm.doc = doc; |
| 5164 doc.cm = cm; | 6305 doc.cm = cm; |
| 5165 estimateLineHeights(cm); | 6306 estimateLineHeights(cm); |
| 5166 loadMode(cm); | 6307 loadMode(cm); |
| 5167 if (!cm.options.lineWrapping) computeMaxLength(cm); | 6308 if (!cm.options.lineWrapping) findMaxLine(cm); |
| 5168 cm.options.mode = doc.modeOption; | 6309 cm.options.mode = doc.modeOption; |
| 5169 regChange(cm); | 6310 regChange(cm); |
| 5170 } | 6311 } |
| 5171 | 6312 |
| 5172 // LINE UTILITIES | 6313 // LINE UTILITIES |
| 5173 | 6314 |
| 5174 function getLine(chunk, n) { | 6315 // Find the line object corresponding to the given line number. |
| 5175 n -= chunk.first; | 6316 function getLine(doc, n) { |
| 5176 while (!chunk.lines) { | 6317 n -= doc.first; |
| 6318 if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.f
irst) + " in the document."); |
| 6319 for (var chunk = doc; !chunk.lines;) { |
| 5177 for (var i = 0;; ++i) { | 6320 for (var i = 0;; ++i) { |
| 5178 var child = chunk.children[i], sz = child.chunkSize(); | 6321 var child = chunk.children[i], sz = child.chunkSize(); |
| 5179 if (n < sz) { chunk = child; break; } | 6322 if (n < sz) { chunk = child; break; } |
| 5180 n -= sz; | 6323 n -= sz; |
| 5181 } | 6324 } |
| 5182 } | 6325 } |
| 5183 return chunk.lines[n]; | 6326 return chunk.lines[n]; |
| 5184 } | 6327 } |
| 5185 | 6328 |
| 6329 // Get the part of a document between two positions, as an array of |
| 6330 // strings. |
| 5186 function getBetween(doc, start, end) { | 6331 function getBetween(doc, start, end) { |
| 5187 var out = [], n = start.line; | 6332 var out = [], n = start.line; |
| 5188 doc.iter(start.line, end.line + 1, function(line) { | 6333 doc.iter(start.line, end.line + 1, function(line) { |
| 5189 var text = line.text; | 6334 var text = line.text; |
| 5190 if (n == end.line) text = text.slice(0, end.ch); | 6335 if (n == end.line) text = text.slice(0, end.ch); |
| 5191 if (n == start.line) text = text.slice(start.ch); | 6336 if (n == start.line) text = text.slice(start.ch); |
| 5192 out.push(text); | 6337 out.push(text); |
| 5193 ++n; | 6338 ++n; |
| 5194 }); | 6339 }); |
| 5195 return out; | 6340 return out; |
| 5196 } | 6341 } |
| 6342 // Get the lines between from and to, as array of strings. |
| 5197 function getLines(doc, from, to) { | 6343 function getLines(doc, from, to) { |
| 5198 var out = []; | 6344 var out = []; |
| 5199 doc.iter(from, to, function(line) { out.push(line.text); }); | 6345 doc.iter(from, to, function(line) { out.push(line.text); }); |
| 5200 return out; | 6346 return out; |
| 5201 } | 6347 } |
| 5202 | 6348 |
| 6349 // Update the height of a line, propagating the height change |
| 6350 // upwards to parent nodes. |
| 5203 function updateLineHeight(line, height) { | 6351 function updateLineHeight(line, height) { |
| 5204 var diff = height - line.height; | 6352 var diff = height - line.height; |
| 5205 for (var n = line; n; n = n.parent) n.height += diff; | 6353 if (diff) for (var n = line; n; n = n.parent) n.height += diff; |
| 5206 } | 6354 } |
| 5207 | 6355 |
| 6356 // Given a line object, find its line number by walking up through |
| 6357 // its parent links. |
| 5208 function lineNo(line) { | 6358 function lineNo(line) { |
| 5209 if (line.parent == null) return null; | 6359 if (line.parent == null) return null; |
| 5210 var cur = line.parent, no = indexOf(cur.lines, line); | 6360 var cur = line.parent, no = indexOf(cur.lines, line); |
| 5211 for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { | 6361 for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { |
| 5212 for (var i = 0;; ++i) { | 6362 for (var i = 0;; ++i) { |
| 5213 if (chunk.children[i] == cur) break; | 6363 if (chunk.children[i] == cur) break; |
| 5214 no += chunk.children[i].chunkSize(); | 6364 no += chunk.children[i].chunkSize(); |
| 5215 } | 6365 } |
| 5216 } | 6366 } |
| 5217 return no + cur.first; | 6367 return no + cur.first; |
| 5218 } | 6368 } |
| 5219 | 6369 |
| 6370 // Find the line at the given vertical position, using the height |
| 6371 // information in the document tree. |
| 5220 function lineAtHeight(chunk, h) { | 6372 function lineAtHeight(chunk, h) { |
| 5221 var n = chunk.first; | 6373 var n = chunk.first; |
| 5222 outer: do { | 6374 outer: do { |
| 5223 for (var i = 0, e = chunk.children.length; i < e; ++i) { | 6375 for (var i = 0; i < chunk.children.length; ++i) { |
| 5224 var child = chunk.children[i], ch = child.height; | 6376 var child = chunk.children[i], ch = child.height; |
| 5225 if (h < ch) { chunk = child; continue outer; } | 6377 if (h < ch) { chunk = child; continue outer; } |
| 5226 h -= ch; | 6378 h -= ch; |
| 5227 n += child.chunkSize(); | 6379 n += child.chunkSize(); |
| 5228 } | 6380 } |
| 5229 return n; | 6381 return n; |
| 5230 } while (!chunk.lines); | 6382 } while (!chunk.lines); |
| 5231 for (var i = 0, e = chunk.lines.length; i < e; ++i) { | 6383 for (var i = 0; i < chunk.lines.length; ++i) { |
| 5232 var line = chunk.lines[i], lh = line.height; | 6384 var line = chunk.lines[i], lh = line.height; |
| 5233 if (h < lh) break; | 6385 if (h < lh) break; |
| 5234 h -= lh; | 6386 h -= lh; |
| 5235 } | 6387 } |
| 5236 return n + i; | 6388 return n + i; |
| 5237 } | 6389 } |
| 5238 | 6390 |
| 5239 function heightAtLine(cm, lineObj) { | 6391 |
| 5240 lineObj = visualLine(cm.doc, lineObj); | 6392 // Find the height above the given line. |
| 6393 function heightAtLine(lineObj) { |
| 6394 lineObj = visualLine(lineObj); |
| 5241 | 6395 |
| 5242 var h = 0, chunk = lineObj.parent; | 6396 var h = 0, chunk = lineObj.parent; |
| 5243 for (var i = 0; i < chunk.lines.length; ++i) { | 6397 for (var i = 0; i < chunk.lines.length; ++i) { |
| 5244 var line = chunk.lines[i]; | 6398 var line = chunk.lines[i]; |
| 5245 if (line == lineObj) break; | 6399 if (line == lineObj) break; |
| 5246 else h += line.height; | 6400 else h += line.height; |
| 5247 } | 6401 } |
| 5248 for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { | 6402 for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { |
| 5249 for (var i = 0; i < p.children.length; ++i) { | 6403 for (var i = 0; i < p.children.length; ++i) { |
| 5250 var cur = p.children[i]; | 6404 var cur = p.children[i]; |
| 5251 if (cur == chunk) break; | 6405 if (cur == chunk) break; |
| 5252 else h += cur.height; | 6406 else h += cur.height; |
| 5253 } | 6407 } |
| 5254 } | 6408 } |
| 5255 return h; | 6409 return h; |
| 5256 } | 6410 } |
| 5257 | 6411 |
| 6412 // Get the bidi ordering for the given line (and cache it). Returns |
| 6413 // false for lines that are fully left-to-right, and an array of |
| 6414 // BidiSpan objects otherwise. |
| 5258 function getOrder(line) { | 6415 function getOrder(line) { |
| 5259 var order = line.order; | 6416 var order = line.order; |
| 5260 if (order == null) order = line.order = bidiOrdering(line.text); | 6417 if (order == null) order = line.order = bidiOrdering(line.text); |
| 5261 return order; | 6418 return order; |
| 5262 } | 6419 } |
| 5263 | 6420 |
| 5264 // HISTORY | 6421 // HISTORY |
| 5265 | 6422 |
| 5266 function makeHistory(startGen) { | 6423 function History(startGen) { |
| 5267 return { | 6424 // Arrays of change events and selections. Doing something adds an |
| 5268 // Arrays of history events. Doing something adds an event to | 6425 // event to done and clears undo. Undoing moves events from done |
| 5269 // done and clears undo. Undoing moves events from done to | 6426 // to undone, redoing moves them in the other direction. |
| 5270 // undone, redoing moves them in the other direction. | 6427 this.done = []; this.undone = []; |
| 5271 done: [], undone: [], undoDepth: Infinity, | 6428 this.undoDepth = Infinity; |
| 5272 // Used to track when changes can be merged into a single undo | 6429 // Used to track when changes can be merged into a single undo |
| 5273 // event | 6430 // event |
| 5274 lastTime: 0, lastOp: null, lastOrigin: null, | 6431 this.lastModTime = this.lastSelTime = 0; |
| 5275 // Used by the isClean() method | 6432 this.lastOp = null; |
| 5276 generation: startGen || 1, maxGeneration: startGen || 1 | 6433 this.lastOrigin = this.lastSelOrigin = null; |
| 5277 }; | 6434 // Used by the isClean() method |
| 6435 this.generation = this.maxGeneration = startGen || 1; |
| 5278 } | 6436 } |
| 5279 | 6437 |
| 5280 function attachLocalSpans(doc, change, from, to) { | 6438 // Create a history change event from an updateDoc-style change |
| 5281 var existing = change["spans_" + doc.id], n = 0; | 6439 // object. |
| 5282 doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), func
tion(line) { | |
| 5283 if (line.markedSpans) | |
| 5284 (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.mark
edSpans; | |
| 5285 ++n; | |
| 5286 }); | |
| 5287 } | |
| 5288 | |
| 5289 function historyChangeFromChange(doc, change) { | 6440 function historyChangeFromChange(doc, change) { |
| 5290 var from = { line: change.from.line, ch: change.from.ch }; | 6441 var histChange = {from: copyPos(change.from), to: changeEnd(change), text: g
etBetween(doc, change.from, change.to)}; |
| 5291 var histChange = {from: from, to: changeEnd(change), text: getBetween(doc, c
hange.from, change.to)}; | |
| 5292 attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); | 6442 attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); |
| 5293 linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from
.line, change.to.line + 1);}, true); | 6443 linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from
.line, change.to.line + 1);}, true); |
| 5294 return histChange; | 6444 return histChange; |
| 5295 } | 6445 } |
| 5296 | 6446 |
| 5297 function addToHistory(doc, change, selAfter, opId) { | 6447 // Pop all selection events off the end of a history array. Stop at |
| 6448 // a change event. |
| 6449 function clearSelectionEvents(array) { |
| 6450 while (array.length) { |
| 6451 var last = lst(array); |
| 6452 if (last.ranges) array.pop(); |
| 6453 else break; |
| 6454 } |
| 6455 } |
| 6456 |
| 6457 // Find the top change event in the history. Pop off selection |
| 6458 // events that are in the way. |
| 6459 function lastChangeEvent(hist, force) { |
| 6460 if (force) { |
| 6461 clearSelectionEvents(hist.done); |
| 6462 return lst(hist.done); |
| 6463 } else if (hist.done.length && !lst(hist.done).ranges) { |
| 6464 return lst(hist.done); |
| 6465 } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges)
{ |
| 6466 hist.done.pop(); |
| 6467 return lst(hist.done); |
| 6468 } |
| 6469 } |
| 6470 |
| 6471 // Register a change in the history. Merges changes that are within |
| 6472 // a single operation, ore are close together with an origin that |
| 6473 // allows merging (starting with "+") into a single event. |
| 6474 function addChangeToHistory(doc, change, selAfter, opId) { |
| 5298 var hist = doc.history; | 6475 var hist = doc.history; |
| 5299 hist.undone.length = 0; | 6476 hist.undone.length = 0; |
| 5300 var time = +new Date, cur = lst(hist.done); | 6477 var time = +new Date, cur; |
| 5301 | 6478 |
| 5302 if (cur && | 6479 if ((hist.lastOp == opId || |
| 5303 (hist.lastOp == opId || | |
| 5304 hist.lastOrigin == change.origin && change.origin && | 6480 hist.lastOrigin == change.origin && change.origin && |
| 5305 ((change.origin.charAt(0) == "+" && doc.cm && hist.lastTime > time - do
c.cm.options.historyEventDelay) || | 6481 ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time -
doc.cm.options.historyEventDelay) || |
| 5306 change.origin.charAt(0) == "*"))) { | 6482 change.origin.charAt(0) == "*")) && |
| 6483 (cur = lastChangeEvent(hist, hist.lastOp == opId))) { |
| 5307 // Merge this change into the last event | 6484 // Merge this change into the last event |
| 5308 var last = lst(cur.changes); | 6485 var last = lst(cur.changes); |
| 5309 if (posEq(change.from, change.to) && posEq(change.from, last.to)) { | 6486 if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { |
| 5310 // Optimized case for simple insertion -- don't want to add | 6487 // Optimized case for simple insertion -- don't want to add |
| 5311 // new changesets for every character typed | 6488 // new changesets for every character typed |
| 5312 last.to = changeEnd(change); | 6489 last.to = changeEnd(change); |
| 5313 } else { | 6490 } else { |
| 5314 // Add new sub-event | 6491 // Add new sub-event |
| 5315 cur.changes.push(historyChangeFromChange(doc, change)); | 6492 cur.changes.push(historyChangeFromChange(doc, change)); |
| 5316 } | 6493 } |
| 5317 cur.anchorAfter = selAfter.anchor; cur.headAfter = selAfter.head; | |
| 5318 } else { | 6494 } else { |
| 5319 // Can not be merged, start a new event. | 6495 // Can not be merged, start a new event. |
| 6496 var before = lst(hist.done); |
| 6497 if (!before || !before.ranges) |
| 6498 pushSelectionToHistory(doc.sel, hist.done); |
| 5320 cur = {changes: [historyChangeFromChange(doc, change)], | 6499 cur = {changes: [historyChangeFromChange(doc, change)], |
| 5321 generation: hist.generation, | 6500 generation: hist.generation}; |
| 5322 anchorBefore: doc.sel.anchor, headBefore: doc.sel.head, | |
| 5323 anchorAfter: selAfter.anchor, headAfter: selAfter.head}; | |
| 5324 hist.done.push(cur); | 6501 hist.done.push(cur); |
| 5325 while (hist.done.length > hist.undoDepth) | 6502 while (hist.done.length > hist.undoDepth) { |
| 5326 hist.done.shift(); | 6503 hist.done.shift(); |
| 6504 if (!hist.done[0].ranges) hist.done.shift(); |
| 6505 } |
| 5327 } | 6506 } |
| 6507 hist.done.push(selAfter); |
| 5328 hist.generation = ++hist.maxGeneration; | 6508 hist.generation = ++hist.maxGeneration; |
| 5329 hist.lastTime = time; | 6509 hist.lastModTime = hist.lastSelTime = time; |
| 5330 hist.lastOp = opId; | 6510 hist.lastOp = opId; |
| 5331 hist.lastOrigin = change.origin; | 6511 hist.lastOrigin = hist.lastSelOrigin = change.origin; |
| 6512 |
| 6513 if (!last) signal(doc, "historyAdded"); |
| 5332 } | 6514 } |
| 5333 | 6515 |
| 6516 function selectionEventCanBeMerged(doc, origin, prev, sel) { |
| 6517 var ch = origin.charAt(0); |
| 6518 return ch == "*" || |
| 6519 ch == "+" && |
| 6520 prev.ranges.length == sel.ranges.length && |
| 6521 prev.somethingSelected() == sel.somethingSelected() && |
| 6522 new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEven
tDelay : 500); |
| 6523 } |
| 6524 |
| 6525 // Called whenever the selection changes, sets the new selection as |
| 6526 // the pending selection in the history, and pushes the old pending |
| 6527 // selection into the 'done' array when it was significantly |
| 6528 // different (in number of selected ranges, emptiness, or time). |
| 6529 function addSelectionToHistory(doc, sel, opId, options) { |
| 6530 var hist = doc.history, origin = options && options.origin; |
| 6531 |
| 6532 // A new event is started when the previous origin does not match |
| 6533 // the current, or the origins don't allow matching. Origins |
| 6534 // starting with * are always merged, those starting with + are |
| 6535 // merged when similar and close together in time. |
| 6536 if (opId == hist.lastOp || |
| 6537 (origin && hist.lastSelOrigin == origin && |
| 6538 (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || |
| 6539 selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) |
| 6540 hist.done[hist.done.length - 1] = sel; |
| 6541 else |
| 6542 pushSelectionToHistory(sel, hist.done); |
| 6543 |
| 6544 hist.lastSelTime = +new Date; |
| 6545 hist.lastSelOrigin = origin; |
| 6546 hist.lastOp = opId; |
| 6547 if (options && options.clearRedo !== false) |
| 6548 clearSelectionEvents(hist.undone); |
| 6549 } |
| 6550 |
| 6551 function pushSelectionToHistory(sel, dest) { |
| 6552 var top = lst(dest); |
| 6553 if (!(top && top.ranges && top.equals(sel))) |
| 6554 dest.push(sel); |
| 6555 } |
| 6556 |
| 6557 // Used to store marked span information in the history. |
| 6558 function attachLocalSpans(doc, change, from, to) { |
| 6559 var existing = change["spans_" + doc.id], n = 0; |
| 6560 doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), func
tion(line) { |
| 6561 if (line.markedSpans) |
| 6562 (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.mark
edSpans; |
| 6563 ++n; |
| 6564 }); |
| 6565 } |
| 6566 |
| 6567 // When un/re-doing restores text containing marked spans, those |
| 6568 // that have been explicitly cleared should not be restored. |
| 5334 function removeClearedSpans(spans) { | 6569 function removeClearedSpans(spans) { |
| 5335 if (!spans) return null; | 6570 if (!spans) return null; |
| 5336 for (var i = 0, out; i < spans.length; ++i) { | 6571 for (var i = 0, out; i < spans.length; ++i) { |
| 5337 if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i)
; } | 6572 if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i)
; } |
| 5338 else if (out) out.push(spans[i]); | 6573 else if (out) out.push(spans[i]); |
| 5339 } | 6574 } |
| 5340 return !out ? spans : out.length ? out : null; | 6575 return !out ? spans : out.length ? out : null; |
| 5341 } | 6576 } |
| 5342 | 6577 |
| 6578 // Retrieve and filter the old marked spans stored in a change event. |
| 5343 function getOldSpans(doc, change) { | 6579 function getOldSpans(doc, change) { |
| 5344 var found = change["spans_" + doc.id]; | 6580 var found = change["spans_" + doc.id]; |
| 5345 if (!found) return null; | 6581 if (!found) return null; |
| 5346 for (var i = 0, nw = []; i < change.text.length; ++i) | 6582 for (var i = 0, nw = []; i < change.text.length; ++i) |
| 5347 nw.push(removeClearedSpans(found[i])); | 6583 nw.push(removeClearedSpans(found[i])); |
| 5348 return nw; | 6584 return nw; |
| 5349 } | 6585 } |
| 5350 | 6586 |
| 5351 // Used both to provide a JSON-safe object in .getHistory, and, when | 6587 // Used both to provide a JSON-safe object in .getHistory, and, when |
| 5352 // detaching a document, to split the history in two | 6588 // detaching a document, to split the history in two |
| 5353 function copyHistoryArray(events, newGroup) { | 6589 function copyHistoryArray(events, newGroup, instantiateSel) { |
| 5354 for (var i = 0, copy = []; i < events.length; ++i) { | 6590 for (var i = 0, copy = []; i < events.length; ++i) { |
| 5355 var event = events[i], changes = event.changes, newChanges = []; | 6591 var event = events[i]; |
| 5356 copy.push({changes: newChanges, anchorBefore: event.anchorBefore, headBefo
re: event.headBefore, | 6592 if (event.ranges) { |
| 5357 anchorAfter: event.anchorAfter, headAfter: event.headAfter}); | 6593 copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : ev
ent); |
| 6594 continue; |
| 6595 } |
| 6596 var changes = event.changes, newChanges = []; |
| 6597 copy.push({changes: newChanges}); |
| 5358 for (var j = 0; j < changes.length; ++j) { | 6598 for (var j = 0; j < changes.length; ++j) { |
| 5359 var change = changes[j], m; | 6599 var change = changes[j], m; |
| 5360 newChanges.push({from: change.from, to: change.to, text: change.text}); | 6600 newChanges.push({from: change.from, to: change.to, text: change.text}); |
| 5361 if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$
/)) { | 6601 if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$
/)) { |
| 5362 if (indexOf(newGroup, Number(m[1])) > -1) { | 6602 if (indexOf(newGroup, Number(m[1])) > -1) { |
| 5363 lst(newChanges)[prop] = change[prop]; | 6603 lst(newChanges)[prop] = change[prop]; |
| 5364 delete change[prop]; | 6604 delete change[prop]; |
| 5365 } | 6605 } |
| 5366 } | 6606 } |
| 5367 } | 6607 } |
| 5368 } | 6608 } |
| 5369 return copy; | 6609 return copy; |
| 5370 } | 6610 } |
| 5371 | 6611 |
| 5372 // Rebasing/resetting history to deal with externally-sourced changes | 6612 // Rebasing/resetting history to deal with externally-sourced changes |
| 5373 | 6613 |
| 5374 function rebaseHistSel(pos, from, to, diff) { | 6614 function rebaseHistSelSingle(pos, from, to, diff) { |
| 5375 if (to < pos.line) { | 6615 if (to < pos.line) { |
| 5376 pos.line += diff; | 6616 pos.line += diff; |
| 5377 } else if (from < pos.line) { | 6617 } else if (from < pos.line) { |
| 5378 pos.line = from; | 6618 pos.line = from; |
| 5379 pos.ch = 0; | 6619 pos.ch = 0; |
| 5380 } | 6620 } |
| 5381 } | 6621 } |
| 5382 | 6622 |
| 5383 // Tries to rebase an array of history events given a change in the | 6623 // Tries to rebase an array of history events given a change in the |
| 5384 // document. If the change touches the same lines as the event, the | 6624 // document. If the change touches the same lines as the event, the |
| 5385 // event, and everything 'behind' it, is discarded. If the change is | 6625 // event, and everything 'behind' it, is discarded. If the change is |
| 5386 // before the event, the event's positions are updated. Uses a | 6626 // before the event, the event's positions are updated. Uses a |
| 5387 // copy-on-write scheme for the positions, to avoid having to | 6627 // copy-on-write scheme for the positions, to avoid having to |
| 5388 // reallocate them all on every rebase, but also avoid problems with | 6628 // reallocate them all on every rebase, but also avoid problems with |
| 5389 // shared position objects being unsafely updated. | 6629 // shared position objects being unsafely updated. |
| 5390 function rebaseHistArray(array, from, to, diff) { | 6630 function rebaseHistArray(array, from, to, diff) { |
| 5391 for (var i = 0; i < array.length; ++i) { | 6631 for (var i = 0; i < array.length; ++i) { |
| 5392 var sub = array[i], ok = true; | 6632 var sub = array[i], ok = true; |
| 6633 if (sub.ranges) { |
| 6634 if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } |
| 6635 for (var j = 0; j < sub.ranges.length; j++) { |
| 6636 rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); |
| 6637 rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); |
| 6638 } |
| 6639 continue; |
| 6640 } |
| 5393 for (var j = 0; j < sub.changes.length; ++j) { | 6641 for (var j = 0; j < sub.changes.length; ++j) { |
| 5394 var cur = sub.changes[j]; | 6642 var cur = sub.changes[j]; |
| 5395 if (!sub.copied) { cur.from = copyPos(cur.from); cur.to = copyPos(cur.to
); } | |
| 5396 if (to < cur.from.line) { | 6643 if (to < cur.from.line) { |
| 5397 cur.from.line += diff; | 6644 cur.from = Pos(cur.from.line + diff, cur.from.ch); |
| 5398 cur.to.line += diff; | 6645 cur.to = Pos(cur.to.line + diff, cur.to.ch); |
| 5399 } else if (from <= cur.to.line) { | 6646 } else if (from <= cur.to.line) { |
| 5400 ok = false; | 6647 ok = false; |
| 5401 break; | 6648 break; |
| 5402 } | 6649 } |
| 5403 } | 6650 } |
| 5404 if (!sub.copied) { | |
| 5405 sub.anchorBefore = copyPos(sub.anchorBefore); sub.headBefore = copyPos(s
ub.headBefore); | |
| 5406 sub.anchorAfter = copyPos(sub.anchorAfter); sub.readAfter = copyPos(sub.
headAfter); | |
| 5407 sub.copied = true; | |
| 5408 } | |
| 5409 if (!ok) { | 6651 if (!ok) { |
| 5410 array.splice(0, i + 1); | 6652 array.splice(0, i + 1); |
| 5411 i = 0; | 6653 i = 0; |
| 5412 } else { | |
| 5413 rebaseHistSel(sub.anchorBefore); rebaseHistSel(sub.headBefore); | |
| 5414 rebaseHistSel(sub.anchorAfter); rebaseHistSel(sub.headAfter); | |
| 5415 } | 6654 } |
| 5416 } | 6655 } |
| 5417 } | 6656 } |
| 5418 | 6657 |
| 5419 function rebaseHist(hist, change) { | 6658 function rebaseHist(hist, change) { |
| 5420 var from = change.from.line, to = change.to.line, diff = change.text.length
- (to - from) - 1; | 6659 var from = change.from.line, to = change.to.line, diff = change.text.length
- (to - from) - 1; |
| 5421 rebaseHistArray(hist.done, from, to, diff); | 6660 rebaseHistArray(hist.done, from, to, diff); |
| 5422 rebaseHistArray(hist.undone, from, to, diff); | 6661 rebaseHistArray(hist.undone, from, to, diff); |
| 5423 } | 6662 } |
| 5424 | 6663 |
| 5425 // EVENT OPERATORS | 6664 // EVENT UTILITIES |
| 5426 | 6665 |
| 5427 function stopMethod() {e_stop(this);} | 6666 // Due to the fact that we still support jurassic IE versions, some |
| 5428 // Ensure an event has a stop method. | 6667 // compatibility wrappers are needed. |
| 5429 function addStop(event) { | |
| 5430 if (!event.stop) event.stop = stopMethod; | |
| 5431 return event; | |
| 5432 } | |
| 5433 | 6668 |
| 5434 function e_preventDefault(e) { | 6669 var e_preventDefault = CodeMirror.e_preventDefault = function(e) { |
| 5435 if (e.preventDefault) e.preventDefault(); | 6670 if (e.preventDefault) e.preventDefault(); |
| 5436 else e.returnValue = false; | 6671 else e.returnValue = false; |
| 5437 } | 6672 }; |
| 5438 function e_stopPropagation(e) { | 6673 var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) { |
| 5439 if (e.stopPropagation) e.stopPropagation(); | 6674 if (e.stopPropagation) e.stopPropagation(); |
| 5440 else e.cancelBubble = true; | 6675 else e.cancelBubble = true; |
| 5441 } | 6676 }; |
| 5442 function e_defaultPrevented(e) { | 6677 function e_defaultPrevented(e) { |
| 5443 return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == fa
lse; | 6678 return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == fa
lse; |
| 5444 } | 6679 } |
| 5445 function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);} | 6680 var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropa
gation(e);}; |
| 5446 CodeMirror.e_stop = e_stop; | |
| 5447 CodeMirror.e_preventDefault = e_preventDefault; | |
| 5448 CodeMirror.e_stopPropagation = e_stopPropagation; | |
| 5449 | 6681 |
| 5450 function e_target(e) {return e.target || e.srcElement;} | 6682 function e_target(e) {return e.target || e.srcElement;} |
| 5451 function e_button(e) { | 6683 function e_button(e) { |
| 5452 var b = e.which; | 6684 var b = e.which; |
| 5453 if (b == null) { | 6685 if (b == null) { |
| 5454 if (e.button & 1) b = 1; | 6686 if (e.button & 1) b = 1; |
| 5455 else if (e.button & 2) b = 3; | 6687 else if (e.button & 2) b = 3; |
| 5456 else if (e.button & 4) b = 2; | 6688 else if (e.button & 4) b = 2; |
| 5457 } | 6689 } |
| 5458 if (mac && e.ctrlKey && b == 1) b = 3; | 6690 if (mac && e.ctrlKey && b == 1) b = 3; |
| 5459 return b; | 6691 return b; |
| 5460 } | 6692 } |
| 5461 | 6693 |
| 5462 // EVENT HANDLING | 6694 // EVENT HANDLING |
| 5463 | 6695 |
| 5464 function on(emitter, type, f) { | 6696 // Lightweight event framework. on/off also work on DOM nodes, |
| 6697 // registering native DOM handlers. |
| 6698 |
| 6699 var on = CodeMirror.on = function(emitter, type, f) { |
| 5465 if (emitter.addEventListener) | 6700 if (emitter.addEventListener) |
| 5466 emitter.addEventListener(type, f, false); | 6701 emitter.addEventListener(type, f, false); |
| 5467 else if (emitter.attachEvent) | 6702 else if (emitter.attachEvent) |
| 5468 emitter.attachEvent("on" + type, f); | 6703 emitter.attachEvent("on" + type, f); |
| 5469 else { | 6704 else { |
| 5470 var map = emitter._handlers || (emitter._handlers = {}); | 6705 var map = emitter._handlers || (emitter._handlers = {}); |
| 5471 var arr = map[type] || (map[type] = []); | 6706 var arr = map[type] || (map[type] = []); |
| 5472 arr.push(f); | 6707 arr.push(f); |
| 5473 } | 6708 } |
| 5474 } | 6709 }; |
| 5475 | 6710 |
| 5476 function off(emitter, type, f) { | 6711 var off = CodeMirror.off = function(emitter, type, f) { |
| 5477 if (emitter.removeEventListener) | 6712 if (emitter.removeEventListener) |
| 5478 emitter.removeEventListener(type, f, false); | 6713 emitter.removeEventListener(type, f, false); |
| 5479 else if (emitter.detachEvent) | 6714 else if (emitter.detachEvent) |
| 5480 emitter.detachEvent("on" + type, f); | 6715 emitter.detachEvent("on" + type, f); |
| 5481 else { | 6716 else { |
| 5482 var arr = emitter._handlers && emitter._handlers[type]; | 6717 var arr = emitter._handlers && emitter._handlers[type]; |
| 5483 if (!arr) return; | 6718 if (!arr) return; |
| 5484 for (var i = 0; i < arr.length; ++i) | 6719 for (var i = 0; i < arr.length; ++i) |
| 5485 if (arr[i] == f) { arr.splice(i, 1); break; } | 6720 if (arr[i] == f) { arr.splice(i, 1); break; } |
| 5486 } | 6721 } |
| 5487 } | 6722 }; |
| 5488 | 6723 |
| 5489 function signal(emitter, type /*, values...*/) { | 6724 var signal = CodeMirror.signal = function(emitter, type /*, values...*/) { |
| 5490 var arr = emitter._handlers && emitter._handlers[type]; | 6725 var arr = emitter._handlers && emitter._handlers[type]; |
| 5491 if (!arr) return; | 6726 if (!arr) return; |
| 5492 var args = Array.prototype.slice.call(arguments, 2); | 6727 var args = Array.prototype.slice.call(arguments, 2); |
| 5493 for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args); | 6728 for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args); |
| 5494 } | 6729 }; |
| 5495 | 6730 |
| 6731 // Often, we want to signal events at a point where we are in the |
| 6732 // middle of some work, but don't want the handler to start calling |
| 6733 // other methods on the editor, which might be in an inconsistent |
| 6734 // state or simply not expect any other events to happen. |
| 6735 // signalLater looks whether there are any handlers, and schedules |
| 6736 // them to be executed when the last operation ends, or, if no |
| 6737 // operation is active, when a timeout fires. |
| 5496 var delayedCallbacks, delayedCallbackDepth = 0; | 6738 var delayedCallbacks, delayedCallbackDepth = 0; |
| 5497 function signalLater(emitter, type /*, values...*/) { | 6739 function signalLater(emitter, type /*, values...*/) { |
| 5498 var arr = emitter._handlers && emitter._handlers[type]; | 6740 var arr = emitter._handlers && emitter._handlers[type]; |
| 5499 if (!arr) return; | 6741 if (!arr) return; |
| 5500 var args = Array.prototype.slice.call(arguments, 2); | 6742 var args = Array.prototype.slice.call(arguments, 2); |
| 5501 if (!delayedCallbacks) { | 6743 if (!delayedCallbacks) { |
| 5502 ++delayedCallbackDepth; | 6744 ++delayedCallbackDepth; |
| 5503 delayedCallbacks = []; | 6745 delayedCallbacks = []; |
| 5504 setTimeout(fireDelayed, 0); | 6746 setTimeout(fireDelayed, 0); |
| 5505 } | 6747 } |
| 5506 function bnd(f) {return function(){f.apply(null, args);};}; | 6748 function bnd(f) {return function(){f.apply(null, args);};}; |
| 5507 for (var i = 0; i < arr.length; ++i) | 6749 for (var i = 0; i < arr.length; ++i) |
| 5508 delayedCallbacks.push(bnd(arr[i])); | 6750 delayedCallbacks.push(bnd(arr[i])); |
| 5509 } | 6751 } |
| 5510 | 6752 |
| 5511 function signalDOMEvent(cm, e, override) { | |
| 5512 signal(cm, override || e.type, cm, e); | |
| 5513 return e_defaultPrevented(e) || e.codemirrorIgnore; | |
| 5514 } | |
| 5515 | |
| 5516 function fireDelayed() { | 6753 function fireDelayed() { |
| 5517 --delayedCallbackDepth; | 6754 --delayedCallbackDepth; |
| 5518 var delayed = delayedCallbacks; | 6755 var delayed = delayedCallbacks; |
| 5519 delayedCallbacks = null; | 6756 delayedCallbacks = null; |
| 5520 for (var i = 0; i < delayed.length; ++i) delayed[i](); | 6757 for (var i = 0; i < delayed.length; ++i) delayed[i](); |
| 5521 } | 6758 } |
| 5522 | 6759 |
| 6760 // The DOM events that CodeMirror handles can be overridden by |
| 6761 // registering a (non-DOM) handler on the editor for the event name, |
| 6762 // and preventDefault-ing the event in that handler. |
| 6763 function signalDOMEvent(cm, e, override) { |
| 6764 signal(cm, override || e.type, cm, e); |
| 6765 return e_defaultPrevented(e) || e.codemirrorIgnore; |
| 6766 } |
| 6767 |
| 5523 function hasHandler(emitter, type) { | 6768 function hasHandler(emitter, type) { |
| 5524 var arr = emitter._handlers && emitter._handlers[type]; | 6769 var arr = emitter._handlers && emitter._handlers[type]; |
| 5525 return arr && arr.length > 0; | 6770 return arr && arr.length > 0; |
| 5526 } | 6771 } |
| 5527 | 6772 |
| 5528 CodeMirror.on = on; CodeMirror.off = off; CodeMirror.signal = signal; | 6773 // Add on and off methods to a constructor's prototype, to make |
| 5529 | 6774 // registering events on such objects more convenient. |
| 5530 function eventMixin(ctor) { | 6775 function eventMixin(ctor) { |
| 5531 ctor.prototype.on = function(type, f) {on(this, type, f);}; | 6776 ctor.prototype.on = function(type, f) {on(this, type, f);}; |
| 5532 ctor.prototype.off = function(type, f) {off(this, type, f);}; | 6777 ctor.prototype.off = function(type, f) {off(this, type, f);}; |
| 5533 } | 6778 } |
| 5534 | 6779 |
| 5535 // MISC UTILITIES | 6780 // MISC UTILITIES |
| 5536 | 6781 |
| 5537 // Number of pixels added to scroller and sizer to hide scrollbar | 6782 // Number of pixels added to scroller and sizer to hide scrollbar |
| 5538 var scrollerCutOff = 30; | 6783 var scrollerCutOff = 30; |
| 5539 | 6784 |
| 5540 // Returned or thrown by various protocols to signal 'I'm not | 6785 // Returned or thrown by various protocols to signal 'I'm not |
| 5541 // handling this'. | 6786 // handling this'. |
| 5542 var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}
; | 6787 var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}
; |
| 5543 | 6788 |
| 6789 // Reused option objects for setSelection & friends |
| 6790 var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move
= {origin: "+move"}; |
| 6791 |
| 5544 function Delayed() {this.id = null;} | 6792 function Delayed() {this.id = null;} |
| 5545 Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = se
tTimeout(f, ms);}}; | 6793 Delayed.prototype.set = function(ms, f) { |
| 6794 clearTimeout(this.id); |
| 6795 this.id = setTimeout(f, ms); |
| 6796 }; |
| 5546 | 6797 |
| 5547 // Counts the column offset in a string, taking tabs into account. | 6798 // Counts the column offset in a string, taking tabs into account. |
| 5548 // Used mostly to find indentation. | 6799 // Used mostly to find indentation. |
| 5549 function countColumn(string, end, tabSize, startIndex, startValue) { | 6800 var countColumn = CodeMirror.countColumn = function(string, end, tabSize, star
tIndex, startValue) { |
| 5550 if (end == null) { | 6801 if (end == null) { |
| 5551 end = string.search(/[^\s\u00a0]/); | 6802 end = string.search(/[^\s\u00a0]/); |
| 5552 if (end == -1) end = string.length; | 6803 if (end == -1) end = string.length; |
| 5553 } | 6804 } |
| 5554 for (var i = startIndex || 0, n = startValue || 0; i < end; ++i) { | 6805 for (var i = startIndex || 0, n = startValue || 0;;) { |
| 5555 if (string.charAt(i) == "\t") n += tabSize - (n % tabSize); | 6806 var nextTab = string.indexOf("\t", i); |
| 5556 else ++n; | 6807 if (nextTab < 0 || nextTab >= end) |
| 6808 return n + (end - i); |
| 6809 n += nextTab - i; |
| 6810 n += tabSize - (n % tabSize); |
| 6811 i = nextTab + 1; |
| 5557 } | 6812 } |
| 5558 return n; | 6813 }; |
| 6814 |
| 6815 // The inverse of countColumn -- find the offset that corresponds to |
| 6816 // a particular column. |
| 6817 function findColumn(string, goal, tabSize) { |
| 6818 for (var pos = 0, col = 0;;) { |
| 6819 var nextTab = string.indexOf("\t", pos); |
| 6820 if (nextTab == -1) nextTab = string.length; |
| 6821 var skipped = nextTab - pos; |
| 6822 if (nextTab == string.length || col + skipped >= goal) |
| 6823 return pos + Math.min(skipped, goal - col); |
| 6824 col += nextTab - pos; |
| 6825 col += tabSize - (col % tabSize); |
| 6826 pos = nextTab + 1; |
| 6827 if (col >= goal) return pos; |
| 6828 } |
| 5559 } | 6829 } |
| 5560 CodeMirror.countColumn = countColumn; | |
| 5561 | 6830 |
| 5562 var spaceStrs = [""]; | 6831 var spaceStrs = [""]; |
| 5563 function spaceStr(n) { | 6832 function spaceStr(n) { |
| 5564 while (spaceStrs.length <= n) | 6833 while (spaceStrs.length <= n) |
| 5565 spaceStrs.push(lst(spaceStrs) + " "); | 6834 spaceStrs.push(lst(spaceStrs) + " "); |
| 5566 return spaceStrs[n]; | 6835 return spaceStrs[n]; |
| 5567 } | 6836 } |
| 5568 | 6837 |
| 5569 function lst(arr) { return arr[arr.length-1]; } | 6838 function lst(arr) { return arr[arr.length-1]; } |
| 5570 | 6839 |
| 5571 function selectInput(node) { | 6840 var selectInput = function(node) { node.select(); }; |
| 5572 if (ios) { // Mobile Safari apparently has a bug where select() is broken. | 6841 if (ios) // Mobile Safari apparently has a bug where select() is broken. |
| 5573 node.selectionStart = 0; | 6842 selectInput = function(node) { node.selectionStart = 0; node.selectionEnd =
node.value.length; }; |
| 5574 node.selectionEnd = node.value.length; | 6843 else if (ie) // Suppress mysterious IE10 errors |
| 5575 } else { | 6844 selectInput = function(node) { try { node.select(); } catch(_e) {} }; |
| 5576 // Suppress mysterious IE10 errors | |
| 5577 try { node.select(); } | |
| 5578 catch(_e) {} | |
| 5579 } | |
| 5580 } | |
| 5581 | 6845 |
| 5582 function indexOf(collection, elt) { | 6846 function indexOf(array, elt) { |
| 5583 if (collection.indexOf) return collection.indexOf(elt); | 6847 for (var i = 0; i < array.length; ++i) |
| 5584 for (var i = 0, e = collection.length; i < e; ++i) | 6848 if (array[i] == elt) return i; |
| 5585 if (collection[i] == elt) return i; | |
| 5586 return -1; | 6849 return -1; |
| 5587 } | 6850 } |
| 6851 if ([].indexOf) indexOf = function(array, elt) { return array.indexOf(elt); }; |
| 6852 function map(array, f) { |
| 6853 var out = []; |
| 6854 for (var i = 0; i < array.length; i++) out[i] = f(array[i], i); |
| 6855 return out; |
| 6856 } |
| 6857 if ([].map) map = function(array, f) { return array.map(f); }; |
| 5588 | 6858 |
| 5589 function createObj(base, props) { | 6859 function createObj(base, props) { |
| 5590 function Obj() {} | 6860 var inst; |
| 5591 Obj.prototype = base; | 6861 if (Object.create) { |
| 5592 var inst = new Obj(); | 6862 inst = Object.create(base); |
| 6863 } else { |
| 6864 var ctor = function() {}; |
| 6865 ctor.prototype = base; |
| 6866 inst = new ctor(); |
| 6867 } |
| 5593 if (props) copyObj(props, inst); | 6868 if (props) copyObj(props, inst); |
| 5594 return inst; | 6869 return inst; |
| 5595 } | 6870 }; |
| 5596 | 6871 |
| 5597 function copyObj(obj, target) { | 6872 function copyObj(obj, target) { |
| 5598 if (!target) target = {}; | 6873 if (!target) target = {}; |
| 5599 for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop]
; | 6874 for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop]
; |
| 5600 return target; | 6875 return target; |
| 5601 } | 6876 } |
| 5602 | 6877 |
| 5603 function emptyArray(size) { | |
| 5604 for (var a = [], i = 0; i < size; ++i) a.push(undefined); | |
| 5605 return a; | |
| 5606 } | |
| 5607 | |
| 5608 function bind(f) { | 6878 function bind(f) { |
| 5609 var args = Array.prototype.slice.call(arguments, 1); | 6879 var args = Array.prototype.slice.call(arguments, 1); |
| 5610 return function(){return f.apply(null, args);}; | 6880 return function(){return f.apply(null, args);}; |
| 5611 } | 6881 } |
| 5612 | 6882 |
| 5613 var nonASCIISingleCaseWordChar = /[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e
00-\u9fcc\uac00-\ud7af]/; | 6883 var nonASCIISingleCaseWordChar = /[\u00df\u3040-\u309f\u30a0-\u30ff\u3400-\u4d
b5\u4e00-\u9fcc\uac00-\ud7af]/; |
| 5614 function isWordChar(ch) { | 6884 var isWordChar = CodeMirror.isWordChar = function(ch) { |
| 5615 return /\w/.test(ch) || ch > "\x80" && | 6885 return /\w/.test(ch) || ch > "\x80" && |
| 5616 (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(c
h)); | 6886 (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(c
h)); |
| 5617 } | 6887 }; |
| 5618 | 6888 |
| 5619 function isEmpty(obj) { | 6889 function isEmpty(obj) { |
| 5620 for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false; | 6890 for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false; |
| 5621 return true; | 6891 return true; |
| 5622 } | 6892 } |
| 5623 | 6893 |
| 6894 // Extending unicode characters. A series of a non-extending char + |
| 6895 // any number of extending chars is treated as a single unit as far |
| 6896 // as editing and measuring is concerned. This is not fully correct, |
| 6897 // since some scripts/fonts/browsers also treat other configurations |
| 6898 // of code points as a group. |
| 5624 var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05
c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u
06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u081
9\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u
0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u
0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0
a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b
3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3
e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0c
c6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d6
3\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0e
b4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0
f80-\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-\u17b
d\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u19
39-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u
1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-
\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1c
e8\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\ua9b
3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab
2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe0
0-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; | 6899 var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05
c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u
06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u081
9\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u
0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u
0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0
a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b
3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3
e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0c
c6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d6
3\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0e
b4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0
f80-\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-\u17b
d\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u19
39-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u
1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-
\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1c
e8\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\ua9b
3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab
2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe0
0-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; |
| 5625 function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChar
s.test(ch); } | 6900 function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChar
s.test(ch); } |
| 5626 | 6901 |
| 5627 // DOM UTILITIES | 6902 // DOM UTILITIES |
| 5628 | 6903 |
| 5629 function elt(tag, content, className, style) { | 6904 function elt(tag, content, className, style) { |
| 5630 var e = document.createElement(tag); | 6905 var e = document.createElement(tag); |
| 5631 if (className) e.className = className; | 6906 if (className) e.className = className; |
| 5632 if (style) e.style.cssText = style; | 6907 if (style) e.style.cssText = style; |
| 5633 if (typeof content == "string") setTextContent(e, content); | 6908 if (typeof content == "string") e.appendChild(document.createTextNode(conten
t)); |
| 5634 else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(con
tent[i]); | 6909 else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(con
tent[i]); |
| 5635 return e; | 6910 return e; |
| 5636 } | 6911 } |
| 5637 | 6912 |
| 6913 var range; |
| 6914 if (document.createRange) range = function(node, start, end) { |
| 6915 var r = document.createRange(); |
| 6916 r.setEnd(node, end); |
| 6917 r.setStart(node, start); |
| 6918 return r; |
| 6919 }; |
| 6920 else range = function(node, start, end) { |
| 6921 var r = document.body.createTextRange(); |
| 6922 r.moveToElementText(node.parentNode); |
| 6923 r.collapse(true); |
| 6924 r.moveEnd("character", end); |
| 6925 r.moveStart("character", start); |
| 6926 return r; |
| 6927 }; |
| 6928 |
| 5638 function removeChildren(e) { | 6929 function removeChildren(e) { |
| 5639 for (var count = e.childNodes.length; count > 0; --count) | 6930 for (var count = e.childNodes.length; count > 0; --count) |
| 5640 e.removeChild(e.firstChild); | 6931 e.removeChild(e.firstChild); |
| 5641 return e; | 6932 return e; |
| 5642 } | 6933 } |
| 5643 | 6934 |
| 5644 function removeChildrenAndAdd(parent, e) { | 6935 function removeChildrenAndAdd(parent, e) { |
| 5645 return removeChildren(parent).appendChild(e); | 6936 return removeChildren(parent).appendChild(e); |
| 5646 } | 6937 } |
| 5647 | 6938 |
| 5648 function setTextContent(e, str) { | 6939 function contains(parent, child) { |
| 5649 if (ie_lt9) { | 6940 if (parent.contains) |
| 5650 e.innerHTML = ""; | 6941 return parent.contains(child); |
| 5651 e.appendChild(document.createTextNode(str)); | 6942 while (child = child.parentNode) |
| 5652 } else e.textContent = str; | 6943 if (child == parent) return true; |
| 5653 } | 6944 } |
| 5654 | 6945 |
| 5655 function getRect(node) { | 6946 function activeElt() { return document.activeElement; } |
| 5656 return node.getBoundingClientRect(); | 6947 // Older versions of IE throws unspecified error when touching |
| 5657 } | 6948 // document.activeElement in some cases (during loading, in iframe) |
| 5658 CodeMirror.replaceGetRect = function(f) { getRect = f; }; | 6949 if (ie_upto10) activeElt = function() { |
| 6950 try { return document.activeElement; } |
| 6951 catch(e) { return document.body; } |
| 6952 }; |
| 5659 | 6953 |
| 5660 // FEATURE DETECTION | 6954 // FEATURE DETECTION |
| 5661 | 6955 |
| 5662 // Detect drag-and-drop | 6956 // Detect drag-and-drop |
| 5663 var dragAndDrop = function() { | 6957 var dragAndDrop = function() { |
| 5664 // There is *some* kind of drag-and-drop support in IE6-8, but I | 6958 // There is *some* kind of drag-and-drop support in IE6-8, but I |
| 5665 // couldn't get it to work yet. | 6959 // couldn't get it to work yet. |
| 5666 if (ie_lt9) return false; | 6960 if (ie_upto8) return false; |
| 5667 var div = elt('div'); | 6961 var div = elt('div'); |
| 5668 return "draggable" in div || "dragDrop" in div; | 6962 return "draggable" in div || "dragDrop" in div; |
| 5669 }(); | 6963 }(); |
| 5670 | 6964 |
| 5671 // For a reason I have yet to figure out, some browsers disallow | |
| 5672 // word wrapping between certain characters *only* if a new inline | |
| 5673 // element is started between them. This makes it hard to reliably | |
| 5674 // measure the position of things, since that requires inserting an | |
| 5675 // extra span. This terribly fragile set of tests matches the | |
| 5676 // character combinations that suffer from this phenomenon on the | |
| 5677 // various browsers. | |
| 5678 function spanAffectsWrapping() { return false; } | |
| 5679 if (gecko) // Only for "$'" | |
| 5680 spanAffectsWrapping = function(str, i) { | |
| 5681 return str.charCodeAt(i - 1) == 36 && str.charCodeAt(i) == 39; | |
| 5682 }; | |
| 5683 else if (safari && !/Version\/([6-9]|\d\d)\b/.test(navigator.userAgent)) | |
| 5684 spanAffectsWrapping = function(str, i) { | |
| 5685 return /\-[^ \-?]|\?[^ !\'\"\),.\-\/:;\?\]\}]/.test(str.slice(i - 1, i + 1
)); | |
| 5686 }; | |
| 5687 else if (webkit && /Chrome\/(?:29|[3-9]\d|\d\d\d)\./.test(navigator.userAgent)
) | |
| 5688 spanAffectsWrapping = function(str, i) { | |
| 5689 var code = str.charCodeAt(i - 1); | |
| 5690 return code >= 8208 && code <= 8212; | |
| 5691 }; | |
| 5692 else if (webkit) | |
| 5693 spanAffectsWrapping = function(str, i) { | |
| 5694 if (i > 1 && str.charCodeAt(i - 1) == 45) { | |
| 5695 if (/\w/.test(str.charAt(i - 2)) && /[^\-?\.]/.test(str.charAt(i))) retu
rn true; | |
| 5696 if (i > 2 && /[\d\.,]/.test(str.charAt(i - 2)) && /[\d\.,]/.test(str.cha
rAt(i))) return false; | |
| 5697 } | |
| 5698 return /[~!#%&*)=+}\]\\|\"\.>,:;][({[<]|-[^\-?\.\u2010-\u201f\u2026]|\?[\w
~`@#$%\^&*(_=+{[|><]|\u2026[\w~`@#$%\^&*(_=+{[><]/.test(str.slice(i - 1, i + 1))
; | |
| 5699 }; | |
| 5700 | |
| 5701 var knownScrollbarWidth; | 6965 var knownScrollbarWidth; |
| 5702 function scrollbarWidth(measure) { | 6966 function scrollbarWidth(measure) { |
| 5703 if (knownScrollbarWidth != null) return knownScrollbarWidth; | 6967 if (knownScrollbarWidth != null) return knownScrollbarWidth; |
| 5704 var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: sc
roll"); | 6968 var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: sc
roll"); |
| 5705 removeChildrenAndAdd(measure, test); | 6969 removeChildrenAndAdd(measure, test); |
| 5706 if (test.offsetWidth) | 6970 if (test.offsetWidth) |
| 5707 knownScrollbarWidth = test.offsetHeight - test.clientHeight; | 6971 knownScrollbarWidth = test.offsetHeight - test.clientHeight; |
| 5708 return knownScrollbarWidth || 0; | 6972 return knownScrollbarWidth || 0; |
| 5709 } | 6973 } |
| 5710 | 6974 |
| 5711 var zwspSupported; | 6975 var zwspSupported; |
| 5712 function zeroWidthElement(measure) { | 6976 function zeroWidthElement(measure) { |
| 5713 if (zwspSupported == null) { | 6977 if (zwspSupported == null) { |
| 5714 var test = elt("span", "\u200b"); | 6978 var test = elt("span", "\u200b"); |
| 5715 removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("
x")])); | 6979 removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("
x")])); |
| 5716 if (measure.firstChild.offsetHeight != 0) | 6980 if (measure.firstChild.offsetHeight != 0) |
| 5717 zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_lt
8; | 6981 zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_up
to7; |
| 5718 } | 6982 } |
| 5719 if (zwspSupported) return elt("span", "\u200b"); | 6983 if (zwspSupported) return elt("span", "\u200b"); |
| 5720 else return elt("span", "\u00a0", null, "display: inline-block; width: 1px;
margin-right: -1px"); | 6984 else return elt("span", "\u00a0", null, "display: inline-block; width: 1px;
margin-right: -1px"); |
| 5721 } | 6985 } |
| 5722 | 6986 |
| 6987 // Feature-detect IE's crummy client rect reporting for bidi text |
| 6988 var badBidiRects; |
| 6989 function hasBadBidiRects(measure) { |
| 6990 if (badBidiRects != null) return badBidiRects; |
| 6991 var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"))
; |
| 6992 var r0 = range(txt, 0, 1).getBoundingClientRect(); |
| 6993 if (r0.left == r0.right) return false; |
| 6994 var r1 = range(txt, 1, 2).getBoundingClientRect(); |
| 6995 return badBidiRects = (r1.right - r0.right < 3); |
| 6996 } |
| 6997 |
| 5723 // See if "".split is the broken IE version, if so, provide an | 6998 // See if "".split is the broken IE version, if so, provide an |
| 5724 // alternative way to split lines. | 6999 // alternative way to split lines. |
| 5725 var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) { | 7000 var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? fun
ction(string) { |
| 5726 var pos = 0, result = [], l = string.length; | 7001 var pos = 0, result = [], l = string.length; |
| 5727 while (pos <= l) { | 7002 while (pos <= l) { |
| 5728 var nl = string.indexOf("\n", pos); | 7003 var nl = string.indexOf("\n", pos); |
| 5729 if (nl == -1) nl = string.length; | 7004 if (nl == -1) nl = string.length; |
| 5730 var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); | 7005 var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); |
| 5731 var rt = line.indexOf("\r"); | 7006 var rt = line.indexOf("\r"); |
| 5732 if (rt != -1) { | 7007 if (rt != -1) { |
| 5733 result.push(line.slice(0, rt)); | 7008 result.push(line.slice(0, rt)); |
| 5734 pos += rt + 1; | 7009 pos += rt + 1; |
| 5735 } else { | 7010 } else { |
| 5736 result.push(line); | 7011 result.push(line); |
| 5737 pos = nl + 1; | 7012 pos = nl + 1; |
| 5738 } | 7013 } |
| 5739 } | 7014 } |
| 5740 return result; | 7015 return result; |
| 5741 } : function(string){return string.split(/\r\n?|\n/);}; | 7016 } : function(string){return string.split(/\r\n?|\n/);}; |
| 5742 CodeMirror.splitLines = splitLines; | |
| 5743 | 7017 |
| 5744 var hasSelection = window.getSelection ? function(te) { | 7018 var hasSelection = window.getSelection ? function(te) { |
| 5745 try { return te.selectionStart != te.selectionEnd; } | 7019 try { return te.selectionStart != te.selectionEnd; } |
| 5746 catch(e) { return false; } | 7020 catch(e) { return false; } |
| 5747 } : function(te) { | 7021 } : function(te) { |
| 5748 try {var range = te.ownerDocument.selection.createRange();} | 7022 try {var range = te.ownerDocument.selection.createRange();} |
| 5749 catch(e) {} | 7023 catch(e) {} |
| 5750 if (!range || range.parentElement() != te) return false; | 7024 if (!range || range.parentElement() != te) return false; |
| 5751 return range.compareEndPoints("StartToEnd", range) != 0; | 7025 return range.compareEndPoints("StartToEnd", range) != 0; |
| 5752 }; | 7026 }; |
| 5753 | 7027 |
| 5754 var hasCopyEvent = (function() { | 7028 var hasCopyEvent = (function() { |
| 5755 var e = elt("div"); | 7029 var e = elt("div"); |
| 5756 if ("oncopy" in e) return true; | 7030 if ("oncopy" in e) return true; |
| 5757 e.setAttribute("oncopy", "return;"); | 7031 e.setAttribute("oncopy", "return;"); |
| 5758 return typeof e.oncopy == 'function'; | 7032 return typeof e.oncopy == "function"; |
| 5759 })(); | 7033 })(); |
| 5760 | 7034 |
| 5761 // KEY NAMING | 7035 // KEY NAMES |
| 5762 | 7036 |
| 5763 var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift"
, 17: "Ctrl", 18: "Alt", | 7037 var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift"
, 17: "Ctrl", 18: "Alt", |
| 5764 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "Page
Up", 34: "PageDown", 35: "End", | 7038 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "Page
Up", 34: "PageDown", 35: "End", |
| 5765 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44:
"PrintScrn", 45: "Insert", | 7039 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44:
"PrintScrn", 45: "Insert", |
| 5766 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod
", 107: "=", 109: "-", 127: "Delete", | 7040 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod
", 107: "=", 109: "-", 127: "Delete", |
| 5767 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 19
1: "/", 192: "`", 219: "[", 220: "\\", | 7041 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 19
1: "/", 192: "`", 219: "[", 220: "\\", |
| 5768 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left",
63235: "Right", 63272: "Delete", | 7042 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left",
63235: "Right", 63272: "Delete", |
| 5769 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown
", 63302: "Insert"}; | 7043 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown
", 63302: "Insert"}; |
| 5770 CodeMirror.keyNames = keyNames; | 7044 CodeMirror.keyNames = keyNames; |
| 5771 (function() { | 7045 (function() { |
| (...skipping 25 matching lines...) Expand all Loading... |
| 5797 | 7071 |
| 5798 function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(
order[0]) : 0; } | 7072 function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(
order[0]) : 0; } |
| 5799 function lineRight(line) { | 7073 function lineRight(line) { |
| 5800 var order = getOrder(line); | 7074 var order = getOrder(line); |
| 5801 if (!order) return line.text.length; | 7075 if (!order) return line.text.length; |
| 5802 return bidiRight(lst(order)); | 7076 return bidiRight(lst(order)); |
| 5803 } | 7077 } |
| 5804 | 7078 |
| 5805 function lineStart(cm, lineN) { | 7079 function lineStart(cm, lineN) { |
| 5806 var line = getLine(cm.doc, lineN); | 7080 var line = getLine(cm.doc, lineN); |
| 5807 var visual = visualLine(cm.doc, line); | 7081 var visual = visualLine(line); |
| 5808 if (visual != line) lineN = lineNo(visual); | 7082 if (visual != line) lineN = lineNo(visual); |
| 5809 var order = getOrder(visual); | 7083 var order = getOrder(visual); |
| 5810 var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visu
al); | 7084 var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visu
al); |
| 5811 return Pos(lineN, ch); | 7085 return Pos(lineN, ch); |
| 5812 } | 7086 } |
| 5813 function lineEnd(cm, lineN) { | 7087 function lineEnd(cm, lineN) { |
| 5814 var merged, line; | 7088 var merged, line = getLine(cm.doc, lineN); |
| 5815 while (merged = collapsedSpanAtEnd(line = getLine(cm.doc, lineN))) | 7089 while (merged = collapsedSpanAtEnd(line)) { |
| 5816 lineN = merged.find().to.line; | 7090 line = merged.find(1, true).line; |
| 7091 lineN = null; |
| 7092 } |
| 5817 var order = getOrder(line); | 7093 var order = getOrder(line); |
| 5818 var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : l
ineRight(line); | 7094 var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : l
ineRight(line); |
| 5819 return Pos(lineN, ch); | 7095 return Pos(lineN == null ? lineNo(line) : lineN, ch); |
| 5820 } | 7096 } |
| 5821 | 7097 |
| 5822 function compareBidiLevel(order, a, b) { | 7098 function compareBidiLevel(order, a, b) { |
| 5823 var linedir = order[0].level; | 7099 var linedir = order[0].level; |
| 5824 if (a == linedir) return true; | 7100 if (a == linedir) return true; |
| 5825 if (b == linedir) return false; | 7101 if (b == linedir) return false; |
| 5826 return a < b; | 7102 return a < b; |
| 5827 } | 7103 } |
| 5828 var bidiOther; | 7104 var bidiOther; |
| 5829 function getBidiPartAt(order, pos) { | 7105 function getBidiPartAt(order, pos) { |
| (...skipping 16 matching lines...) Expand all Loading... |
| 5846 return found; | 7122 return found; |
| 5847 } | 7123 } |
| 5848 | 7124 |
| 5849 function moveInLine(line, pos, dir, byUnit) { | 7125 function moveInLine(line, pos, dir, byUnit) { |
| 5850 if (!byUnit) return pos + dir; | 7126 if (!byUnit) return pos + dir; |
| 5851 do pos += dir; | 7127 do pos += dir; |
| 5852 while (pos > 0 && isExtendingChar(line.text.charAt(pos))); | 7128 while (pos > 0 && isExtendingChar(line.text.charAt(pos))); |
| 5853 return pos; | 7129 return pos; |
| 5854 } | 7130 } |
| 5855 | 7131 |
| 5856 // This is somewhat involved. It is needed in order to move | 7132 // This is needed in order to move 'visually' through bi-directional |
| 5857 // 'visually' through bi-directional text -- i.e., pressing left | 7133 // text -- i.e., pressing left should make the cursor go left, even |
| 5858 // should make the cursor go left, even when in RTL text. The | 7134 // when in RTL text. The tricky part is the 'jumps', where RTL and |
| 5859 // tricky part is the 'jumps', where RTL and LTR text touch each | 7135 // LTR text touch each other. This often requires the cursor offset |
| 5860 // other. This often requires the cursor offset to move more than | 7136 // to move more than one unit, in order to visually move one unit. |
| 5861 // one unit, in order to visually move one unit. | |
| 5862 function moveVisually(line, start, dir, byUnit) { | 7137 function moveVisually(line, start, dir, byUnit) { |
| 5863 var bidi = getOrder(line); | 7138 var bidi = getOrder(line); |
| 5864 if (!bidi) return moveLogically(line, start, dir, byUnit); | 7139 if (!bidi) return moveLogically(line, start, dir, byUnit); |
| 5865 var pos = getBidiPartAt(bidi, start), part = bidi[pos]; | 7140 var pos = getBidiPartAt(bidi, start), part = bidi[pos]; |
| 5866 var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit); | 7141 var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit); |
| 5867 | 7142 |
| 5868 for (;;) { | 7143 for (;;) { |
| 5869 if (target > part.from && target < part.to) return target; | 7144 if (target > part.from && target < part.to) return target; |
| 5870 if (target == part.from || target == part.to) { | 7145 if (target == part.from || target == part.to) { |
| 5871 if (getBidiPartAt(bidi, target) == pos) return target; | 7146 if (getBidiPartAt(bidi, target) == pos) return target; |
| (...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 5906 // s (B): Paragraph Separator | 7181 // s (B): Paragraph Separator |
| 5907 // t (S): Segment Separator | 7182 // t (S): Segment Separator |
| 5908 // w (WS): Whitespace | 7183 // w (WS): Whitespace |
| 5909 // N (ON): Other Neutrals | 7184 // N (ON): Other Neutrals |
| 5910 | 7185 |
| 5911 // Returns null if characters are ordered as they appear | 7186 // Returns null if characters are ordered as they appear |
| 5912 // (left-to-right), or an array of sections ({from, to, level} | 7187 // (left-to-right), or an array of sections ({from, to, level} |
| 5913 // objects) in the order in which they occur visually. | 7188 // objects) in the order in which they occur visually. |
| 5914 var bidiOrdering = (function() { | 7189 var bidiOrdering = (function() { |
| 5915 // Character types for codepoints 0 to 0xff | 7190 // Character types for codepoints 0 to 0xff |
| 5916 var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NN
NNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbb
bbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLL
LLLLLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLL"; | 7191 var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NN
NNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbb
bbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLL
LLLLLLLLLLLLLLLLLLLLLLLLLLLN"; |
| 5917 // Character types for codepoints 0x600 to 0x6ff | 7192 // Character types for codepoints 0x600 to 0x6ff |
| 5918 var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmm
mmmmmmmmmmmmmmmmNmmmmrrrrrrrrrrrrrrrrrr"; | 7193 var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmm
mmmmmmmmmmmmmmmmNmmmm"; |
| 5919 function charType(code) { | 7194 function charType(code) { |
| 5920 if (code <= 0xff) return lowTypes.charAt(code); | 7195 if (code <= 0xf7) return lowTypes.charAt(code); |
| 5921 else if (0x590 <= code && code <= 0x5f4) return "R"; | 7196 else if (0x590 <= code && code <= 0x5f4) return "R"; |
| 5922 else if (0x600 <= code && code <= 0x6ff) return arabicTypes.charAt(code -
0x600); | 7197 else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code -
0x600); |
| 5923 else if (0x700 <= code && code <= 0x8ac) return "r"; | 7198 else if (0x6ee <= code && code <= 0x8ac) return "r"; |
| 7199 else if (0x2000 <= code && code <= 0x200b) return "w"; |
| 7200 else if (code == 0x200c) return "b"; |
| 5924 else return "L"; | 7201 else return "L"; |
| 5925 } | 7202 } |
| 5926 | 7203 |
| 5927 var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; | 7204 var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; |
| 5928 var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, count
sAsNum = /[1n]/; | 7205 var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, count
sAsNum = /[1n]/; |
| 5929 // Browsers seem to always treat the boundaries of block elements as being L
. | 7206 // Browsers seem to always treat the boundaries of block elements as being L
. |
| 5930 var outerType = "L"; | 7207 var outerType = "L"; |
| 5931 | 7208 |
| 7209 function BidiSpan(level, from, to) { |
| 7210 this.level = level; |
| 7211 this.from = from; this.to = to; |
| 7212 } |
| 7213 |
| 5932 return function(str) { | 7214 return function(str) { |
| 5933 if (!bidiRE.test(str)) return false; | 7215 if (!bidiRE.test(str)) return false; |
| 5934 var len = str.length, types = []; | 7216 var len = str.length, types = []; |
| 5935 for (var i = 0, type; i < len; ++i) | 7217 for (var i = 0, type; i < len; ++i) |
| 5936 types.push(type = charType(str.charCodeAt(i))); | 7218 types.push(type = charType(str.charCodeAt(i))); |
| 5937 | 7219 |
| 5938 // W1. Examine each non-spacing mark (NSM) in the level run, and | 7220 // W1. Examine each non-spacing mark (NSM) in the level run, and |
| 5939 // change the type of the NSM to the type of the previous | 7221 // change the type of the NSM to the type of the previous |
| 5940 // character. If the NSM is at the start of the level run, it will | 7222 // character. If the NSM is at the start of the level run, it will |
| 5941 // get the type of sor. | 7223 // get the type of sor. |
| (...skipping 69 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 6011 // Here we depart from the documented algorithm, in order to avoid | 7293 // Here we depart from the documented algorithm, in order to avoid |
| 6012 // building up an actual levels array. Since there are only three | 7294 // building up an actual levels array. Since there are only three |
| 6013 // levels (0, 1, 2) in an implementation that doesn't take | 7295 // levels (0, 1, 2) in an implementation that doesn't take |
| 6014 // explicit embedding into account, we can build up the order on | 7296 // explicit embedding into account, we can build up the order on |
| 6015 // the fly, without following the level-based algorithm. | 7297 // the fly, without following the level-based algorithm. |
| 6016 var order = [], m; | 7298 var order = [], m; |
| 6017 for (var i = 0; i < len;) { | 7299 for (var i = 0; i < len;) { |
| 6018 if (countsAsLeft.test(types[i])) { | 7300 if (countsAsLeft.test(types[i])) { |
| 6019 var start = i; | 7301 var start = i; |
| 6020 for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} | 7302 for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} |
| 6021 order.push({from: start, to: i, level: 0}); | 7303 order.push(new BidiSpan(0, start, i)); |
| 6022 } else { | 7304 } else { |
| 6023 var pos = i, at = order.length; | 7305 var pos = i, at = order.length; |
| 6024 for (++i; i < len && types[i] != "L"; ++i) {} | 7306 for (++i; i < len && types[i] != "L"; ++i) {} |
| 6025 for (var j = pos; j < i;) { | 7307 for (var j = pos; j < i;) { |
| 6026 if (countsAsNum.test(types[j])) { | 7308 if (countsAsNum.test(types[j])) { |
| 6027 if (pos < j) order.splice(at, 0, {from: pos, to: j, level: 1}); | 7309 if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j)); |
| 6028 var nstart = j; | 7310 var nstart = j; |
| 6029 for (++j; j < i && countsAsNum.test(types[j]); ++j) {} | 7311 for (++j; j < i && countsAsNum.test(types[j]); ++j) {} |
| 6030 order.splice(at, 0, {from: nstart, to: j, level: 2}); | 7312 order.splice(at, 0, new BidiSpan(2, nstart, j)); |
| 6031 pos = j; | 7313 pos = j; |
| 6032 } else ++j; | 7314 } else ++j; |
| 6033 } | 7315 } |
| 6034 if (pos < i) order.splice(at, 0, {from: pos, to: i, level: 1}); | 7316 if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i)); |
| 6035 } | 7317 } |
| 6036 } | 7318 } |
| 6037 if (order[0].level == 1 && (m = str.match(/^\s+/))) { | 7319 if (order[0].level == 1 && (m = str.match(/^\s+/))) { |
| 6038 order[0].from = m[0].length; | 7320 order[0].from = m[0].length; |
| 6039 order.unshift({from: 0, to: m[0].length, level: 0}); | 7321 order.unshift(new BidiSpan(0, 0, m[0].length)); |
| 6040 } | 7322 } |
| 6041 if (lst(order).level == 1 && (m = str.match(/\s+$/))) { | 7323 if (lst(order).level == 1 && (m = str.match(/\s+$/))) { |
| 6042 lst(order).to -= m[0].length; | 7324 lst(order).to -= m[0].length; |
| 6043 order.push({from: len - m[0].length, to: len, level: 0}); | 7325 order.push(new BidiSpan(0, len - m[0].length, len)); |
| 6044 } | 7326 } |
| 6045 if (order[0].level != lst(order).level) | 7327 if (order[0].level != lst(order).level) |
| 6046 order.push({from: len, to: len, level: order[0].level}); | 7328 order.push(new BidiSpan(order[0].level, len, len)); |
| 6047 | 7329 |
| 6048 return order; | 7330 return order; |
| 6049 }; | 7331 }; |
| 6050 })(); | 7332 })(); |
| 6051 | 7333 |
| 6052 // THE END | 7334 // THE END |
| 6053 | 7335 |
| 6054 CodeMirror.version = "3.21.1"; | 7336 CodeMirror.version = "4.0.3"; |
| 6055 | 7337 |
| 6056 return CodeMirror; | 7338 return CodeMirror; |
| 6057 })(); | 7339 }); |
| OLD | NEW |