codemirror.js 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144
  1. // All functions that need access to the editor's state live inside
  2. // the CodeMirror function. Below that, at the bottom of the file,
  3. // some utilities are defined.
  4. // CodeMirror is the only global var we claim
  5. var CodeMirror = (function() {
  6. // This is the function that produces an editor instance. It's
  7. // closure is used to store the editor state.
  8. function CodeMirror(place, givenOptions) {
  9. // Determine effective options based on given values and defaults.
  10. var options = {}, defaults = CodeMirror.defaults;
  11. for (var opt in defaults)
  12. if (defaults.hasOwnProperty(opt))
  13. options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt];
  14. var targetDocument = options["document"];
  15. // The element in which the editor lives.
  16. var wrapper = targetDocument.createElement("div");
  17. wrapper.className = "CodeMirror";
  18. // This mess creates the base DOM structure for the editor.
  19. wrapper.innerHTML =
  20. '<div style="overflow: hidden; position: relative; width: 1px; height: 0px;">' + // Wraps and hides input textarea
  21. '<textarea style="position: absolute; width: 2px;" wrap="off"></textarea></div>' +
  22. '<div class="CodeMirror-scroll cm-s-' + options.theme + '">' +
  23. '<div style="position: relative">' + // Set to the height of the text, causes scrolling
  24. '<div style="position: absolute; height: 0; width: 0; overflow: hidden;"></div>' +
  25. '<div style="position: relative">' + // Moved around its parent to cover visible view
  26. '<div class="CodeMirror-gutter"><div class="CodeMirror-gutter-text"></div></div>' +
  27. // Provides positioning relative to (visible) text origin
  28. '<div class="CodeMirror-lines"><div style="position: relative">' +
  29. '<pre class="CodeMirror-cursor">&#160;</pre>' + // Absolutely positioned blinky cursor
  30. '<div></div>' + // This DIV contains the actual code
  31. '</div></div></div></div></div>';
  32. if (place.appendChild) place.appendChild(wrapper); else place(wrapper);
  33. // I've never seen more elegant code in my life.
  34. var inputDiv = wrapper.firstChild, input = inputDiv.firstChild,
  35. scroller = wrapper.lastChild, code = scroller.firstChild,
  36. measure = code.firstChild, mover = measure.nextSibling,
  37. gutter = mover.firstChild, gutterText = gutter.firstChild,
  38. lineSpace = gutter.nextSibling.firstChild,
  39. cursor = lineSpace.firstChild, lineDiv = cursor.nextSibling;
  40. if (options.tabindex != null) input.tabindex = options.tabindex;
  41. if (!options.gutter && !options.lineNumbers) gutter.style.display = "none";
  42. // Delayed object wrap timeouts, making sure only one is active. blinker holds an interval.
  43. var poll = new Delayed(), highlight = new Delayed(), blinker;
  44. // mode holds a mode API object. lines an array of Line objects
  45. // (see Line constructor), work an array of lines that should be
  46. // parsed, and history the undo history (instance of History
  47. // constructor).
  48. var mode, lines = [new Line("")], work, history = new History(), focused;
  49. loadMode();
  50. // The selection. These are always maintained to point at valid
  51. // positions. Inverted is used to remember that the user is
  52. // selecting bottom-to-top.
  53. var sel = {from: {line: 0, ch: 0}, to: {line: 0, ch: 0}, inverted: false};
  54. // Selection-related flags. shiftSelecting obviously tracks
  55. // whether the user is holding shift. reducedSelection is a hack
  56. // to get around the fact that we can't create inverted
  57. // selections. See below.
  58. var shiftSelecting, reducedSelection, lastDoubleClick;
  59. // Variables used by startOperation/endOperation to track what
  60. // happened during the operation.
  61. var updateInput, changes, textChanged, selectionChanged, leaveInputAlone;
  62. // Current visible range (may be bigger than the view window).
  63. var showingFrom = 0, showingTo = 0, lastHeight = 0, curKeyId = null;
  64. // editing will hold an object describing the things we put in the
  65. // textarea, to help figure out whether something changed.
  66. // bracketHighlighted is used to remember that a backet has been
  67. // marked.
  68. var editing, bracketHighlighted;
  69. // Tracks the maximum line length so that the horizontal scrollbar
  70. // can be kept static when scrolling.
  71. var maxLine = "", maxWidth;
  72. // Initialize the content.
  73. operation(function(){setValue(options.value || ""); updateInput = false;})();
  74. // Register our event handlers.
  75. connect(scroller, "mousedown", operation(onMouseDown));
  76. // Gecko browsers fire contextmenu *after* opening the menu, at
  77. // which point we can't mess with it anymore. Context menu is
  78. // handled in onMouseDown for Gecko.
  79. if (!gecko) connect(scroller, "contextmenu", onContextMenu);
  80. connect(code, "dblclick", operation(onDblClick));
  81. connect(scroller, "scroll", function() {updateDisplay([]); if (options.onScroll) options.onScroll(instance);});
  82. connect(window, "resize", function() {updateDisplay(true);});
  83. connect(input, "keyup", operation(onKeyUp));
  84. connect(input, "keydown", operation(onKeyDown));
  85. connect(input, "keypress", operation(onKeyPress));
  86. connect(input, "focus", onFocus);
  87. connect(input, "blur", onBlur);
  88. connect(scroller, "dragenter", e_stop);
  89. connect(scroller, "dragover", e_stop);
  90. connect(scroller, "drop", operation(onDrop));
  91. connect(scroller, "paste", function(){focusInput(); fastPoll();});
  92. connect(input, "paste", function(){fastPoll();});
  93. connect(input, "cut", function(){fastPoll();});
  94. // IE throws unspecified error in certain cases, when
  95. // trying to access activeElement before onload
  96. var hasFocus; try { hasFocus = (targetDocument.activeElement == input); } catch(e) { }
  97. if (hasFocus) setTimeout(onFocus, 20);
  98. else onBlur();
  99. function isLine(l) {return l >= 0 && l < lines.length;}
  100. // The instance object that we'll return. Mostly calls out to
  101. // local functions in the CodeMirror function. Some do some extra
  102. // range checking and/or clipping. operation is used to wrap the
  103. // call so that changes it makes are tracked, and the display is
  104. // updated afterwards.
  105. var instance = {
  106. getValue: getValue,
  107. setValue: operation(setValue),
  108. getSelection: getSelection,
  109. replaceSelection: operation(replaceSelection),
  110. focus: function(){focusInput(); onFocus(); fastPoll();},
  111. setOption: function(option, value) {
  112. options[option] = value;
  113. if (option == "lineNumbers" || option == "gutter") gutterChanged();
  114. else if (option == "mode" || option == "indentUnit") loadMode();
  115. else if (option == "readOnly" && value == "nocursor") input.blur();
  116. else if (option == "theme") scroller.className = scroller.className.replace(/cm-s-\w+/, "cm-s-" + value);
  117. },
  118. getOption: function(option) {return options[option];},
  119. undo: operation(undo),
  120. redo: operation(redo),
  121. indentLine: operation(function(n) {if (isLine(n)) indentLine(n, "smart");}),
  122. historySize: function() {return {undo: history.done.length, redo: history.undone.length};},
  123. matchBrackets: operation(function(){matchBrackets(true);}),
  124. getTokenAt: function(pos) {
  125. pos = clipPos(pos);
  126. return lines[pos.line].getTokenAt(mode, getStateBefore(pos.line), pos.ch);
  127. },
  128. getStateAfter: function(line) {
  129. line = clipLine(line == null ? lines.length - 1: line);
  130. return getStateBefore(line + 1);
  131. },
  132. cursorCoords: function(start){
  133. if (start == null) start = sel.inverted;
  134. return pageCoords(start ? sel.from : sel.to);
  135. },
  136. charCoords: function(pos){return pageCoords(clipPos(pos));},
  137. coordsChar: function(coords) {
  138. var off = eltOffset(lineSpace);
  139. var line = clipLine(Math.min(lines.length - 1, showingFrom + Math.floor((coords.y - off.top) / lineHeight())));
  140. return clipPos({line: line, ch: charFromX(clipLine(line), coords.x - off.left)});
  141. },
  142. getSearchCursor: function(query, pos, caseFold) {return new SearchCursor(query, pos, caseFold);},
  143. markText: operation(function(a, b, c){return operation(markText(a, b, c));}),
  144. setMarker: addGutterMarker,
  145. clearMarker: removeGutterMarker,
  146. setLineClass: operation(setLineClass),
  147. lineInfo: lineInfo,
  148. addWidget: function(pos, node, scroll, where) {
  149. pos = localCoords(clipPos(pos));
  150. var top = pos.yBot, left = pos.x;
  151. node.style.position = "absolute";
  152. code.appendChild(node);
  153. node.style.left = left + "px";
  154. if (where == "over") top = pos.y;
  155. else if (where == "near") {
  156. var vspace = Math.max(scroller.offsetHeight, lines.length * lineHeight()),
  157. hspace = Math.max(code.clientWidth, lineSpace.clientWidth) - paddingLeft();
  158. if (pos.yBot + node.offsetHeight > vspace && pos.y > node.offsetHeight)
  159. top = pos.y - node.offsetHeight;
  160. if (left + node.offsetWidth > hspace)
  161. left = hspace - node.offsetWidth;
  162. }
  163. node.style.top = (top + paddingTop()) + "px";
  164. node.style.left = (left + paddingLeft()) + "px";
  165. if (scroll)
  166. scrollIntoView(left, top, left + node.offsetWidth, top + node.offsetHeight);
  167. },
  168. lineCount: function() {return lines.length;},
  169. getCursor: function(start) {
  170. if (start == null) start = sel.inverted;
  171. return copyPos(start ? sel.from : sel.to);
  172. },
  173. somethingSelected: function() {return !posEq(sel.from, sel.to);},
  174. setCursor: operation(function(line, ch) {
  175. if (ch == null && typeof line.line == "number") setCursor(line.line, line.ch);
  176. else setCursor(line, ch);
  177. }),
  178. setSelection: operation(function(from, to) {setSelection(clipPos(from), clipPos(to || from));}),
  179. getLine: function(line) {if (isLine(line)) return lines[line].text;},
  180. setLine: operation(function(line, text) {
  181. if (isLine(line)) replaceRange(text, {line: line, ch: 0}, {line: line, ch: lines[line].text.length});
  182. }),
  183. removeLine: operation(function(line) {
  184. if (isLine(line)) replaceRange("", {line: line, ch: 0}, clipPos({line: line+1, ch: 0}));
  185. }),
  186. replaceRange: operation(replaceRange),
  187. getRange: function(from, to) {return getRange(clipPos(from), clipPos(to));},
  188. operation: function(f){return operation(f)();},
  189. refresh: function(){updateDisplay(true);},
  190. getInputField: function(){return input;},
  191. getWrapperElement: function(){return wrapper;},
  192. getScrollerElement: function(){return scroller;}
  193. };
  194. function setValue(code) {
  195. history = null;
  196. var top = {line: 0, ch: 0};
  197. updateLines(top, {line: lines.length - 1, ch: lines[lines.length-1].text.length},
  198. splitLines(code), top, top);
  199. history = new History();
  200. }
  201. function getValue(code) {
  202. var text = [];
  203. for (var i = 0, l = lines.length; i < l; ++i)
  204. text.push(lines[i].text);
  205. return text.join("\n");
  206. }
  207. function onMouseDown(e) {
  208. // Check whether this is a click in a widget
  209. for (var n = e_target(e); n != wrapper; n = n.parentNode)
  210. if (n.parentNode == code && n != mover) return;
  211. var ld = lastDoubleClick; lastDoubleClick = null;
  212. // First, see if this is a click in the gutter
  213. for (var n = e_target(e); n != wrapper; n = n.parentNode)
  214. if (n.parentNode == gutterText) {
  215. if (options.onGutterClick)
  216. options.onGutterClick(instance, indexOf(gutterText.childNodes, n) + showingFrom);
  217. return e_preventDefault(e);
  218. }
  219. var start = posFromMouse(e);
  220. switch (e_button(e)) {
  221. case 3:
  222. if (gecko && !mac) onContextMenu(e);
  223. return;
  224. case 2:
  225. if (start) setCursor(start.line, start.ch, true);
  226. return;
  227. }
  228. // For button 1, if it was clicked inside the editor
  229. // (posFromMouse returning non-null), we have to adjust the
  230. // selection.
  231. if (!start) {if (e_target(e) == scroller) e_preventDefault(e); return;}
  232. if (!focused) onFocus();
  233. e_preventDefault(e);
  234. if (ld && +new Date - ld < 400) return selectLine(start.line);
  235. setCursor(start.line, start.ch, true);
  236. var last = start, going;
  237. // And then we have to see if it's a drag event, in which case
  238. // the dragged-over text must be selected.
  239. function end() {
  240. focusInput();
  241. updateInput = true;
  242. move(); up();
  243. }
  244. function extend(e) {
  245. var cur = posFromMouse(e, true);
  246. if (cur && !posEq(cur, last)) {
  247. if (!focused) onFocus();
  248. last = cur;
  249. setSelectionUser(start, cur);
  250. updateInput = false;
  251. var visible = visibleLines();
  252. if (cur.line >= visible.to || cur.line < visible.from)
  253. going = setTimeout(operation(function(){extend(e);}), 150);
  254. }
  255. }
  256. var move = connect(targetDocument, "mousemove", operation(function(e) {
  257. clearTimeout(going);
  258. e_preventDefault(e);
  259. extend(e);
  260. }), true);
  261. var up = connect(targetDocument, "mouseup", operation(function(e) {
  262. clearTimeout(going);
  263. var cur = posFromMouse(e);
  264. if (cur) setSelectionUser(start, cur);
  265. e_preventDefault(e);
  266. end();
  267. }), true);
  268. }
  269. function onDblClick(e) {
  270. var pos = posFromMouse(e);
  271. if (!pos) return;
  272. selectWordAt(pos);
  273. e_preventDefault(e);
  274. lastDoubleClick = +new Date;
  275. }
  276. function onDrop(e) {
  277. e.preventDefault();
  278. var pos = posFromMouse(e, true), files = e.dataTransfer.files;
  279. if (!pos || options.readOnly) return;
  280. if (files && files.length && window.FileReader && window.File) {
  281. function loadFile(file, i) {
  282. var reader = new FileReader;
  283. reader.onload = function() {
  284. text[i] = reader.result;
  285. if (++read == n) replaceRange(text.join(""), clipPos(pos), clipPos(pos));
  286. };
  287. reader.readAsText(file);
  288. }
  289. var n = files.length, text = Array(n), read = 0;
  290. for (var i = 0; i < n; ++i) loadFile(files[i], i);
  291. }
  292. else {
  293. try {
  294. var text = e.dataTransfer.getData("Text");
  295. if (text) replaceRange(text, pos, pos);
  296. }
  297. catch(e){}
  298. }
  299. }
  300. function onKeyDown(e) {
  301. if (!focused) onFocus();
  302. var code = e.keyCode;
  303. // IE does strange things with escape.
  304. if (ie && code == 27) { e.returnValue = false; }
  305. // Tries to detect ctrl on non-mac, cmd on mac.
  306. var mod = (mac ? e.metaKey : e.ctrlKey) && !e.altKey, anyMod = e.ctrlKey || e.altKey || e.metaKey;
  307. if (code == 16 || e.shiftKey) shiftSelecting = shiftSelecting || (sel.inverted ? sel.to : sel.from);
  308. else shiftSelecting = null;
  309. // First give onKeyEvent option a chance to handle this.
  310. if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
  311. if (code == 33 || code == 34) {scrollPage(code == 34); return e_preventDefault(e);} // page up/down
  312. if (mod && ((code == 36 || code == 35) || // ctrl-home/end
  313. mac && (code == 38 || code == 40))) { // cmd-up/down
  314. scrollEnd(code == 36 || code == 38); return e_preventDefault(e);
  315. }
  316. if (mod && code == 65) {selectAll(); return e_preventDefault(e);} // ctrl-a
  317. if (!options.readOnly) {
  318. if (!anyMod && code == 13) {return;} // enter
  319. if (!anyMod && code == 9 && handleTab(e.shiftKey)) return e_preventDefault(e); // tab
  320. if (mod && code == 90) {undo(); return e_preventDefault(e);} // ctrl-z
  321. if (mod && ((e.shiftKey && code == 90) || code == 89)) {redo(); return e_preventDefault(e);} // ctrl-shift-z, ctrl-y
  322. }
  323. // Key id to use in the movementKeys map. We also pass it to
  324. // fastPoll in order to 'self learn'. We need this because
  325. // reducedSelection, the hack where we collapse the selection to
  326. // its start when it is inverted and a movement key is pressed
  327. // (and later restore it again), shouldn't be used for
  328. // non-movement keys.
  329. curKeyId = (mod ? "c" : "") + code;
  330. if (sel.inverted && movementKeys.hasOwnProperty(curKeyId)) {
  331. var range = selRange(input);
  332. if (range) {
  333. reducedSelection = {anchor: range.start};
  334. setSelRange(input, range.start, range.start);
  335. }
  336. }
  337. fastPoll(curKeyId);
  338. }
  339. function onKeyUp(e) {
  340. if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
  341. if (reducedSelection) {
  342. reducedSelection = null;
  343. updateInput = true;
  344. }
  345. if (e.keyCode == 16) shiftSelecting = null;
  346. }
  347. function onKeyPress(e) {
  348. if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
  349. if (options.electricChars && mode.electricChars) {
  350. var ch = String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode);
  351. if (mode.electricChars.indexOf(ch) > -1)
  352. setTimeout(operation(function() {indentLine(sel.to.line, "smart");}), 50);
  353. }
  354. var code = e.keyCode;
  355. // Re-stop tab and enter. Necessary on some browsers.
  356. if (code == 13) {if (!options.readOnly) handleEnter(); e_preventDefault(e);}
  357. else if (!e.ctrlKey && !e.altKey && !e.metaKey && code == 9 && options.tabMode != "default") e_preventDefault(e);
  358. else fastPoll(curKeyId);
  359. }
  360. function onFocus() {
  361. if (options.readOnly == "nocursor") return;
  362. if (!focused) {
  363. if (options.onFocus) options.onFocus(instance);
  364. focused = true;
  365. if (wrapper.className.search(/\bCodeMirror-focused\b/) == -1)
  366. wrapper.className += " CodeMirror-focused";
  367. if (!leaveInputAlone) prepareInput();
  368. }
  369. slowPoll();
  370. restartBlink();
  371. }
  372. function onBlur() {
  373. if (focused) {
  374. if (options.onBlur) options.onBlur(instance);
  375. focused = false;
  376. wrapper.className = wrapper.className.replace(" CodeMirror-focused", "");
  377. }
  378. clearInterval(blinker);
  379. setTimeout(function() {if (!focused) shiftSelecting = null;}, 150);
  380. }
  381. // Replace the range from from to to by the strings in newText.
  382. // Afterwards, set the selection to selFrom, selTo.
  383. function updateLines(from, to, newText, selFrom, selTo) {
  384. if (history) {
  385. var old = [];
  386. for (var i = from.line, e = to.line + 1; i < e; ++i) old.push(lines[i].text);
  387. history.addChange(from.line, newText.length, old);
  388. while (history.done.length > options.undoDepth) history.done.shift();
  389. }
  390. updateLinesNoUndo(from, to, newText, selFrom, selTo);
  391. }
  392. function unredoHelper(from, to) {
  393. var change = from.pop();
  394. if (change) {
  395. var replaced = [], end = change.start + change.added;
  396. for (var i = change.start; i < end; ++i) replaced.push(lines[i].text);
  397. to.push({start: change.start, added: change.old.length, old: replaced});
  398. var pos = clipPos({line: change.start + change.old.length - 1,
  399. ch: editEnd(replaced[replaced.length-1], change.old[change.old.length-1])});
  400. updateLinesNoUndo({line: change.start, ch: 0}, {line: end - 1, ch: lines[end-1].text.length}, change.old, pos, pos);
  401. updateInput = true;
  402. }
  403. }
  404. function undo() {unredoHelper(history.done, history.undone);}
  405. function redo() {unredoHelper(history.undone, history.done);}
  406. function updateLinesNoUndo(from, to, newText, selFrom, selTo) {
  407. var recomputeMaxLength = false, maxLineLength = maxLine.length;
  408. for (var i = from.line; i <= to.line; ++i) {
  409. if (lines[i].text.length == maxLineLength) {recomputeMaxLength = true; break;}
  410. }
  411. var nlines = to.line - from.line, firstLine = lines[from.line], lastLine = lines[to.line];
  412. // First adjust the line structure, taking some care to leave highlighting intact.
  413. if (firstLine == lastLine) {
  414. if (newText.length == 1)
  415. firstLine.replace(from.ch, to.ch, newText[0]);
  416. else {
  417. lastLine = firstLine.split(to.ch, newText[newText.length-1]);
  418. var spliceargs = [from.line + 1, nlines];
  419. firstLine.replace(from.ch, firstLine.text.length, newText[0]);
  420. for (var i = 1, e = newText.length - 1; i < e; ++i) spliceargs.push(new Line(newText[i]));
  421. spliceargs.push(lastLine);
  422. lines.splice.apply(lines, spliceargs);
  423. }
  424. }
  425. else if (newText.length == 1) {
  426. firstLine.replace(from.ch, firstLine.text.length, newText[0] + lastLine.text.slice(to.ch));
  427. lines.splice(from.line + 1, nlines);
  428. }
  429. else {
  430. var spliceargs = [from.line + 1, nlines - 1];
  431. firstLine.replace(from.ch, firstLine.text.length, newText[0]);
  432. lastLine.replace(0, to.ch, newText[newText.length-1]);
  433. for (var i = 1, e = newText.length - 1; i < e; ++i) spliceargs.push(new Line(newText[i]));
  434. lines.splice.apply(lines, spliceargs);
  435. }
  436. for (var i = from.line, e = i + newText.length; i < e; ++i) {
  437. var l = lines[i].text;
  438. if (l.length > maxLineLength) {
  439. maxLine = l; maxLineLength = l.length; maxWidth = null;
  440. recomputeMaxLength = false;
  441. }
  442. }
  443. if (recomputeMaxLength) {
  444. maxLineLength = 0; maxLine = ""; maxWidth = null;
  445. for (var i = 0, e = lines.length; i < e; ++i) {
  446. var l = lines[i].text;
  447. if (l.length > maxLineLength) {
  448. maxLineLength = l.length; maxLine = l;
  449. }
  450. }
  451. }
  452. // Add these lines to the work array, so that they will be
  453. // highlighted. Adjust work lines if lines were added/removed.
  454. var newWork = [], lendiff = newText.length - nlines - 1;
  455. for (var i = 0, l = work.length; i < l; ++i) {
  456. var task = work[i];
  457. if (task < from.line) newWork.push(task);
  458. else if (task > to.line) newWork.push(task + lendiff);
  459. }
  460. if (newText.length < 5) {
  461. highlightLines(from.line, from.line + newText.length);
  462. newWork.push(from.line + newText.length);
  463. } else {
  464. newWork.push(from.line);
  465. }
  466. work = newWork;
  467. startWorker(100);
  468. // Remember that these lines changed, for updating the display
  469. changes.push({from: from.line, to: to.line + 1, diff: lendiff});
  470. textChanged = {from: from, to: to, text: newText};
  471. // Update the selection
  472. function updateLine(n) {return n <= Math.min(to.line, to.line + lendiff) ? n : n + lendiff;}
  473. setSelection(selFrom, selTo, updateLine(sel.from.line), updateLine(sel.to.line));
  474. // Make sure the scroll-size div has the correct height.
  475. code.style.height = (lines.length * lineHeight() + 2 * paddingTop()) + "px";
  476. }
  477. function replaceRange(code, from, to) {
  478. from = clipPos(from);
  479. if (!to) to = from; else to = clipPos(to);
  480. code = splitLines(code);
  481. function adjustPos(pos) {
  482. if (posLess(pos, from)) return pos;
  483. if (!posLess(to, pos)) return end;
  484. var line = pos.line + code.length - (to.line - from.line) - 1;
  485. var ch = pos.ch;
  486. if (pos.line == to.line)
  487. ch += code[code.length-1].length - (to.ch - (to.line == from.line ? from.ch : 0));
  488. return {line: line, ch: ch};
  489. }
  490. var end;
  491. replaceRange1(code, from, to, function(end1) {
  492. end = end1;
  493. return {from: adjustPos(sel.from), to: adjustPos(sel.to)};
  494. });
  495. return end;
  496. }
  497. function replaceSelection(code, collapse) {
  498. replaceRange1(splitLines(code), sel.from, sel.to, function(end) {
  499. if (collapse == "end") return {from: end, to: end};
  500. else if (collapse == "start") return {from: sel.from, to: sel.from};
  501. else return {from: sel.from, to: end};
  502. });
  503. }
  504. function replaceRange1(code, from, to, computeSel) {
  505. var endch = code.length == 1 ? code[0].length + from.ch : code[code.length-1].length;
  506. var newSel = computeSel({line: from.line + code.length - 1, ch: endch});
  507. updateLines(from, to, code, newSel.from, newSel.to);
  508. }
  509. function getRange(from, to) {
  510. var l1 = from.line, l2 = to.line;
  511. if (l1 == l2) return lines[l1].text.slice(from.ch, to.ch);
  512. var code = [lines[l1].text.slice(from.ch)];
  513. for (var i = l1 + 1; i < l2; ++i) code.push(lines[i].text);
  514. code.push(lines[l2].text.slice(0, to.ch));
  515. return code.join("\n");
  516. }
  517. function getSelection() {
  518. return getRange(sel.from, sel.to);
  519. }
  520. var pollingFast = false; // Ensures slowPoll doesn't cancel fastPoll
  521. function slowPoll() {
  522. if (pollingFast) return;
  523. poll.set(2000, function() {
  524. startOperation();
  525. readInput();
  526. if (focused) slowPoll();
  527. endOperation();
  528. });
  529. }
  530. function fastPoll(keyId) {
  531. var missed = false;
  532. pollingFast = true;
  533. function p() {
  534. startOperation();
  535. var changed = readInput();
  536. if (changed == "moved" && keyId) movementKeys[keyId] = true;
  537. if (!changed && !missed) {missed = true; poll.set(80, p);}
  538. else {pollingFast = false; slowPoll();}
  539. endOperation();
  540. }
  541. poll.set(20, p);
  542. }
  543. // Inspects the textarea, compares its state (content, selection)
  544. // to the data in the editing variable, and updates the editor
  545. // content or cursor if something changed.
  546. function readInput() {
  547. if (leaveInputAlone || !focused) return;
  548. var changed = false, text = input.value, sr = selRange(input);
  549. if (!sr) return false;
  550. var changed = editing.text != text, rs = reducedSelection;
  551. var moved = changed || sr.start != editing.start || sr.end != (rs ? editing.start : editing.end);
  552. if (!moved && !rs) return false;
  553. if (changed) {
  554. shiftSelecting = reducedSelection = null;
  555. if (options.readOnly) {updateInput = true; return "changed";}
  556. }
  557. // Compute selection start and end based on start/end offsets in textarea
  558. function computeOffset(n, startLine) {
  559. var pos = 0;
  560. for (;;) {
  561. var found = text.indexOf("\n", pos);
  562. if (found == -1 || (text.charAt(found-1) == "\r" ? found - 1 : found) >= n)
  563. return {line: startLine, ch: n - pos};
  564. ++startLine;
  565. pos = found + 1;
  566. }
  567. }
  568. var from = computeOffset(sr.start, editing.from),
  569. to = computeOffset(sr.end, editing.from);
  570. // Here we have to take the reducedSelection hack into account,
  571. // so that you can, for example, press shift-up at the start of
  572. // your selection and have the right thing happen.
  573. if (rs) {
  574. var head = sr.start == rs.anchor ? to : from;
  575. var tail = shiftSelecting ? sel.to : sr.start == rs.anchor ? from : to;
  576. if (sel.inverted = posLess(head, tail)) { from = head; to = tail; }
  577. else { reducedSelection = null; from = tail; to = head; }
  578. }
  579. // In some cases (cursor on same line as before), we don't have
  580. // to update the textarea content at all.
  581. if (from.line == to.line && from.line == sel.from.line && from.line == sel.to.line && !shiftSelecting)
  582. updateInput = false;
  583. // Magic mess to extract precise edited range from the changed
  584. // string.
  585. if (changed) {
  586. var start = 0, end = text.length, len = Math.min(end, editing.text.length);
  587. var c, line = editing.from, nl = -1;
  588. while (start < len && (c = text.charAt(start)) == editing.text.charAt(start)) {
  589. ++start;
  590. if (c == "\n") {line++; nl = start;}
  591. }
  592. var ch = nl > -1 ? start - nl : start, endline = editing.to - 1, edend = editing.text.length;
  593. for (;;) {
  594. c = editing.text.charAt(edend);
  595. if (text.charAt(end) != c) {++end; ++edend; break;}
  596. if (c == "\n") endline--;
  597. if (edend <= start || end <= start) break;
  598. --end; --edend;
  599. }
  600. var nl = editing.text.lastIndexOf("\n", edend - 1), endch = nl == -1 ? edend : edend - nl - 1;
  601. updateLines({line: line, ch: ch}, {line: endline, ch: endch}, splitLines(text.slice(start, end)), from, to);
  602. if (line != endline || from.line != line) updateInput = true;
  603. }
  604. else setSelection(from, to);
  605. editing.text = text; editing.start = sr.start; editing.end = sr.end;
  606. return changed ? "changed" : moved ? "moved" : false;
  607. }
  608. // Set the textarea content and selection range to match the
  609. // editor state.
  610. function prepareInput() {
  611. var text = [];
  612. var from = Math.max(0, sel.from.line - 1), to = Math.min(lines.length, sel.to.line + 2);
  613. for (var i = from; i < to; ++i) text.push(lines[i].text);
  614. text = input.value = text.join(lineSep);
  615. var startch = sel.from.ch, endch = sel.to.ch;
  616. for (var i = from; i < sel.from.line; ++i)
  617. startch += lineSep.length + lines[i].text.length;
  618. for (var i = from; i < sel.to.line; ++i)
  619. endch += lineSep.length + lines[i].text.length;
  620. editing = {text: text, from: from, to: to, start: startch, end: endch};
  621. setSelRange(input, startch, reducedSelection ? startch : endch);
  622. }
  623. function focusInput() {
  624. if (options.readOnly != "nocursor") input.focus();
  625. }
  626. function scrollCursorIntoView() {
  627. var cursor = localCoords(sel.inverted ? sel.from : sel.to);
  628. return scrollIntoView(cursor.x, cursor.y, cursor.x, cursor.yBot);
  629. }
  630. function scrollIntoView(x1, y1, x2, y2) {
  631. var pl = paddingLeft(), pt = paddingTop(), lh = lineHeight();
  632. y1 += pt; y2 += pt; x1 += pl; x2 += pl;
  633. var screen = scroller.clientHeight, screentop = scroller.scrollTop, scrolled = false, result = true;
  634. if (y1 < screentop) {scroller.scrollTop = Math.max(0, y1 - 2*lh); scrolled = true;}
  635. else if (y2 > screentop + screen) {scroller.scrollTop = y2 + lh - screen; scrolled = true;}
  636. var screenw = scroller.clientWidth, screenleft = scroller.scrollLeft;
  637. if (x1 < screenleft) {
  638. if (x1 < 50) x1 = 0;
  639. scroller.scrollLeft = Math.max(0, x1 - 10);
  640. scrolled = true;
  641. }
  642. else if (x2 > screenw + screenleft) {
  643. scroller.scrollLeft = x2 + 10 - screenw;
  644. scrolled = true;
  645. if (x2 > code.clientWidth) result = false;
  646. }
  647. if (scrolled && options.onScroll) options.onScroll(instance);
  648. return result;
  649. }
  650. function visibleLines() {
  651. var lh = lineHeight(), top = scroller.scrollTop - paddingTop();
  652. return {from: Math.min(lines.length, Math.max(0, Math.floor(top / lh))),
  653. to: Math.min(lines.length, Math.ceil((top + scroller.clientHeight) / lh))};
  654. }
  655. // Uses a set of changes plus the current scroll position to
  656. // determine which DOM updates have to be made, and makes the
  657. // updates.
  658. function updateDisplay(changes) {
  659. if (!scroller.clientWidth) {
  660. showingFrom = showingTo = 0;
  661. return;
  662. }
  663. // First create a range of theoretically intact lines, and punch
  664. // holes in that using the change info.
  665. var intact = changes === true ? [] : [{from: showingFrom, to: showingTo, domStart: 0}];
  666. for (var i = 0, l = changes.length || 0; i < l; ++i) {
  667. var change = changes[i], intact2 = [], diff = change.diff || 0;
  668. for (var j = 0, l2 = intact.length; j < l2; ++j) {
  669. var range = intact[j];
  670. if (change.to <= range.from)
  671. intact2.push({from: range.from + diff, to: range.to + diff, domStart: range.domStart});
  672. else if (range.to <= change.from)
  673. intact2.push(range);
  674. else {
  675. if (change.from > range.from)
  676. intact2.push({from: range.from, to: change.from, domStart: range.domStart})
  677. if (change.to < range.to)
  678. intact2.push({from: change.to + diff, to: range.to + diff,
  679. domStart: range.domStart + (change.to - range.from)});
  680. }
  681. }
  682. intact = intact2;
  683. }
  684. // Then, determine which lines we'd want to see, and which
  685. // updates have to be made to get there.
  686. var visible = visibleLines();
  687. var from = Math.min(showingFrom, Math.max(visible.from - 3, 0)),
  688. to = Math.min(lines.length, Math.max(showingTo, visible.to + 3)),
  689. updates = [], domPos = 0, domEnd = showingTo - showingFrom, pos = from, changedLines = 0;
  690. for (var i = 0, l = intact.length; i < l; ++i) {
  691. var range = intact[i];
  692. if (range.to <= from) continue;
  693. if (range.from >= to) break;
  694. if (range.domStart > domPos || range.from > pos) {
  695. updates.push({from: pos, to: range.from, domSize: range.domStart - domPos, domStart: domPos});
  696. changedLines += range.from - pos;
  697. }
  698. pos = range.to;
  699. domPos = range.domStart + (range.to - range.from);
  700. }
  701. if (domPos != domEnd || pos != to) {
  702. changedLines += Math.abs(to - pos);
  703. updates.push({from: pos, to: to, domSize: domEnd - domPos, domStart: domPos});
  704. }
  705. if (!updates.length) return;
  706. lineDiv.style.display = "none";
  707. // If more than 30% of the screen needs update, just do a full
  708. // redraw (which is quicker than patching)
  709. if (changedLines > (visible.to - visible.from) * .3)
  710. refreshDisplay(from = Math.max(visible.from - 10, 0), to = Math.min(visible.to + 7, lines.length));
  711. // Otherwise, only update the stuff that needs updating.
  712. else
  713. patchDisplay(updates);
  714. lineDiv.style.display = "";
  715. // Position the mover div to align with the lines it's supposed
  716. // to be showing (which will cover the visible display)
  717. var different = from != showingFrom || to != showingTo || lastHeight != scroller.clientHeight;
  718. showingFrom = from; showingTo = to;
  719. mover.style.top = (from * lineHeight()) + "px";
  720. if (different) {
  721. lastHeight = scroller.clientHeight;
  722. code.style.height = (lines.length * lineHeight() + 2 * paddingTop()) + "px";
  723. updateGutter();
  724. }
  725. if (maxWidth == null) maxWidth = stringWidth(maxLine);
  726. if (maxWidth > scroller.clientWidth) {
  727. lineSpace.style.width = maxWidth + "px";
  728. // Needed to prevent odd wrapping/hiding of widgets placed in here.
  729. code.style.width = "";
  730. code.style.width = scroller.scrollWidth + "px";
  731. } else {
  732. lineSpace.style.width = code.style.width = "";
  733. }
  734. // Since this is all rather error prone, it is honoured with the
  735. // only assertion in the whole file.
  736. if (lineDiv.childNodes.length != showingTo - showingFrom)
  737. throw new Error("BAD PATCH! " + JSON.stringify(updates) + " size=" + (showingTo - showingFrom) +
  738. " nodes=" + lineDiv.childNodes.length);
  739. updateCursor();
  740. }
  741. function refreshDisplay(from, to) {
  742. var html = [], start = {line: from, ch: 0}, inSel = posLess(sel.from, start) && !posLess(sel.to, start);
  743. for (var i = from; i < to; ++i) {
  744. var ch1 = null, ch2 = null;
  745. if (inSel) {
  746. ch1 = 0;
  747. if (sel.to.line == i) {inSel = false; ch2 = sel.to.ch;}
  748. }
  749. else if (sel.from.line == i) {
  750. if (sel.to.line == i) {ch1 = sel.from.ch; ch2 = sel.to.ch;}
  751. else {inSel = true; ch1 = sel.from.ch;}
  752. }
  753. html.push(lines[i].getHTML(ch1, ch2, true));
  754. }
  755. lineDiv.innerHTML = html.join("");
  756. }
  757. function patchDisplay(updates) {
  758. // Slightly different algorithm for IE (badInnerHTML), since
  759. // there .innerHTML on PRE nodes is dumb, and discards
  760. // whitespace.
  761. var sfrom = sel.from.line, sto = sel.to.line, off = 0,
  762. scratch = badInnerHTML && targetDocument.createElement("div");
  763. for (var i = 0, e = updates.length; i < e; ++i) {
  764. var rec = updates[i];
  765. var extra = (rec.to - rec.from) - rec.domSize;
  766. var nodeAfter = lineDiv.childNodes[rec.domStart + rec.domSize + off] || null;
  767. if (badInnerHTML)
  768. for (var j = Math.max(-extra, rec.domSize); j > 0; --j)
  769. lineDiv.removeChild(nodeAfter ? nodeAfter.previousSibling : lineDiv.lastChild);
  770. else if (extra) {
  771. for (var j = Math.max(0, extra); j > 0; --j)
  772. lineDiv.insertBefore(targetDocument.createElement("pre"), nodeAfter);
  773. for (var j = Math.max(0, -extra); j > 0; --j)
  774. lineDiv.removeChild(nodeAfter ? nodeAfter.previousSibling : lineDiv.lastChild);
  775. }
  776. var node = lineDiv.childNodes[rec.domStart + off], inSel = sfrom < rec.from && sto >= rec.from;
  777. for (var j = rec.from; j < rec.to; ++j) {
  778. var ch1 = null, ch2 = null;
  779. if (inSel) {
  780. ch1 = 0;
  781. if (sto == j) {inSel = false; ch2 = sel.to.ch;}
  782. }
  783. else if (sfrom == j) {
  784. if (sto == j) {ch1 = sel.from.ch; ch2 = sel.to.ch;}
  785. else {inSel = true; ch1 = sel.from.ch;}
  786. }
  787. if (badInnerHTML) {
  788. scratch.innerHTML = lines[j].getHTML(ch1, ch2, true);
  789. lineDiv.insertBefore(scratch.firstChild, nodeAfter);
  790. }
  791. else {
  792. node.innerHTML = lines[j].getHTML(ch1, ch2, false);
  793. node.className = lines[j].className || "";
  794. node = node.nextSibling;
  795. }
  796. }
  797. off += extra;
  798. }
  799. }
  800. function updateGutter() {
  801. if (!options.gutter && !options.lineNumbers) return;
  802. var hText = mover.offsetHeight, hEditor = scroller.clientHeight;
  803. gutter.style.height = (hText - hEditor < 2 ? hEditor : hText) + "px";
  804. var html = [];
  805. for (var i = showingFrom; i < Math.max(showingTo, showingFrom + 1); ++i) {
  806. var marker = lines[i].gutterMarker;
  807. var text = options.lineNumbers ? i + options.firstLineNumber : null;
  808. if (marker && marker.text)
  809. text = marker.text.replace("%N%", text != null ? text : "");
  810. else if (text == null)
  811. text = "\u00a0";
  812. html.push((marker && marker.style ? '<pre class="' + marker.style + '">' : "<pre>"), text, "</pre>");
  813. }
  814. gutter.style.display = "none";
  815. gutterText.innerHTML = html.join("");
  816. var minwidth = String(lines.length).length, firstNode = gutterText.firstChild, val = eltText(firstNode), pad = "";
  817. while (val.length + pad.length < minwidth) pad += "\u00a0";
  818. if (pad) firstNode.insertBefore(targetDocument.createTextNode(pad), firstNode.firstChild);
  819. gutter.style.display = "";
  820. lineSpace.style.marginLeft = gutter.offsetWidth + "px";
  821. }
  822. function updateCursor() {
  823. var head = sel.inverted ? sel.from : sel.to, lh = lineHeight();
  824. var x = charX(head.line, head.ch) + "px", y = (head.line - showingFrom) * lh + "px";
  825. inputDiv.style.top = (head.line * lh - scroller.scrollTop) + "px";
  826. if (posEq(sel.from, sel.to)) {
  827. cursor.style.top = y; cursor.style.left = x;
  828. cursor.style.display = "";
  829. }
  830. else cursor.style.display = "none";
  831. }
  832. function setSelectionUser(from, to) {
  833. var sh = shiftSelecting && clipPos(shiftSelecting);
  834. if (sh) {
  835. if (posLess(sh, from)) from = sh;
  836. else if (posLess(to, sh)) to = sh;
  837. }
  838. setSelection(from, to);
  839. }
  840. // Update the selection. Last two args are only used by
  841. // updateLines, since they have to be expressed in the line
  842. // numbers before the update.
  843. function setSelection(from, to, oldFrom, oldTo) {
  844. if (posEq(sel.from, from) && posEq(sel.to, to)) return;
  845. if (posLess(to, from)) {var tmp = to; to = from; from = tmp;}
  846. if (posEq(from, to)) sel.inverted = false;
  847. else if (posEq(from, sel.to)) sel.inverted = false;
  848. else if (posEq(to, sel.from)) sel.inverted = true;
  849. // Some ugly logic used to only mark the lines that actually did
  850. // see a change in selection as changed, rather than the whole
  851. // selected range.
  852. if (oldFrom == null) {oldFrom = sel.from.line; oldTo = sel.to.line;}
  853. if (posEq(from, to)) {
  854. if (!posEq(sel.from, sel.to))
  855. changes.push({from: oldFrom, to: oldTo + 1});
  856. }
  857. else if (posEq(sel.from, sel.to)) {
  858. changes.push({from: from.line, to: to.line + 1});
  859. }
  860. else {
  861. if (!posEq(from, sel.from)) {
  862. if (from.line < oldFrom)
  863. changes.push({from: from.line, to: Math.min(to.line, oldFrom) + 1});
  864. else
  865. changes.push({from: oldFrom, to: Math.min(oldTo, from.line) + 1});
  866. }
  867. if (!posEq(to, sel.to)) {
  868. if (to.line < oldTo)
  869. changes.push({from: Math.max(oldFrom, from.line), to: oldTo + 1});
  870. else
  871. changes.push({from: Math.max(from.line, oldTo), to: to.line + 1});
  872. }
  873. }
  874. sel.from = from; sel.to = to;
  875. selectionChanged = true;
  876. }
  877. function setCursor(line, ch, user) {
  878. var pos = clipPos({line: line, ch: ch || 0});
  879. (user ? setSelectionUser : setSelection)(pos, pos);
  880. }
  881. function clipLine(n) {return Math.max(0, Math.min(n, lines.length-1));}
  882. function clipPos(pos) {
  883. if (pos.line < 0) return {line: 0, ch: 0};
  884. if (pos.line >= lines.length) return {line: lines.length-1, ch: lines[lines.length-1].text.length};
  885. var ch = pos.ch, linelen = lines[pos.line].text.length;
  886. if (ch == null || ch > linelen) return {line: pos.line, ch: linelen};
  887. else if (ch < 0) return {line: pos.line, ch: 0};
  888. else return pos;
  889. }
  890. function scrollPage(down) {
  891. var linesPerPage = Math.floor(scroller.clientHeight / lineHeight()), head = sel.inverted ? sel.from : sel.to;
  892. setCursor(head.line + (Math.max(linesPerPage - 1, 1) * (down ? 1 : -1)), head.ch, true);
  893. }
  894. function scrollEnd(top) {
  895. var pos = top ? {line: 0, ch: 0} : {line: lines.length - 1, ch: lines[lines.length-1].text.length};
  896. setSelectionUser(pos, pos);
  897. }
  898. function selectAll() {
  899. var endLine = lines.length - 1;
  900. setSelection({line: 0, ch: 0}, {line: endLine, ch: lines[endLine].text.length});
  901. }
  902. function selectWordAt(pos) {
  903. var line = lines[pos.line].text;
  904. var start = pos.ch, end = pos.ch;
  905. while (start > 0 && /\w/.test(line.charAt(start - 1))) --start;
  906. while (end < line.length && /\w/.test(line.charAt(end))) ++end;
  907. setSelectionUser({line: pos.line, ch: start}, {line: pos.line, ch: end});
  908. }
  909. function selectLine(line) {
  910. setSelectionUser({line: line, ch: 0}, {line: line, ch: lines[line].text.length});
  911. }
  912. function handleEnter() {
  913. replaceSelection("\n", "end");
  914. if (options.enterMode != "flat")
  915. indentLine(sel.from.line, options.enterMode == "keep" ? "prev" : "smart");
  916. }
  917. function handleTab(shift) {
  918. function indentSelected(mode) {
  919. if (posEq(sel.from, sel.to)) return indentLine(sel.from.line, mode);
  920. var e = sel.to.line - (sel.to.ch ? 0 : 1);
  921. for (var i = sel.from.line; i <= e; ++i) indentLine(i, mode);
  922. }
  923. shiftSelecting = null;
  924. switch (options.tabMode) {
  925. case "default":
  926. return false;
  927. case "indent":
  928. indentSelected("smart");
  929. break;
  930. case "classic":
  931. if (posEq(sel.from, sel.to)) {
  932. if (shift) indentLine(sel.from.line, "smart");
  933. else replaceSelection("\t", "end");
  934. break;
  935. }
  936. case "shift":
  937. indentSelected(shift ? "subtract" : "add");
  938. break;
  939. }
  940. return true;
  941. }
  942. function indentLine(n, how) {
  943. if (how == "smart") {
  944. if (!mode.indent) how = "prev";
  945. else var state = getStateBefore(n);
  946. }
  947. var line = lines[n], curSpace = line.indentation(), curSpaceString = line.text.match(/^\s*/)[0], indentation;
  948. if (how == "prev") {
  949. if (n) indentation = lines[n-1].indentation();
  950. else indentation = 0;
  951. }
  952. else if (how == "smart") indentation = mode.indent(state, line.text.slice(curSpaceString.length));
  953. else if (how == "add") indentation = curSpace + options.indentUnit;
  954. else if (how == "subtract") indentation = curSpace - options.indentUnit;
  955. indentation = Math.max(0, indentation);
  956. var diff = indentation - curSpace;
  957. if (!diff) {
  958. if (sel.from.line != n && sel.to.line != n) return;
  959. var indentString = curSpaceString;
  960. }
  961. else {
  962. var indentString = "", pos = 0;
  963. if (options.indentWithTabs)
  964. for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
  965. while (pos < indentation) {++pos; indentString += " ";}
  966. }
  967. replaceRange(indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length});
  968. }
  969. function loadMode() {
  970. mode = CodeMirror.getMode(options, options.mode);
  971. for (var i = 0, l = lines.length; i < l; ++i)
  972. lines[i].stateAfter = null;
  973. work = [0];
  974. startWorker();
  975. }
  976. function gutterChanged() {
  977. var visible = options.gutter || options.lineNumbers;
  978. gutter.style.display = visible ? "" : "none";
  979. if (visible) updateGutter();
  980. else lineDiv.parentNode.style.marginLeft = 0;
  981. }
  982. function markText(from, to, className) {
  983. from = clipPos(from); to = clipPos(to);
  984. var accum = [];
  985. function add(line, from, to, className) {
  986. var line = lines[line], mark = line.addMark(from, to, className);
  987. mark.line = line;
  988. accum.push(mark);
  989. }
  990. if (from.line == to.line) add(from.line, from.ch, to.ch, className);
  991. else {
  992. add(from.line, from.ch, null, className);
  993. for (var i = from.line + 1, e = to.line; i < e; ++i)
  994. add(i, 0, null, className);
  995. add(to.line, 0, to.ch, className);
  996. }
  997. changes.push({from: from.line, to: to.line + 1});
  998. return function() {
  999. var start, end;
  1000. for (var i = 0; i < accum.length; ++i) {
  1001. var mark = accum[i], found = indexOf(lines, mark.line);
  1002. mark.line.removeMark(mark);
  1003. if (found > -1) {
  1004. if (start == null) start = found;
  1005. end = found;
  1006. }
  1007. }
  1008. if (start != null) changes.push({from: start, to: end + 1});
  1009. };
  1010. }
  1011. function addGutterMarker(line, text, className) {
  1012. if (typeof line == "number") line = lines[clipLine(line)];
  1013. line.gutterMarker = {text: text, style: className};
  1014. updateGutter();
  1015. return line;
  1016. }
  1017. function removeGutterMarker(line) {
  1018. if (typeof line == "number") line = lines[clipLine(line)];
  1019. line.gutterMarker = null;
  1020. updateGutter();
  1021. }
  1022. function setLineClass(line, className) {
  1023. if (typeof line == "number") {
  1024. var no = line;
  1025. line = lines[clipLine(line)];
  1026. }
  1027. else {
  1028. var no = indexOf(lines, line);
  1029. if (no == -1) return null;
  1030. }
  1031. if (line.className != className) {
  1032. line.className = className;
  1033. changes.push({from: no, to: no + 1});
  1034. }
  1035. return line;
  1036. }
  1037. function lineInfo(line) {
  1038. if (typeof line == "number") {
  1039. var n = line;
  1040. line = lines[line];
  1041. if (!line) return null;
  1042. }
  1043. else {
  1044. var n = indexOf(lines, line);
  1045. if (n == -1) return null;
  1046. }
  1047. var marker = line.gutterMarker;
  1048. return {line: n, text: line.text, markerText: marker && marker.text, markerClass: marker && marker.style};
  1049. }
  1050. function stringWidth(str) {
  1051. measure.innerHTML = "<pre><span>x</span></pre>";
  1052. measure.firstChild.firstChild.firstChild.nodeValue = str;
  1053. return measure.firstChild.firstChild.offsetWidth || 10;
  1054. }
  1055. // These are used to go from pixel positions to character
  1056. // positions, taking varying character widths into account.
  1057. function charX(line, pos) {
  1058. if (pos == 0) return 0;
  1059. measure.innerHTML = "<pre><span>" + lines[line].getHTML(null, null, false, pos) + "</span></pre>";
  1060. return measure.firstChild.firstChild.offsetWidth;
  1061. }
  1062. function charFromX(line, x) {
  1063. if (x <= 0) return 0;
  1064. var lineObj = lines[line], text = lineObj.text;
  1065. function getX(len) {
  1066. measure.innerHTML = "<pre><span>" + lineObj.getHTML(null, null, false, len) + "</span></pre>";
  1067. return measure.firstChild.firstChild.offsetWidth;
  1068. }
  1069. var from = 0, fromX = 0, to = text.length, toX;
  1070. // Guess a suitable upper bound for our search.
  1071. var estimated = Math.min(to, Math.ceil(x / stringWidth("x")));
  1072. for (;;) {
  1073. var estX = getX(estimated);
  1074. if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));
  1075. else {toX = estX; to = estimated; break;}
  1076. }
  1077. if (x > toX) return to;
  1078. // Try to guess a suitable lower bound as well.
  1079. estimated = Math.floor(to * 0.8); estX = getX(estimated);
  1080. if (estX < x) {from = estimated; fromX = estX;}
  1081. // Do a binary search between these bounds.
  1082. for (;;) {
  1083. if (to - from <= 1) return (toX - x > x - fromX) ? from : to;
  1084. var middle = Math.ceil((from + to) / 2), middleX = getX(middle);
  1085. if (middleX > x) {to = middle; toX = middleX;}
  1086. else {from = middle; fromX = middleX;}
  1087. }
  1088. }
  1089. function localCoords(pos, inLineWrap) {
  1090. var lh = lineHeight(), line = pos.line - (inLineWrap ? showingFrom : 0);
  1091. return {x: charX(pos.line, pos.ch), y: line * lh, yBot: (line + 1) * lh};
  1092. }
  1093. function pageCoords(pos) {
  1094. var local = localCoords(pos, true), off = eltOffset(lineSpace);
  1095. return {x: off.left + local.x, y: off.top + local.y, yBot: off.top + local.yBot};
  1096. }
  1097. function lineHeight() {
  1098. var nlines = lineDiv.childNodes.length;
  1099. if (nlines) return (lineDiv.offsetHeight / nlines) || 1;
  1100. measure.innerHTML = "<pre>x</pre>";
  1101. return measure.firstChild.offsetHeight || 1;
  1102. }
  1103. function paddingTop() {return lineSpace.offsetTop;}
  1104. function paddingLeft() {return lineSpace.offsetLeft;}
  1105. function posFromMouse(e, liberal) {
  1106. var offW = eltOffset(scroller, true), x, y;
  1107. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  1108. try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
  1109. // This is a mess of a heuristic to try and determine whether a
  1110. // scroll-bar was clicked or not, and to return null if one was
  1111. // (and !liberal).
  1112. if (!liberal && (x - offW.left > scroller.clientWidth || y - offW.top > scroller.clientHeight))
  1113. return null;
  1114. var offL = eltOffset(lineSpace, true);
  1115. var line = showingFrom + Math.floor((y - offL.top) / lineHeight());
  1116. return clipPos({line: line, ch: charFromX(clipLine(line), x - offL.left)});
  1117. }
  1118. function onContextMenu(e) {
  1119. var pos = posFromMouse(e);
  1120. if (!pos || window.opera) return; // Opera is difficult.
  1121. if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
  1122. operation(setCursor)(pos.line, pos.ch);
  1123. var oldCSS = input.style.cssText;
  1124. inputDiv.style.position = "absolute";
  1125. input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e_pageY(e) - 1) +
  1126. "px; left: " + (e_pageX(e) - 1) + "px; z-index: 1000; background: white; " +
  1127. "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  1128. leaveInputAlone = true;
  1129. var val = input.value = getSelection();
  1130. focusInput();
  1131. setSelRange(input, 0, input.value.length);
  1132. function rehide() {
  1133. var newVal = splitLines(input.value).join("\n");
  1134. if (newVal != val) operation(replaceSelection)(newVal, "end");
  1135. inputDiv.style.position = "relative";
  1136. input.style.cssText = oldCSS;
  1137. leaveInputAlone = false;
  1138. prepareInput();
  1139. slowPoll();
  1140. }
  1141. if (gecko) {
  1142. e_stop(e);
  1143. var mouseup = connect(window, "mouseup", function() {
  1144. mouseup();
  1145. setTimeout(rehide, 20);
  1146. }, true);
  1147. }
  1148. else {
  1149. setTimeout(rehide, 50);
  1150. }
  1151. }
  1152. // Cursor-blinking
  1153. function restartBlink() {
  1154. clearInterval(blinker);
  1155. var on = true;
  1156. cursor.style.visibility = "";
  1157. blinker = setInterval(function() {
  1158. cursor.style.visibility = (on = !on) ? "" : "hidden";
  1159. }, 650);
  1160. }
  1161. var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
  1162. function matchBrackets(autoclear) {
  1163. var head = sel.inverted ? sel.from : sel.to, line = lines[head.line], pos = head.ch - 1;
  1164. var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
  1165. if (!match) return;
  1166. var ch = match.charAt(0), forward = match.charAt(1) == ">", d = forward ? 1 : -1, st = line.styles;
  1167. for (var off = pos + 1, i = 0, e = st.length; i < e; i+=2)
  1168. if ((off -= st[i].length) <= 0) {var style = st[i+1]; break;}
  1169. var stack = [line.text.charAt(pos)], re = /[(){}[\]]/;
  1170. function scan(line, from, to) {
  1171. if (!line.text) return;
  1172. var st = line.styles, pos = forward ? 0 : line.text.length - 1, cur;
  1173. for (var i = forward ? 0 : st.length - 2, e = forward ? st.length : -2; i != e; i += 2*d) {
  1174. var text = st[i];
  1175. if (st[i+1] != null && st[i+1] != style) {pos += d * text.length; continue;}
  1176. for (var j = forward ? 0 : text.length - 1, te = forward ? text.length : -1; j != te; j += d, pos+=d) {
  1177. if (pos >= from && pos < to && re.test(cur = text.charAt(j))) {
  1178. var match = matching[cur];
  1179. if (match.charAt(1) == ">" == forward) stack.push(cur);
  1180. else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false};
  1181. else if (!stack.length) return {pos: pos, match: true};
  1182. }
  1183. }
  1184. }
  1185. }
  1186. for (var i = head.line, e = forward ? Math.min(i + 100, lines.length) : Math.max(-1, i - 100); i != e; i+=d) {
  1187. var line = lines[i], first = i == head.line;
  1188. var found = scan(line, first && forward ? pos + 1 : 0, first && !forward ? pos : line.text.length);
  1189. if (found) break;
  1190. }
  1191. if (!found) found = {pos: null, match: false};
  1192. var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
  1193. var one = markText({line: head.line, ch: pos}, {line: head.line, ch: pos+1}, style),
  1194. two = found.pos != null
  1195. ? markText({line: i, ch: found.pos}, {line: i, ch: found.pos + 1}, style)
  1196. : function() {};
  1197. var clear = operation(function(){one(); two();});
  1198. if (autoclear) setTimeout(clear, 800);
  1199. else bracketHighlighted = clear;
  1200. }
  1201. // Finds the line to start with when starting a parse. Tries to
  1202. // find a line with a stateAfter, so that it can start with a
  1203. // valid state. If that fails, it returns the line with the
  1204. // smallest indentation, which tends to need the least context to
  1205. // parse correctly.
  1206. function findStartLine(n) {
  1207. var minindent, minline;
  1208. for (var search = n, lim = n - 40; search > lim; --search) {
  1209. if (search == 0) return 0;
  1210. var line = lines[search-1];
  1211. if (line.stateAfter) return search;
  1212. var indented = line.indentation();
  1213. if (minline == null || minindent > indented) {
  1214. minline = search;
  1215. minindent = indented;
  1216. }
  1217. }
  1218. return minline;
  1219. }
  1220. function getStateBefore(n) {
  1221. var start = findStartLine(n), state = start && lines[start-1].stateAfter;
  1222. if (!state) state = startState(mode);
  1223. else state = copyState(mode, state);
  1224. for (var i = start; i < n; ++i) {
  1225. var line = lines[i];
  1226. line.highlight(mode, state);
  1227. line.stateAfter = copyState(mode, state);
  1228. }
  1229. if (n < lines.length && !lines[n].stateAfter) work.push(n);
  1230. return state;
  1231. }
  1232. function highlightLines(start, end) {
  1233. var state = getStateBefore(start);
  1234. for (var i = start; i < end; ++i) {
  1235. var line = lines[i];
  1236. line.highlight(mode, state);
  1237. line.stateAfter = copyState(mode, state);
  1238. }
  1239. }
  1240. function highlightWorker() {
  1241. var end = +new Date + options.workTime;
  1242. var foundWork = work.length;
  1243. while (work.length) {
  1244. if (!lines[showingFrom].stateAfter) var task = showingFrom;
  1245. else var task = work.pop();
  1246. if (task >= lines.length) continue;
  1247. var start = findStartLine(task), state = start && lines[start-1].stateAfter;
  1248. if (state) state = copyState(mode, state);
  1249. else state = startState(mode);
  1250. var unchanged = 0, compare = mode.compareStates;
  1251. for (var i = start, l = lines.length; i < l; ++i) {
  1252. var line = lines[i], hadState = line.stateAfter;
  1253. if (+new Date > end) {
  1254. work.push(i);
  1255. startWorker(options.workDelay);
  1256. changes.push({from: task, to: i + 1});
  1257. return;
  1258. }
  1259. var changed = line.highlight(mode, state);
  1260. line.stateAfter = copyState(mode, state);
  1261. if (compare) {
  1262. if (hadState && compare(hadState, state)) break;
  1263. } else {
  1264. if (changed || !hadState) unchanged = 0;
  1265. else if (++unchanged > 3) break;
  1266. }
  1267. }
  1268. changes.push({from: task, to: i + 1});
  1269. }
  1270. if (foundWork && options.onHighlightComplete)
  1271. options.onHighlightComplete(instance);
  1272. }
  1273. function startWorker(time) {
  1274. if (!work.length) return;
  1275. highlight.set(time, operation(highlightWorker));
  1276. }
  1277. // Operations are used to wrap changes in such a way that each
  1278. // change won't have to update the cursor and display (which would
  1279. // be awkward, slow, and error-prone), but instead updates are
  1280. // batched and then all combined and executed at once.
  1281. function startOperation() {
  1282. updateInput = null; changes = []; textChanged = selectionChanged = false;
  1283. }
  1284. function endOperation() {
  1285. var reScroll = false;
  1286. if (selectionChanged) reScroll = !scrollCursorIntoView();
  1287. if (changes.length) updateDisplay(changes);
  1288. else if (selectionChanged) updateCursor();
  1289. if (reScroll) scrollCursorIntoView();
  1290. if (selectionChanged) restartBlink();
  1291. // updateInput can be set to a boolean value to force/prevent an
  1292. // update.
  1293. if (focused && !leaveInputAlone &&
  1294. (updateInput === true || (updateInput !== false && selectionChanged)))
  1295. prepareInput();
  1296. if (selectionChanged && options.matchBrackets)
  1297. setTimeout(operation(function() {
  1298. if (bracketHighlighted) {bracketHighlighted(); bracketHighlighted = null;}
  1299. matchBrackets(false);
  1300. }), 20);
  1301. var tc = textChanged; // textChanged can be reset by cursoractivity callback
  1302. if (selectionChanged && options.onCursorActivity)
  1303. options.onCursorActivity(instance);
  1304. if (tc && options.onChange && instance)
  1305. options.onChange(instance, tc);
  1306. }
  1307. var nestedOperation = 0;
  1308. function operation(f) {
  1309. return function() {
  1310. if (!nestedOperation++) startOperation();
  1311. try {var result = f.apply(this, arguments);}
  1312. finally {if (!--nestedOperation) endOperation();}
  1313. return result;
  1314. };
  1315. }
  1316. function SearchCursor(query, pos, caseFold) {
  1317. this.atOccurrence = false;
  1318. if (caseFold == null) caseFold = typeof query == "string" && query == query.toLowerCase();
  1319. if (pos && typeof pos == "object") pos = clipPos(pos);
  1320. else pos = {line: 0, ch: 0};
  1321. this.pos = {from: pos, to: pos};
  1322. // The matches method is filled in based on the type of query.
  1323. // It takes a position and a direction, and returns an object
  1324. // describing the next occurrence of the query, or null if no
  1325. // more matches were found.
  1326. if (typeof query != "string") // Regexp match
  1327. this.matches = function(reverse, pos) {
  1328. if (reverse) {
  1329. var line = lines[pos.line].text.slice(0, pos.ch), match = line.match(query), start = 0;
  1330. while (match) {
  1331. var ind = line.indexOf(match[0]);
  1332. start += ind;
  1333. line = line.slice(ind + 1);
  1334. var newmatch = line.match(query);
  1335. if (newmatch) match = newmatch;
  1336. else break;
  1337. start++;
  1338. }
  1339. }
  1340. else {
  1341. var line = lines[pos.line].text.slice(pos.ch), match = line.match(query),
  1342. start = match && pos.ch + line.indexOf(match[0]);
  1343. }
  1344. if (match)
  1345. return {from: {line: pos.line, ch: start},
  1346. to: {line: pos.line, ch: start + match[0].length},
  1347. match: match};
  1348. };
  1349. else { // String query
  1350. if (caseFold) query = query.toLowerCase();
  1351. var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
  1352. var target = query.split("\n");
  1353. // Different methods for single-line and multi-line queries
  1354. if (target.length == 1)
  1355. this.matches = function(reverse, pos) {
  1356. var line = fold(lines[pos.line].text), len = query.length, match;
  1357. if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1)
  1358. : (match = line.indexOf(query, pos.ch)) != -1)
  1359. return {from: {line: pos.line, ch: match},
  1360. to: {line: pos.line, ch: match + len}};
  1361. };
  1362. else
  1363. this.matches = function(reverse, pos) {
  1364. var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(lines[ln].text);
  1365. var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match));
  1366. if (reverse ? offsetA >= pos.ch || offsetA != match.length
  1367. : offsetA <= pos.ch || offsetA != line.length - match.length)
  1368. return;
  1369. for (;;) {
  1370. if (reverse ? !ln : ln == lines.length - 1) return;
  1371. line = fold(lines[ln += reverse ? -1 : 1].text);
  1372. match = target[reverse ? --idx : ++idx];
  1373. if (idx > 0 && idx < target.length - 1) {
  1374. if (line != match) return;
  1375. else continue;
  1376. }
  1377. var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length);
  1378. if (reverse ? offsetB != line.length - match.length : offsetB != match.length)
  1379. return;
  1380. var start = {line: pos.line, ch: offsetA}, end = {line: ln, ch: offsetB};
  1381. return {from: reverse ? end : start, to: reverse ? start : end};
  1382. }
  1383. };
  1384. }
  1385. }
  1386. SearchCursor.prototype = {
  1387. findNext: function() {return this.find(false);},
  1388. findPrevious: function() {return this.find(true);},
  1389. find: function(reverse) {
  1390. var self = this, pos = clipPos(reverse ? this.pos.from : this.pos.to);
  1391. function savePosAndFail(line) {
  1392. var pos = {line: line, ch: 0};
  1393. self.pos = {from: pos, to: pos};
  1394. self.atOccurrence = false;
  1395. return false;
  1396. }
  1397. for (;;) {
  1398. if (this.pos = this.matches(reverse, pos)) {
  1399. this.atOccurrence = true;
  1400. return this.pos.match || true;
  1401. }
  1402. if (reverse) {
  1403. if (!pos.line) return savePosAndFail(0);
  1404. pos = {line: pos.line-1, ch: lines[pos.line-1].text.length};
  1405. }
  1406. else {
  1407. if (pos.line == lines.length - 1) return savePosAndFail(lines.length);
  1408. pos = {line: pos.line+1, ch: 0};
  1409. }
  1410. }
  1411. },
  1412. from: function() {if (this.atOccurrence) return copyPos(this.pos.from);},
  1413. to: function() {if (this.atOccurrence) return copyPos(this.pos.to);},
  1414. replace: function(newText) {
  1415. var self = this;
  1416. if (this.atOccurrence)
  1417. operation(function() {
  1418. self.pos.to = replaceRange(newText, self.pos.from, self.pos.to);
  1419. })();
  1420. }
  1421. };
  1422. for (var ext in extensions)
  1423. if (extensions.propertyIsEnumerable(ext) &&
  1424. !instance.propertyIsEnumerable(ext))
  1425. instance[ext] = extensions[ext];
  1426. return instance;
  1427. } // (end of function CodeMirror)
  1428. // The default configuration options.
  1429. CodeMirror.defaults = {
  1430. value: "",
  1431. mode: null,
  1432. theme: "default",
  1433. indentUnit: 2,
  1434. indentWithTabs: false,
  1435. tabMode: "classic",
  1436. enterMode: "indent",
  1437. electricChars: true,
  1438. onKeyEvent: null,
  1439. lineNumbers: false,
  1440. gutter: false,
  1441. firstLineNumber: 1,
  1442. readOnly: false,
  1443. onChange: null,
  1444. onCursorActivity: null,
  1445. onGutterClick: null,
  1446. onHighlightComplete: null,
  1447. onFocus: null, onBlur: null, onScroll: null,
  1448. matchBrackets: false,
  1449. workTime: 100,
  1450. workDelay: 200,
  1451. undoDepth: 40,
  1452. tabindex: null,
  1453. document: window.document
  1454. };
  1455. // Known modes, by name and by MIME
  1456. var modes = {}, mimeModes = {};
  1457. CodeMirror.defineMode = function(name, mode) {
  1458. if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
  1459. modes[name] = mode;
  1460. };
  1461. CodeMirror.defineMIME = function(mime, spec) {
  1462. mimeModes[mime] = spec;
  1463. };
  1464. CodeMirror.getMode = function(options, spec) {
  1465. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
  1466. spec = mimeModes[spec];
  1467. if (typeof spec == "string")
  1468. var mname = spec, config = {};
  1469. else if (spec != null)
  1470. var mname = spec.name, config = spec;
  1471. var mfactory = modes[mname];
  1472. if (!mfactory) {
  1473. if (window.console) console.warn("No mode " + mname + " found, falling back to plain text.");
  1474. return CodeMirror.getMode(options, "text/plain");
  1475. }
  1476. return mfactory(options, config || {});
  1477. };
  1478. CodeMirror.listModes = function() {
  1479. var list = [];
  1480. for (var m in modes)
  1481. if (modes.propertyIsEnumerable(m)) list.push(m);
  1482. return list;
  1483. };
  1484. CodeMirror.listMIMEs = function() {
  1485. var list = [];
  1486. for (var m in mimeModes)
  1487. if (mimeModes.propertyIsEnumerable(m)) list.push(m);
  1488. return list;
  1489. };
  1490. var extensions = {};
  1491. CodeMirror.defineExtension = function(name, func) {
  1492. extensions[name] = func;
  1493. };
  1494. CodeMirror.fromTextArea = function(textarea, options) {
  1495. if (!options) options = {};
  1496. options.value = textarea.value;
  1497. if (!options.tabindex && textarea.tabindex)
  1498. options.tabindex = textarea.tabindex;
  1499. function save() {textarea.value = instance.getValue();}
  1500. if (textarea.form) {
  1501. // Deplorable hack to make the submit method do the right thing.
  1502. var rmSubmit = connect(textarea.form, "submit", save, true);
  1503. if (typeof textarea.form.submit == "function") {
  1504. var realSubmit = textarea.form.submit;
  1505. function wrappedSubmit() {
  1506. save();
  1507. textarea.form.submit = realSubmit;
  1508. textarea.form.submit();
  1509. textarea.form.submit = wrappedSubmit;
  1510. }
  1511. textarea.form.submit = wrappedSubmit;
  1512. }
  1513. }
  1514. textarea.style.display = "none";
  1515. var instance = CodeMirror(function(node) {
  1516. textarea.parentNode.insertBefore(node, textarea.nextSibling);
  1517. }, options);
  1518. instance.save = save;
  1519. instance.toTextArea = function() {
  1520. save();
  1521. textarea.parentNode.removeChild(instance.getWrapperElement());
  1522. textarea.style.display = "";
  1523. if (textarea.form) {
  1524. rmSubmit();
  1525. if (typeof textarea.form.submit == "function")
  1526. textarea.form.submit = realSubmit;
  1527. }
  1528. };
  1529. return instance;
  1530. };
  1531. // Utility functions for working with state. Exported because modes
  1532. // sometimes need to do this.
  1533. function copyState(mode, state) {
  1534. if (state === true) return state;
  1535. if (mode.copyState) return mode.copyState(state);
  1536. var nstate = {};
  1537. for (var n in state) {
  1538. var val = state[n];
  1539. if (val instanceof Array) val = val.concat([]);
  1540. nstate[n] = val;
  1541. }
  1542. return nstate;
  1543. }
  1544. CodeMirror.startState = startState;
  1545. function startState(mode, a1, a2) {
  1546. return mode.startState ? mode.startState(a1, a2) : true;
  1547. }
  1548. CodeMirror.copyState = copyState;
  1549. // The character stream used by a mode's parser.
  1550. function StringStream(string) {
  1551. this.pos = this.start = 0;
  1552. this.string = string;
  1553. }
  1554. StringStream.prototype = {
  1555. eol: function() {return this.pos >= this.string.length;},
  1556. sol: function() {return this.pos == 0;},
  1557. peek: function() {return this.string.charAt(this.pos);},
  1558. next: function() {
  1559. if (this.pos < this.string.length)
  1560. return this.string.charAt(this.pos++);
  1561. },
  1562. eat: function(match) {
  1563. var ch = this.string.charAt(this.pos);
  1564. if (typeof match == "string") var ok = ch == match;
  1565. else var ok = ch && (match.test ? match.test(ch) : match(ch));
  1566. if (ok) {++this.pos; return ch;}
  1567. },
  1568. eatWhile: function(match) {
  1569. var start = this.start;
  1570. while (this.eat(match)){}
  1571. return this.pos > start;
  1572. },
  1573. eatSpace: function() {
  1574. var start = this.pos;
  1575. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
  1576. return this.pos > start;
  1577. },
  1578. skipToEnd: function() {this.pos = this.string.length;},
  1579. skipTo: function(ch) {
  1580. var found = this.string.indexOf(ch, this.pos);
  1581. if (found > -1) {this.pos = found; return true;}
  1582. },
  1583. backUp: function(n) {this.pos -= n;},
  1584. column: function() {return countColumn(this.string, this.start);},
  1585. indentation: function() {return countColumn(this.string);},
  1586. match: function(pattern, consume, caseInsensitive) {
  1587. if (typeof pattern == "string") {
  1588. function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}
  1589. if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
  1590. if (consume !== false) this.pos += pattern.length;
  1591. return true;
  1592. }
  1593. }
  1594. else {
  1595. var match = this.string.slice(this.pos).match(pattern);
  1596. if (match && consume !== false) this.pos += match[0].length;
  1597. return match;
  1598. }
  1599. },
  1600. current: function(){return this.string.slice(this.start, this.pos);}
  1601. };
  1602. CodeMirror.StringStream = StringStream;
  1603. // Line objects. These hold state related to a line, including
  1604. // highlighting info (the styles array).
  1605. function Line(text, styles) {
  1606. this.styles = styles || [text, null];
  1607. this.stateAfter = null;
  1608. this.text = text;
  1609. this.marked = this.gutterMarker = this.className = null;
  1610. }
  1611. Line.prototype = {
  1612. // Replace a piece of a line, keeping the styles around it intact.
  1613. replace: function(from, to, text) {
  1614. var st = [], mk = this.marked;
  1615. copyStyles(0, from, this.styles, st);
  1616. if (text) st.push(text, null);
  1617. copyStyles(to, this.text.length, this.styles, st);
  1618. this.styles = st;
  1619. this.text = this.text.slice(0, from) + text + this.text.slice(to);
  1620. this.stateAfter = null;
  1621. if (mk) {
  1622. var diff = text.length - (to - from), end = this.text.length;
  1623. function fix(n) {return n <= Math.min(to, to + diff) ? n : n + diff;}
  1624. for (var i = 0; i < mk.length; ++i) {
  1625. var mark = mk[i], del = false;
  1626. if (mark.from >= end) del = true;
  1627. else {mark.from = fix(mark.from); if (mark.to != null) mark.to = fix(mark.to);}
  1628. if (del || mark.from >= mark.to) {mk.splice(i, 1); i--;}
  1629. }
  1630. }
  1631. },
  1632. // Split a line in two, again keeping styles intact.
  1633. split: function(pos, textBefore) {
  1634. var st = [textBefore, null];
  1635. copyStyles(pos, this.text.length, this.styles, st);
  1636. return new Line(textBefore + this.text.slice(pos), st);
  1637. },
  1638. addMark: function(from, to, style) {
  1639. var mk = this.marked, mark = {from: from, to: to, style: style};
  1640. if (this.marked == null) this.marked = [];
  1641. this.marked.push(mark);
  1642. this.marked.sort(function(a, b){return a.from - b.from;});
  1643. return mark;
  1644. },
  1645. removeMark: function(mark) {
  1646. var mk = this.marked;
  1647. if (!mk) return;
  1648. for (var i = 0; i < mk.length; ++i)
  1649. if (mk[i] == mark) {mk.splice(i, 1); break;}
  1650. },
  1651. // Run the given mode's parser over a line, update the styles
  1652. // array, which contains alternating fragments of text and CSS
  1653. // classes.
  1654. highlight: function(mode, state) {
  1655. var stream = new StringStream(this.text), st = this.styles, pos = 0;
  1656. var changed = false, curWord = st[0], prevWord;
  1657. if (this.text == "" && mode.blankLine) mode.blankLine(state);
  1658. while (!stream.eol()) {
  1659. var style = mode.token(stream, state);
  1660. var substr = this.text.slice(stream.start, stream.pos);
  1661. stream.start = stream.pos;
  1662. if (pos && st[pos-1] == style)
  1663. st[pos-2] += substr;
  1664. else if (substr) {
  1665. if (!changed && (st[pos+1] != style || (pos && st[pos-2] != prevWord))) changed = true;
  1666. st[pos++] = substr; st[pos++] = style;
  1667. prevWord = curWord; curWord = st[pos];
  1668. }
  1669. // Give up when line is ridiculously long
  1670. if (stream.pos > 5000) {
  1671. st[pos++] = this.text.slice(stream.pos); st[pos++] = null;
  1672. break;
  1673. }
  1674. }
  1675. if (st.length != pos) {st.length = pos; changed = true;}
  1676. if (pos && st[pos-2] != prevWord) changed = true;
  1677. // Short lines with simple highlights always count as changed,
  1678. // because they are likely to highlight the same way in various
  1679. // contexts.
  1680. return changed || (st.length < 5 && this.text.length < 10);
  1681. },
  1682. // Fetch the parser token for a given character. Useful for hacks
  1683. // that want to inspect the mode state (say, for completion).
  1684. getTokenAt: function(mode, state, ch) {
  1685. var txt = this.text, stream = new StringStream(txt);
  1686. while (stream.pos < ch && !stream.eol()) {
  1687. stream.start = stream.pos;
  1688. var style = mode.token(stream, state);
  1689. }
  1690. return {start: stream.start,
  1691. end: stream.pos,
  1692. string: stream.current(),
  1693. className: style || null,
  1694. state: state};
  1695. },
  1696. indentation: function() {return countColumn(this.text);},
  1697. // Produces an HTML fragment for the line, taking selection,
  1698. // marking, and highlighting into account.
  1699. getHTML: function(sfrom, sto, includePre, endAt) {
  1700. var html = [];
  1701. if (includePre)
  1702. html.push(this.className ? '<pre class="' + this.className + '">': "<pre>");
  1703. function span(text, style) {
  1704. if (!text) return;
  1705. if (style) html.push('<span class="', style, '">', htmlEscape(text), "</span>");
  1706. else html.push(htmlEscape(text));
  1707. }
  1708. var st = this.styles, allText = this.text, marked = this.marked;
  1709. if (sfrom == sto) sfrom = null;
  1710. var len = allText.length;
  1711. if (endAt != null) len = Math.min(endAt, len);
  1712. if (!allText && endAt == null)
  1713. span(" ", sfrom != null && sto == null ? "CodeMirror-selected" : null);
  1714. else if (!marked && sfrom == null)
  1715. for (var i = 0, ch = 0; ch < len; i+=2) {
  1716. var str = st[i], l = str.length;
  1717. if (ch + l > len) str = str.slice(0, len - ch);
  1718. ch += l;
  1719. span(str, "cm-" + st[i+1]);
  1720. }
  1721. else {
  1722. var pos = 0, i = 0, text = "", style, sg = 0;
  1723. var markpos = -1, mark = null;
  1724. function nextMark() {
  1725. if (marked) {
  1726. markpos += 1;
  1727. mark = (markpos < marked.length) ? marked[markpos] : null;
  1728. }
  1729. }
  1730. nextMark();
  1731. while (pos < len) {
  1732. var upto = len;
  1733. var extraStyle = "";
  1734. if (sfrom != null) {
  1735. if (sfrom > pos) upto = sfrom;
  1736. else if (sto == null || sto > pos) {
  1737. extraStyle = " CodeMirror-selected";
  1738. if (sto != null) upto = Math.min(upto, sto);
  1739. }
  1740. }
  1741. while (mark && mark.to != null && mark.to <= pos) nextMark();
  1742. if (mark) {
  1743. if (mark.from > pos) upto = Math.min(upto, mark.from);
  1744. else {
  1745. extraStyle += " " + mark.style;
  1746. if (mark.to != null) upto = Math.min(upto, mark.to);
  1747. }
  1748. }
  1749. for (;;) {
  1750. var end = pos + text.length;
  1751. var appliedStyle = style;
  1752. if (extraStyle) appliedStyle = style ? style + extraStyle : extraStyle;
  1753. span(end > upto ? text.slice(0, upto - pos) : text, appliedStyle);
  1754. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
  1755. pos = end;
  1756. text = st[i++]; style = "cm-" + st[i++];
  1757. }
  1758. }
  1759. if (sfrom != null && sto == null) span(" ", "CodeMirror-selected");
  1760. }
  1761. if (includePre) html.push("</pre>");
  1762. return html.join("");
  1763. }
  1764. };
  1765. // Utility used by replace and split above
  1766. function copyStyles(from, to, source, dest) {
  1767. for (var i = 0, pos = 0, state = 0; pos < to; i+=2) {
  1768. var part = source[i], end = pos + part.length;
  1769. if (state == 0) {
  1770. if (end > from) dest.push(part.slice(from - pos, Math.min(part.length, to - pos)), source[i+1]);
  1771. if (end >= from) state = 1;
  1772. }
  1773. else if (state == 1) {
  1774. if (end > to) dest.push(part.slice(0, to - pos), source[i+1]);
  1775. else dest.push(part, source[i+1]);
  1776. }
  1777. pos = end;
  1778. }
  1779. }
  1780. // The history object 'chunks' changes that are made close together
  1781. // and at almost the same time into bigger undoable units.
  1782. function History() {
  1783. this.time = 0;
  1784. this.done = []; this.undone = [];
  1785. }
  1786. History.prototype = {
  1787. addChange: function(start, added, old) {
  1788. this.undone.length = 0;
  1789. var time = +new Date, last = this.done[this.done.length - 1];
  1790. if (time - this.time > 400 || !last ||
  1791. last.start > start + added || last.start + last.added < start - last.added + last.old.length)
  1792. this.done.push({start: start, added: added, old: old});
  1793. else {
  1794. var oldoff = 0;
  1795. if (start < last.start) {
  1796. for (var i = last.start - start - 1; i >= 0; --i)
  1797. last.old.unshift(old[i]);
  1798. last.added += last.start - start;
  1799. last.start = start;
  1800. }
  1801. else if (last.start < start) {
  1802. oldoff = start - last.start;
  1803. added += oldoff;
  1804. }
  1805. for (var i = last.added - oldoff, e = old.length; i < e; ++i)
  1806. last.old.push(old[i]);
  1807. if (last.added < added) last.added = added;
  1808. }
  1809. this.time = time;
  1810. }
  1811. };
  1812. function stopMethod() {e_stop(this);}
  1813. // Ensure an event has a stop method.
  1814. function addStop(event) {
  1815. if (!event.stop) event.stop = stopMethod;
  1816. return event;
  1817. }
  1818. function e_preventDefault(e) {
  1819. if (e.preventDefault) e.preventDefault();
  1820. else e.returnValue = false;
  1821. }
  1822. function e_stopPropagation(e) {
  1823. if (e.stopPropagation) e.stopPropagation();
  1824. else e.cancelBubble = true;
  1825. }
  1826. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  1827. function e_target(e) {return e.target || e.srcElement;}
  1828. function e_button(e) {
  1829. if (e.which) return e.which;
  1830. else if (e.button & 1) return 1;
  1831. else if (e.button & 2) return 3;
  1832. else if (e.button & 4) return 2;
  1833. }
  1834. function e_pageX(e) {
  1835. if (e.pageX != null) return e.pageX;
  1836. var doc = e_target(e).ownerDocument;
  1837. return e.clientX + doc.body.scrollLeft + doc.documentElement.scrollLeft;
  1838. }
  1839. function e_pageY(e) {
  1840. if (e.pageY != null) return e.pageY;
  1841. var doc = e_target(e).ownerDocument;
  1842. return e.clientY + doc.body.scrollTop + doc.documentElement.scrollTop;
  1843. }
  1844. // Event handler registration. If disconnect is true, it'll return a
  1845. // function that unregisters the handler.
  1846. function connect(node, type, handler, disconnect) {
  1847. function wrapHandler(event) {handler(event || window.event);}
  1848. if (typeof node.addEventListener == "function") {
  1849. node.addEventListener(type, wrapHandler, false);
  1850. if (disconnect) return function() {node.removeEventListener(type, wrapHandler, false);};
  1851. }
  1852. else {
  1853. node.attachEvent("on" + type, wrapHandler);
  1854. if (disconnect) return function() {node.detachEvent("on" + type, wrapHandler);};
  1855. }
  1856. }
  1857. function Delayed() {this.id = null;}
  1858. Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
  1859. // Some IE versions don't preserve whitespace when setting the
  1860. // innerHTML of a PRE tag.
  1861. var badInnerHTML = (function() {
  1862. var pre = document.createElement("pre");
  1863. pre.innerHTML = " "; return !pre.innerHTML;
  1864. })();
  1865. var gecko = /gecko\/\d{7}/i.test(navigator.userAgent);
  1866. var ie = /MSIE \d/.test(navigator.userAgent);
  1867. var safari = /Apple Computer/.test(navigator.vendor);
  1868. var lineSep = "\n";
  1869. // Feature-detect whether newlines in textareas are converted to \r\n
  1870. (function () {
  1871. var te = document.createElement("textarea");
  1872. te.value = "foo\nbar";
  1873. if (te.value.indexOf("\r") > -1) lineSep = "\r\n";
  1874. }());
  1875. var tabSize = 8;
  1876. var mac = /Mac/.test(navigator.platform);
  1877. var movementKeys = {};
  1878. for (var i = 35; i <= 40; ++i)
  1879. movementKeys[i] = movementKeys["c" + i] = true;
  1880. // Counts the column offset in a string, taking tabs into account.
  1881. // Used mostly to find indentation.
  1882. function countColumn(string, end) {
  1883. if (end == null) {
  1884. end = string.search(/[^\s\u00a0]/);
  1885. if (end == -1) end = string.length;
  1886. }
  1887. for (var i = 0, n = 0; i < end; ++i) {
  1888. if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
  1889. else ++n;
  1890. }
  1891. return n;
  1892. }
  1893. function computedStyle(elt) {
  1894. if (elt.currentStyle) return elt.currentStyle;
  1895. return window.getComputedStyle(elt, null);
  1896. }
  1897. // Find the position of an element by following the offsetParent chain.
  1898. // If screen==true, it returns screen (rather than page) coordinates.
  1899. function eltOffset(node, screen) {
  1900. var doc = node.ownerDocument.body;
  1901. var x = 0, y = 0, skipDoc = false;
  1902. for (var n = node; n; n = n.offsetParent) {
  1903. x += n.offsetLeft; y += n.offsetTop;
  1904. if (screen && computedStyle(n).position == "fixed")
  1905. skipDoc = true;
  1906. }
  1907. var e = screen && !skipDoc ? null : doc;
  1908. for (var n = node.parentNode; n != e; n = n.parentNode)
  1909. if (n.scrollLeft != null) { x -= n.scrollLeft; y -= n.scrollTop;}
  1910. return {left: x, top: y};
  1911. }
  1912. // Get a node's text content.
  1913. function eltText(node) {
  1914. return node.textContent || node.innerText || node.nodeValue || "";
  1915. }
  1916. // Operations on {line, ch} objects.
  1917. function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
  1918. function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
  1919. function copyPos(x) {return {line: x.line, ch: x.ch};}
  1920. var escapeElement = document.createElement("div");
  1921. function htmlEscape(str) {
  1922. escapeElement.innerText = escapeElement.textContent = str;
  1923. return escapeElement.innerHTML;
  1924. }
  1925. CodeMirror.htmlEscape = htmlEscape;
  1926. // Used to position the cursor after an undo/redo by finding the
  1927. // last edited character.
  1928. function editEnd(from, to) {
  1929. if (!to) return from ? from.length : 0;
  1930. if (!from) return to.length;
  1931. for (var i = from.length, j = to.length; i >= 0 && j >= 0; --i, --j)
  1932. if (from.charAt(i) != to.charAt(j)) break;
  1933. return j + 1;
  1934. }
  1935. function indexOf(collection, elt) {
  1936. if (collection.indexOf) return collection.indexOf(elt);
  1937. for (var i = 0, e = collection.length; i < e; ++i)
  1938. if (collection[i] == elt) return i;
  1939. return -1;
  1940. }
  1941. // See if "".split is the broken IE version, if so, provide an
  1942. // alternative way to split lines.
  1943. var splitLines, selRange, setSelRange;
  1944. if ("\n\nb".split(/\n/).length != 3)
  1945. splitLines = function(string) {
  1946. var pos = 0, nl, result = [];
  1947. while ((nl = string.indexOf("\n", pos)) > -1) {
  1948. result.push(string.slice(pos, string.charAt(nl-1) == "\r" ? nl - 1 : nl));
  1949. pos = nl + 1;
  1950. }
  1951. result.push(string.slice(pos));
  1952. return result;
  1953. };
  1954. else
  1955. splitLines = function(string){return string.split(/\r?\n/);};
  1956. CodeMirror.splitLines = splitLines;
  1957. // Sane model of finding and setting the selection in a textarea
  1958. if (window.getSelection) {
  1959. selRange = function(te) {
  1960. try {return {start: te.selectionStart, end: te.selectionEnd};}
  1961. catch(e) {return null;}
  1962. };
  1963. if (safari)
  1964. // On Safari, selection set with setSelectionRange are in a sort
  1965. // of limbo wrt their anchor. If you press shift-left in them,
  1966. // the anchor is put at the end, and the selection expanded to
  1967. // the left. If you press shift-right, the anchor ends up at the
  1968. // front. This is not what CodeMirror wants, so it does a
  1969. // spurious modify() call to get out of limbo.
  1970. setSelRange = function(te, start, end) {
  1971. if (start == end)
  1972. te.setSelectionRange(start, end);
  1973. else {
  1974. te.setSelectionRange(start, end - 1);
  1975. window.getSelection().modify("extend", "forward", "character");
  1976. }
  1977. };
  1978. else
  1979. setSelRange = function(te, start, end) {
  1980. try {te.setSelectionRange(start, end);}
  1981. catch(e) {} // Fails on Firefox when textarea isn't part of the document
  1982. };
  1983. }
  1984. // IE model. Don't ask.
  1985. else {
  1986. selRange = function(te) {
  1987. try {var range = te.ownerDocument.selection.createRange();}
  1988. catch(e) {return null;}
  1989. if (!range || range.parentElement() != te) return null;
  1990. var val = te.value, len = val.length, localRange = te.createTextRange();
  1991. localRange.moveToBookmark(range.getBookmark());
  1992. var endRange = te.createTextRange();
  1993. endRange.collapse(false);
  1994. if (localRange.compareEndPoints("StartToEnd", endRange) > -1)
  1995. return {start: len, end: len};
  1996. var start = -localRange.moveStart("character", -len);
  1997. for (var i = val.indexOf("\r"); i > -1 && i < start; i = val.indexOf("\r", i+1), start++) {}
  1998. if (localRange.compareEndPoints("EndToEnd", endRange) > -1)
  1999. return {start: start, end: len};
  2000. var end = -localRange.moveEnd("character", -len);
  2001. for (var i = val.indexOf("\r"); i > -1 && i < end; i = val.indexOf("\r", i+1), end++) {}
  2002. return {start: start, end: end};
  2003. };
  2004. setSelRange = function(te, start, end) {
  2005. var range = te.createTextRange();
  2006. range.collapse(true);
  2007. var endrange = range.duplicate();
  2008. var newlines = 0, txt = te.value;
  2009. for (var pos = txt.indexOf("\n"); pos > -1 && pos < start; pos = txt.indexOf("\n", pos + 1))
  2010. ++newlines;
  2011. range.move("character", start - newlines);
  2012. for (; pos > -1 && pos < end; pos = txt.indexOf("\n", pos + 1))
  2013. ++newlines;
  2014. endrange.move("character", end - newlines);
  2015. range.setEndPoint("EndToEnd", endrange);
  2016. range.select();
  2017. };
  2018. }
  2019. CodeMirror.defineMode("null", function() {
  2020. return {token: function(stream) {stream.skipToEnd();}};
  2021. });
  2022. CodeMirror.defineMIME("text/plain", "null");
  2023. return CodeMirror;
  2024. })()
  2025. ;