codemirror.js 115 KB

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