codemirror.js 129 KB

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