codemirror.js 136 KB

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