codemirror.js 131 KB

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