1
0

codemirror.js 126 KB

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