codemirror.js 162 KB

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