codemirror.js 174 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553
  1. // CodeMirror version 3.0
  2. //
  3. // CodeMirror is the only global var we claim
  4. window.CodeMirror = (function() {
  5. "use strict";
  6. // BROWSER SNIFFING
  7. // Crude, but necessary to handle a number of hard-to-feature-detect
  8. // bugs and behavior differences.
  9. var gecko = /gecko\/\d/i.test(navigator.userAgent);
  10. var ie = /MSIE \d/.test(navigator.userAgent);
  11. var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent);
  12. var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent);
  13. var webkit = /WebKit\//.test(navigator.userAgent);
  14. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
  15. var chrome = /Chrome\//.test(navigator.userAgent);
  16. var opera = /Opera\//.test(navigator.userAgent);
  17. var safari = /Apple Computer/.test(navigator.vendor);
  18. var khtml = /KHTML\//.test(navigator.userAgent);
  19. var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent);
  20. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
  21. var phantom = /PhantomJS/.test(navigator.userAgent);
  22. var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
  23. // This is woefully incomplete. Suggestions for alternative methods welcome.
  24. var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|IEMobile/i.test(navigator.userAgent);
  25. var mac = ios || /Mac/.test(navigator.platform);
  26. // Optimize some code when these features are not used
  27. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  28. // CONSTRUCTOR
  29. function CodeMirror(place, options) {
  30. if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
  31. this.options = options = options || {};
  32. // Determine effective options based on given values and defaults.
  33. for (var opt in defaults) if (!options.hasOwnProperty(opt) && defaults.hasOwnProperty(opt))
  34. options[opt] = defaults[opt];
  35. setGuttersForLineNumbers(options);
  36. var display = this.display = makeDisplay(place);
  37. display.wrapper.CodeMirror = this;
  38. updateGutters(this);
  39. if (options.autofocus && !mobile) focusInput(this);
  40. this.view = makeView(new BranchChunk([new LeafChunk([makeLine("", null, textHeight(display))])]));
  41. this.nextOpId = 0;
  42. loadMode(this);
  43. themeChanged(this);
  44. if (options.lineWrapping)
  45. this.display.wrapper.className += " CodeMirror-wrap";
  46. // Initialize the content.
  47. this.setValue(options.value || "");
  48. // Override magic textarea content restore that IE sometimes does
  49. // on our hidden textarea on reload
  50. if (ie) setTimeout(bind(resetInput, this, true), 20);
  51. this.view.history = makeHistory();
  52. registerEventHandlers(this);
  53. // IE throws unspecified error in certain cases, when
  54. // trying to access activeElement before onload
  55. var hasFocus; try { hasFocus = (document.activeElement == display.input); } catch(e) { }
  56. if (hasFocus || (options.autofocus && !mobile)) setTimeout(bind(onFocus, this), 20);
  57. else onBlur(this);
  58. operation(this, function() {
  59. for (var opt in optionHandlers)
  60. if (optionHandlers.propertyIsEnumerable(opt))
  61. optionHandlers[opt](this, options[opt], Init);
  62. for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
  63. })();
  64. }
  65. // DISPLAY CONSTRUCTOR
  66. function makeDisplay(place) {
  67. var d = {};
  68. var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none;");
  69. input.setAttribute("wrap", "off"); input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off");
  70. // Wraps and hides input textarea
  71. d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  72. // The actual fake scrollbars.
  73. d.scrollbarH = elt("div", [elt("div", null, null, "height: 1px")], "CodeMirror-hscrollbar");
  74. d.scrollbarV = elt("div", [elt("div", null, null, "width: 1px")], "CodeMirror-vscrollbar");
  75. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  76. // DIVs containing the selection and the actual code
  77. d.lineDiv = elt("div");
  78. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  79. // Blinky cursor, and element used to ensure cursor fits at the end of a line
  80. d.cursor = elt("pre", "\u00a0", "CodeMirror-cursor");
  81. // Secondary cursor, shown when on a 'jump' in bi-directional text
  82. d.otherCursor = elt("pre", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor");
  83. // Used to measure text size
  84. d.measure = elt("div", null, "CodeMirror-measure");
  85. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  86. d.lineSpace = elt("div", [d.measure, d.selectionDiv, d.lineDiv, d.cursor, d.otherCursor],
  87. null, "position: relative; outline: none");
  88. // Moved around its parent to cover visible view
  89. d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
  90. // Set to the height of the text, causes scrolling
  91. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  92. // D is needed because behavior of elts with overflow: auto and padding is inconsistent across browsers
  93. d.heightForcer = elt("div", "\u00a0", null, "position: absolute; height: " + scrollerCutOff + "px");
  94. // Will contain the gutters, if any
  95. d.gutters = elt("div", null, "CodeMirror-gutters");
  96. d.lineGutter = null;
  97. // Helper element to properly size the gutter backgrounds
  98. var scrollerInner = elt("div", [d.sizer, d.heightForcer, d.gutters], null, "position: relative; min-height: 100%");
  99. // Provides scrolling
  100. d.scroller = elt("div", [scrollerInner], "CodeMirror-scroll");
  101. d.scroller.setAttribute("tabIndex", "-1");
  102. // The element in which the editor lives.
  103. d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV,
  104. d.scrollbarFiller, d.scroller], "CodeMirror");
  105. // Work around IE7 z-index bug
  106. if (ie_lt8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  107. if (place.appendChild) place.appendChild(d.wrapper); else place(d.wrapper);
  108. // Needed to hide big blue blinking cursor on Mobile Safari
  109. if (ios) input.style.width = "0px";
  110. if (!webkit) d.scroller.draggable = true;
  111. // Needed to handle Tab key in KHTML
  112. if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; }
  113. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  114. else if (ie_lt8) d.scrollbarH.style.minWidth = d.scrollbarV.style.minWidth = "18px";
  115. // Current visible range (may be bigger than the view window).
  116. d.viewOffset = d.showingFrom = d.showingTo = d.lastSizeC = 0;
  117. // Used to only resize the line number gutter when necessary (when
  118. // the amount of lines crosses a boundary that makes its width change)
  119. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  120. // See readInput and resetInput
  121. d.prevInput = "";
  122. // Set to true when a non-horizontal-scrolling widget is added. As
  123. // an optimization, widget aligning is skipped when d is false.
  124. d.alignWidgets = false;
  125. // Flag that indicates whether we currently expect input to appear
  126. // (after some event like 'keypress' or 'input') and are polling
  127. // intensively.
  128. d.pollingFast = false;
  129. // Self-resetting timeout for the poller
  130. d.poll = new Delayed();
  131. // True when a drag from the editor is active
  132. d.draggingText = false;
  133. d.cachedCharWidth = d.cachedTextHeight = null;
  134. d.measureLineCache = [];
  135. d.measureLineCachePos = 0;
  136. // Tracks when resetInput has punted to just putting a short
  137. // string instead of the (large) selection.
  138. d.inaccurateSelection = false;
  139. // Used to adjust overwrite behaviour when a paste has been
  140. // detected
  141. d.pasteIncoming = false;
  142. return d;
  143. }
  144. // VIEW CONSTRUCTOR
  145. function makeView(doc) {
  146. var selPos = {line: 0, ch: 0};
  147. return {
  148. doc: doc,
  149. // frontier is the point up to which the content has been parsed,
  150. frontier: 0, highlight: new Delayed(),
  151. sel: {from: selPos, to: selPos, head: selPos, anchor: selPos, shift: false, extend: false},
  152. scrollTop: 0, scrollLeft: 0,
  153. overwrite: false, focused: false,
  154. // Tracks the maximum line length so that
  155. // the horizontal scrollbar can be kept
  156. // static when scrolling.
  157. maxLine: getLine(doc, 0),
  158. maxLineLength: 0,
  159. maxLineChanged: false,
  160. suppressEdits: false,
  161. goalColumn: null,
  162. cantEdit: false,
  163. keyMaps: []
  164. };
  165. }
  166. // STATE UPDATES
  167. // Used to get the editor into a consistent state again when options change.
  168. function loadMode(cm) {
  169. var doc = cm.view.doc;
  170. cm.view.mode = CodeMirror.getMode(cm.options, cm.options.mode);
  171. doc.iter(0, doc.size, function(line) { line.stateAfter = null; });
  172. cm.view.frontier = 0;
  173. startWorker(cm, 100);
  174. }
  175. function wrappingChanged(cm) {
  176. var doc = cm.view.doc, th = textHeight(cm.display);
  177. if (cm.options.lineWrapping) {
  178. cm.display.wrapper.className += " CodeMirror-wrap";
  179. var perLine = cm.display.scroller.clientWidth / charWidth(cm.display) - 3;
  180. doc.iter(0, doc.size, function(line) {
  181. if (line.height == 0) return;
  182. var guess = Math.ceil(line.text.length / perLine) || 1;
  183. if (guess != 1) updateLineHeight(line, guess * th);
  184. });
  185. cm.display.sizer.style.minWidth = "";
  186. } else {
  187. cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", "");
  188. computeMaxLength(cm.view);
  189. doc.iter(0, doc.size, function(line) {
  190. if (line.height != 0) updateLineHeight(line, th);
  191. });
  192. }
  193. regChange(cm, 0, doc.size);
  194. clearCaches(cm);
  195. setTimeout(function(){updateScrollbars(cm.display, cm.view.doc.height);}, 100);
  196. }
  197. function keyMapChanged(cm) {
  198. var style = keyMap[cm.options.keyMap].style;
  199. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") +
  200. (style ? " cm-keymap-" + style : "");
  201. }
  202. function themeChanged(cm) {
  203. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  204. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  205. clearCaches(cm);
  206. }
  207. function guttersChanged(cm) {
  208. updateGutters(cm);
  209. updateDisplay(cm, true);
  210. }
  211. function updateGutters(cm) {
  212. var gutters = cm.display.gutters, specs = cm.options.gutters;
  213. removeChildren(gutters);
  214. for (var i = 0; i < specs.length; ++i) {
  215. var gutterClass = specs[i];
  216. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
  217. if (gutterClass == "CodeMirror-linenumbers") {
  218. cm.display.lineGutter = gElt;
  219. gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
  220. }
  221. }
  222. gutters.style.display = i ? "" : "none";
  223. }
  224. function lineLength(doc, line) {
  225. if (line.height == 0) return 0;
  226. var len = line.text.length, merged, cur = line;
  227. while (merged = collapsedSpanAtStart(cur)) {
  228. var found = merged.find();
  229. cur = getLine(doc, found.from.line);
  230. len += found.from.ch - found.to.ch;
  231. }
  232. cur = line;
  233. while (merged = collapsedSpanAtEnd(cur)) {
  234. var found = merged.find();
  235. len -= cur.text.length - found.from.ch;
  236. cur = getLine(doc, found.to.line);
  237. len += cur.text.length - found.to.ch;
  238. }
  239. return len;
  240. }
  241. function computeMaxLength(view) {
  242. view.maxLine = getLine(view.doc, 0);
  243. view.maxLineLength = lineLength(view.doc, view.maxLine);
  244. view.maxLineChanged = true;
  245. view.doc.iter(1, view.doc.size, function(line) {
  246. var len = lineLength(view.doc, line);
  247. if (len > view.maxLineLength) {
  248. view.maxLineLength = len;
  249. view.maxLine = line;
  250. }
  251. });
  252. }
  253. // Make sure the gutters options contains the element
  254. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  255. function setGuttersForLineNumbers(options) {
  256. var found = false;
  257. for (var i = 0; i < options.gutters.length; ++i) {
  258. if (options.gutters[i] == "CodeMirror-linenumbers") {
  259. if (options.lineNumbers) found = true;
  260. else options.gutters.splice(i--, 1);
  261. }
  262. }
  263. if (!found && options.lineNumbers)
  264. options.gutters.push("CodeMirror-linenumbers");
  265. }
  266. // SCROLLBARS
  267. // Re-synchronize the fake scrollbars with the actual size of the
  268. // content. Optionally force a scrollTop.
  269. function updateScrollbars(d /* display */, docHeight) {
  270. var totalHeight = docHeight + 2 * paddingTop(d);
  271. d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px";
  272. var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight);
  273. var needsH = d.scroller.scrollWidth > d.scroller.clientWidth;
  274. var needsV = scrollHeight > d.scroller.clientHeight;
  275. if (needsV) {
  276. d.scrollbarV.style.display = "block";
  277. d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0";
  278. d.scrollbarV.firstChild.style.height =
  279. (scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px";
  280. } else d.scrollbarV.style.display = "";
  281. if (needsH) {
  282. d.scrollbarH.style.display = "block";
  283. d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0";
  284. d.scrollbarH.firstChild.style.width =
  285. (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px";
  286. } else d.scrollbarH.style.display = "";
  287. if (needsH && needsV) {
  288. d.scrollbarFiller.style.display = "block";
  289. d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px";
  290. } else d.scrollbarFiller.style.display = "";
  291. if (mac_geLion && scrollbarWidth(d.measure) === 0)
  292. d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px";
  293. }
  294. function visibleLines(display, doc, viewPort) {
  295. var top = display.scroller.scrollTop, height = display.wrapper.clientHeight;
  296. if (typeof viewPort == "number") top = viewPort;
  297. else if (viewPort) {top = viewPort.top; height = viewPort.bottom - viewPort.top;}
  298. top = Math.floor(top - paddingTop(display));
  299. var bottom = Math.ceil(top + height);
  300. return {from: lineAtHeight(doc, top), to: lineAtHeight(doc, bottom)};
  301. }
  302. // LINE NUMBERS
  303. function alignHorizontally(cm) {
  304. var display = cm.display;
  305. if (!display.alignWidgets && !display.gutters.firstChild) return;
  306. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.view.scrollLeft;
  307. var gutterW = display.gutters.offsetWidth, l = comp + "px";
  308. for (var n = display.lineDiv.firstChild; n; n = n.nextSibling) if (n.alignable) {
  309. for (var i = 0, a = n.alignable; i < a.length; ++i) a[i].style.left = l;
  310. }
  311. display.gutters.style.left = (comp + gutterW) + "px";
  312. }
  313. function maybeUpdateLineNumberWidth(cm) {
  314. if (!cm.options.lineNumbers) return false;
  315. var doc = cm.view.doc, last = lineNumberFor(cm.options, doc.size - 1), display = cm.display;
  316. if (last.length != display.lineNumChars) {
  317. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  318. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  319. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  320. display.lineGutter.style.width = "";
  321. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);
  322. display.lineNumWidth = display.lineNumInnerWidth + padding;
  323. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  324. display.lineGutter.style.width = display.lineNumWidth + "px";
  325. return true;
  326. }
  327. return false;
  328. }
  329. function lineNumberFor(options, i) {
  330. return String(options.lineNumberFormatter(i + options.firstLineNumber));
  331. }
  332. function compensateForHScroll(display) {
  333. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
  334. }
  335. // DISPLAY DRAWING
  336. function updateDisplay(cm, changes, viewPort) {
  337. var oldFrom = cm.display.showingFrom, oldTo = cm.display.showingTo;
  338. var updated = updateDisplayInner(cm, changes, viewPort);
  339. if (updated) {
  340. signalLater(cm, cm, "update", cm);
  341. if (cm.display.showingFrom != oldFrom || cm.display.showingTo != oldTo)
  342. signalLater(cm, cm, "viewportChange", cm, cm.display.showingFrom, cm.display.showingTo);
  343. }
  344. updateSelection(cm);
  345. updateScrollbars(cm.display, cm.view.doc.height);
  346. return updated;
  347. }
  348. // Uses a set of changes plus the current scroll position to
  349. // determine which DOM updates have to be made, and makes the
  350. // updates.
  351. function updateDisplayInner(cm, changes, viewPort) {
  352. var display = cm.display, doc = cm.view.doc;
  353. if (!display.wrapper.clientWidth) {
  354. display.showingFrom = display.showingTo = display.viewOffset = 0;
  355. return;
  356. }
  357. // Compute the new visible window
  358. // If scrollTop is specified, use that to determine which lines
  359. // to render instead of the current scrollbar position.
  360. var visible = visibleLines(display, doc, viewPort);
  361. // Bail out if the visible area is already rendered and nothing changed.
  362. if (changes !== true && changes.length == 0 &&
  363. visible.from > display.showingFrom && visible.to < display.showingTo)
  364. return;
  365. if (changes && maybeUpdateLineNumberWidth(cm))
  366. changes = true;
  367. display.sizer.style.marginLeft = display.scrollbarH.style.left = display.gutters.offsetWidth + "px";
  368. // When merged lines are present, the line that needs to be
  369. // redrawn might not be the one that was changed.
  370. if (changes !== true && sawCollapsedSpans)
  371. for (var i = 0; i < changes.length; ++i) {
  372. var ch = changes[i], merged;
  373. while (merged = collapsedSpanAtStart(getLine(doc, ch.from))) {
  374. var from = merged.find().from.line;
  375. if (ch.diff) ch.diff -= ch.from - from;
  376. ch.from = from;
  377. }
  378. }
  379. // Used to determine which lines need their line numbers updated
  380. var positionsChangedFrom = changes === true ? 0 : Infinity;
  381. if (cm.options.lineNumbers && changes && changes !== true)
  382. for (var i = 0; i < changes.length; ++i)
  383. if (changes[i].diff) { positionsChangedFrom = changes[i].from; break; }
  384. var from = Math.max(visible.from - cm.options.viewportMargin, 0);
  385. var to = Math.min(doc.size, visible.to + cm.options.viewportMargin);
  386. if (display.showingFrom < from && from - display.showingFrom < 20) from = display.showingFrom;
  387. if (display.showingTo > to && display.showingTo - to < 20) to = Math.min(doc.size, display.showingTo);
  388. if (sawCollapsedSpans) {
  389. from = lineNo(visualLine(doc, getLine(doc, from)));
  390. while (to < doc.size && lineIsHidden(getLine(doc, to))) ++to;
  391. }
  392. // Create a range of theoretically intact lines, and punch holes
  393. // in that using the change info.
  394. var intact = changes === true ? [] :
  395. computeIntact([{from: display.showingFrom, to: display.showingTo}], changes);
  396. // Clip off the parts that won't be visible
  397. var intactLines = 0;
  398. for (var i = 0; i < intact.length; ++i) {
  399. var range = intact[i];
  400. if (range.from < from) range.from = from;
  401. if (range.to > to) range.to = to;
  402. if (range.from >= range.to) intact.splice(i--, 1);
  403. else intactLines += range.to - range.from;
  404. }
  405. if (intactLines == to - from && from == display.showingFrom && to == display.showingTo)
  406. return;
  407. intact.sort(function(a, b) {return a.from - b.from;});
  408. if (intactLines < (to - from) * .7) display.lineDiv.style.display = "none";
  409. patchDisplay(cm, from, to, intact, positionsChangedFrom);
  410. display.lineDiv.style.display = "";
  411. var different = from != display.showingFrom || to != display.showingTo ||
  412. display.lastSizeC != display.wrapper.clientHeight;
  413. // This is just a bogus formula that detects when the editor is
  414. // resized or the font size changes.
  415. if (different) display.lastSizeC = display.wrapper.clientHeight;
  416. display.showingFrom = from; display.showingTo = to;
  417. startWorker(cm, 100);
  418. var prevBottom = display.lineDiv.offsetTop;
  419. for (var node = display.lineDiv.firstChild, height; node; node = node.nextSibling) if (node.lineObj) {
  420. if (ie_lt8) {
  421. var bot = node.offsetTop + node.offsetHeight;
  422. height = bot - prevBottom;
  423. prevBottom = bot;
  424. } else {
  425. var box = node.getBoundingClientRect();
  426. height = box.bottom - box.top;
  427. }
  428. var diff = node.lineObj.height - height;
  429. if (height < 2) height = textHeight(display);
  430. if (diff > .001 || diff < -.001)
  431. updateLineHeight(node.lineObj, height);
  432. }
  433. display.viewOffset = heightAtLine(cm, getLine(doc, from));
  434. // Position the mover div to align with the current virtual scroll position
  435. display.mover.style.top = display.viewOffset + "px";
  436. return true;
  437. }
  438. function computeIntact(intact, changes) {
  439. for (var i = 0, l = changes.length || 0; i < l; ++i) {
  440. var change = changes[i], intact2 = [], diff = change.diff || 0;
  441. for (var j = 0, l2 = intact.length; j < l2; ++j) {
  442. var range = intact[j];
  443. if (change.to <= range.from && change.diff) {
  444. intact2.push({from: range.from + diff, to: range.to + diff});
  445. } else if (change.to <= range.from || change.from >= range.to) {
  446. intact2.push(range);
  447. } else {
  448. if (change.from > range.from)
  449. intact2.push({from: range.from, to: change.from});
  450. if (change.to < range.to)
  451. intact2.push({from: change.to + diff, to: range.to + diff});
  452. }
  453. }
  454. intact = intact2;
  455. }
  456. return intact;
  457. }
  458. function getDimensions(cm) {
  459. var d = cm.display, left = {}, width = {};
  460. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  461. left[cm.options.gutters[i]] = n.offsetLeft;
  462. width[cm.options.gutters[i]] = n.offsetWidth;
  463. }
  464. return {fixedPos: compensateForHScroll(d),
  465. gutterTotalWidth: d.gutters.offsetWidth,
  466. gutterLeft: left,
  467. gutterWidth: width,
  468. wrapperWidth: d.wrapper.clientWidth};
  469. }
  470. function patchDisplay(cm, from, to, intact, updateNumbersFrom) {
  471. var dims = getDimensions(cm);
  472. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  473. // IE does bad things to nodes when .innerHTML = "" is used on a parent
  474. // we still need widgets and markers intact to add back to the new content later
  475. if (!intact.length && !ie && (!webkit || !cm.display.currentWheelTarget))
  476. removeChildren(display.lineDiv);
  477. var container = display.lineDiv, cur = container.firstChild;
  478. function rm(node) {
  479. var next = node.nextSibling;
  480. if (webkit && mac && cm.display.currentWheelTarget == node) {
  481. node.style.display = "none";
  482. node.lineObj = null;
  483. } else {
  484. container.removeChild(node);
  485. }
  486. return next;
  487. }
  488. var nextIntact = intact.shift(), lineNo = from;
  489. cm.view.doc.iter(from, to, function(line) {
  490. if (nextIntact && nextIntact.to == lineNo) nextIntact = intact.shift();
  491. if (lineIsHidden(line)) {
  492. if (line.height != 0) updateLineHeight(line, 0);
  493. } else if (nextIntact && nextIntact.from <= lineNo && nextIntact.to > lineNo) {
  494. // This line is intact. Skip to the actual node. Update its
  495. // line number if needed.
  496. while (cur.lineObj != line) cur = rm(cur);
  497. if (lineNumbers && updateNumbersFrom <= lineNo && cur.lineNumber)
  498. setTextContent(cur.lineNumber, lineNumberFor(cm.options, lineNo));
  499. cur = cur.nextSibling;
  500. } else {
  501. // This line needs to be generated.
  502. var lineNode = buildLineElement(cm, line, lineNo, dims);
  503. container.insertBefore(lineNode, cur);
  504. lineNode.lineObj = line;
  505. }
  506. ++lineNo;
  507. });
  508. while (cur) cur = rm(cur);
  509. }
  510. function buildLineElement(cm, line, lineNo, dims) {
  511. var lineElement = lineContent(cm, line);
  512. var markers = line.gutterMarkers, display = cm.display;
  513. if (!cm.options.lineNumbers && !markers && !line.bgClass && !line.wrapClass &&
  514. (!line.widgets || !line.widgets.length)) return lineElement;
  515. // Lines with gutter elements or a background class need
  516. // to be wrapped again, and have the extra elements added
  517. // to the wrapper div
  518. var wrap = elt("div", null, line.wrapClass, "position: relative");
  519. if (cm.options.lineNumbers || markers) {
  520. var gutterWrap = wrap.appendChild(elt("div", null, null, "position: absolute; left: " +
  521. dims.fixedPos + "px"));
  522. wrap.alignable = [gutterWrap];
  523. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  524. wrap.lineNumber = gutterWrap.appendChild(
  525. elt("div", lineNumberFor(cm.options, lineNo),
  526. "CodeMirror-linenumber CodeMirror-gutter-elt",
  527. "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
  528. + display.lineNumInnerWidth + "px"));
  529. if (markers)
  530. for (var k = 0; k < cm.options.gutters.length; ++k) {
  531. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
  532. if (found)
  533. gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
  534. dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
  535. }
  536. }
  537. // Kludge to make sure the styled element lies behind the selection (by z-index)
  538. if (line.bgClass)
  539. wrap.appendChild(elt("div", "\u00a0", line.bgClass + " CodeMirror-linebackground"));
  540. wrap.appendChild(lineElement);
  541. if (line.widgets)
  542. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  543. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  544. node.widget = widget;
  545. if (widget.noHScroll) {
  546. (wrap.alignable || (wrap.alignable = [])).push(node);
  547. var width = dims.wrapperWidth;
  548. node.style.left = dims.fixedPos + "px";
  549. if (!widget.coverGutter) {
  550. width -= dims.gutterTotalWidth;
  551. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  552. }
  553. node.style.width = width + "px";
  554. }
  555. if (widget.coverGutter) {
  556. node.style.zIndex = 5;
  557. node.style.position = "relative";
  558. if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
  559. }
  560. if (widget.above)
  561. wrap.insertBefore(node, cm.options.lineNumbers && line.height != 0 ? gutterWrap : lineElement);
  562. else
  563. wrap.appendChild(node);
  564. }
  565. if (ie_lt8) wrap.style.zIndex = 2;
  566. return wrap;
  567. }
  568. // SELECTION / CURSOR
  569. function updateSelection(cm) {
  570. var display = cm.display;
  571. var collapsed = posEq(cm.view.sel.from, cm.view.sel.to);
  572. if (collapsed || cm.options.showCursorWhenSelecting)
  573. updateSelectionCursor(cm);
  574. else
  575. display.cursor.style.display = display.otherCursor.style.display = "none";
  576. if (!collapsed)
  577. updateSelectionRange(cm);
  578. else
  579. display.selectionDiv.style.display = "none";
  580. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  581. var headPos = cursorCoords(cm, cm.view.sel.head, "div");
  582. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  583. display.inputDiv.style.top = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  584. headPos.top + lineOff.top - wrapOff.top)) + "px";
  585. display.inputDiv.style.left = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  586. headPos.left + lineOff.left - wrapOff.left)) + "px";
  587. }
  588. // No selection, plain cursor
  589. function updateSelectionCursor(cm) {
  590. var display = cm.display, pos = cursorCoords(cm, cm.view.sel.head, "div");
  591. display.cursor.style.left = pos.left + "px";
  592. display.cursor.style.top = pos.top + "px";
  593. display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  594. display.cursor.style.display = "";
  595. if (pos.other) {
  596. display.otherCursor.style.display = "";
  597. display.otherCursor.style.left = pos.other.left + "px";
  598. display.otherCursor.style.top = pos.other.top + "px";
  599. display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  600. } else { display.otherCursor.style.display = "none"; }
  601. }
  602. // Highlight selection
  603. function updateSelectionRange(cm) {
  604. var display = cm.display, doc = cm.view.doc, sel = cm.view.sel;
  605. var fragment = document.createDocumentFragment();
  606. var clientWidth = display.lineSpace.offsetWidth, pl = paddingLeft(cm.display);
  607. function add(left, top, width, bottom) {
  608. if (top < 0) top = 0;
  609. fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
  610. "px; top: " + top + "px; width: " + (width == null ? clientWidth - left : width) +
  611. "px; height: " + (bottom - top) + "px"));
  612. }
  613. function drawForLine(line, fromArg, toArg, retTop) {
  614. var lineObj = getLine(doc, line);
  615. var lineLen = lineObj.text.length, rVal = retTop ? Infinity : -Infinity;
  616. function coords(ch) {
  617. return charCoords(cm, {line: line, ch: ch}, "div", lineObj);
  618. }
  619. iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
  620. var leftPos = coords(dir == "rtl" ? to - 1 : from);
  621. var rightPos = coords(dir == "rtl" ? from : to - 1);
  622. var left = leftPos.left, right = rightPos.right;
  623. if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
  624. add(left, leftPos.top, null, leftPos.bottom);
  625. left = pl;
  626. if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
  627. }
  628. if (toArg == null && to == lineLen) right = clientWidth;
  629. if (fromArg == null && from == 0) left = pl;
  630. rVal = retTop ? Math.min(rightPos.top, rVal) : Math.max(rightPos.bottom, rVal);
  631. if (left < pl + 1) left = pl;
  632. add(left, rightPos.top, right - left, rightPos.bottom);
  633. });
  634. return rVal;
  635. }
  636. if (sel.from.line == sel.to.line) {
  637. drawForLine(sel.from.line, sel.from.ch, sel.to.ch);
  638. } else {
  639. var fromObj = getLine(doc, sel.from.line);
  640. var cur = fromObj, merged, path = [sel.from.line, sel.from.ch], singleLine;
  641. while (merged = collapsedSpanAtEnd(cur)) {
  642. var found = merged.find();
  643. path.push(found.from.ch, found.to.line, found.to.ch);
  644. if (found.to.line == sel.to.line) {
  645. path.push(sel.to.ch);
  646. singleLine = true;
  647. break;
  648. }
  649. cur = getLine(doc, found.to.line);
  650. }
  651. // This is a single, merged line
  652. if (singleLine) {
  653. for (var i = 0; i < path.length; i += 3)
  654. drawForLine(path[i], path[i+1], path[i+2]);
  655. } else {
  656. var middleTop, middleBot, toObj = getLine(doc, sel.to.line);
  657. if (sel.from.ch)
  658. // Draw the first line of selection.
  659. middleTop = drawForLine(sel.from.line, sel.from.ch, null, false);
  660. else
  661. // Simply include it in the middle block.
  662. middleTop = heightAtLine(cm, fromObj) - display.viewOffset;
  663. if (!sel.to.ch)
  664. middleBot = heightAtLine(cm, toObj) - display.viewOffset;
  665. else
  666. middleBot = drawForLine(sel.to.line, collapsedSpanAtStart(toObj) ? null : 0, sel.to.ch, true);
  667. if (middleTop < middleBot) add(pl, middleTop, null, middleBot);
  668. }
  669. }
  670. removeChildrenAndAdd(display.selectionDiv, fragment);
  671. display.selectionDiv.style.display = "";
  672. }
  673. // Cursor-blinking
  674. function restartBlink(cm) {
  675. var display = cm.display;
  676. clearInterval(display.blinker);
  677. var on = true;
  678. display.cursor.style.visibility = display.otherCursor.style.visibility = "";
  679. display.blinker = setInterval(function() {
  680. if (!display.cursor.offsetHeight) return;
  681. display.cursor.style.visibility = display.otherCursor.style.visibility = (on = !on) ? "" : "hidden";
  682. }, cm.options.cursorBlinkRate);
  683. }
  684. // HIGHLIGHT WORKER
  685. function startWorker(cm, time) {
  686. if (cm.view.frontier < cm.display.showingTo)
  687. cm.view.highlight.set(time, bind(highlightWorker, cm));
  688. }
  689. function highlightWorker(cm) {
  690. var view = cm.view, doc = view.doc;
  691. if (view.frontier >= cm.display.showingTo) return;
  692. var end = +new Date + cm.options.workTime;
  693. var state = copyState(view.mode, getStateBefore(cm, view.frontier));
  694. var changed = [], prevChange;
  695. doc.iter(view.frontier, Math.min(doc.size, cm.display.showingTo + 500), function(line) {
  696. if (view.frontier >= cm.display.showingFrom) { // Visible
  697. if (highlightLine(cm, line, state) && view.frontier >= cm.display.showingFrom) {
  698. if (prevChange && prevChange.end == view.frontier) prevChange.end++;
  699. else changed.push(prevChange = {start: view.frontier, end: view.frontier + 1});
  700. }
  701. line.stateAfter = copyState(view.mode, state);
  702. } else {
  703. processLine(cm, line, state);
  704. line.stateAfter = view.frontier % 5 == 0 ? copyState(view.mode, state) : null;
  705. }
  706. ++view.frontier;
  707. if (+new Date > end) {
  708. startWorker(cm, cm.options.workDelay);
  709. return true;
  710. }
  711. });
  712. if (changed.length)
  713. operation(cm, function() {
  714. for (var i = 0; i < changed.length; ++i)
  715. regChange(this, changed[i].start, changed[i].end);
  716. })();
  717. }
  718. // Finds the line to start with when starting a parse. Tries to
  719. // find a line with a stateAfter, so that it can start with a
  720. // valid state. If that fails, it returns the line with the
  721. // smallest indentation, which tends to need the least context to
  722. // parse correctly.
  723. function findStartLine(cm, n) {
  724. var minindent, minline, doc = cm.view.doc;
  725. for (var search = n, lim = n - 100; search > lim; --search) {
  726. if (search == 0) return 0;
  727. var line = getLine(doc, search-1);
  728. if (line.stateAfter) return search;
  729. var indented = countColumn(line.text, null, cm.options.tabSize);
  730. if (minline == null || minindent > indented) {
  731. minline = search - 1;
  732. minindent = indented;
  733. }
  734. }
  735. return minline;
  736. }
  737. function getStateBefore(cm, n) {
  738. var view = cm.view;
  739. var pos = findStartLine(cm, n), state = pos && getLine(view.doc, pos-1).stateAfter;
  740. if (!state) state = startState(view.mode);
  741. else state = copyState(view.mode, state);
  742. view.doc.iter(pos, n, function(line) {
  743. processLine(cm, line, state);
  744. var save = pos == n - 1 || pos % 5 == 0 || pos >= view.showingFrom && pos < view.showingTo;
  745. line.stateAfter = save ? copyState(view.mode, state) : null;
  746. ++pos;
  747. });
  748. return state;
  749. }
  750. // POSITION MEASUREMENT
  751. function paddingTop(display) {return display.lineSpace.offsetTop;}
  752. function paddingLeft(display) {
  753. var e = removeChildrenAndAdd(display.measure, elt("pre")).appendChild(elt("span", "x"));
  754. return e.offsetLeft;
  755. }
  756. function measureChar(cm, line, ch, data) {
  757. var data = data || measureLine(cm, line), dir = -1;
  758. for (var pos = ch;; pos += dir) {
  759. var r = data[pos];
  760. if (r) break;
  761. if (dir < 0 && pos == 0) dir = 1;
  762. }
  763. return {left: pos < ch ? r.right : r.left,
  764. right: pos > ch ? r.left : r.right,
  765. top: r.top, bottom: r.bottom};
  766. }
  767. function measureLine(cm, line) {
  768. // First look in the cache
  769. var display = cm.display, cache = cm.display.measureLineCache;
  770. for (var i = 0; i < cache.length; ++i) {
  771. var memo = cache[i];
  772. if (memo.text == line.text && memo.markedSpans == line.markedSpans &&
  773. display.scroller.clientWidth == memo.width)
  774. return memo.measure;
  775. }
  776. var measure = measureLineInner(cm, line);
  777. // Store result in the cache
  778. var memo = {text: line.text, width: display.scroller.clientWidth,
  779. markedSpans: line.markedSpans, measure: measure};
  780. if (cache.length == 16) cache[++display.measureLineCachePos % 16] = memo;
  781. else cache.push(memo);
  782. return measure;
  783. }
  784. function measureLineInner(cm, line) {
  785. var display = cm.display, measure = emptyArray(line.text.length);
  786. var pre = lineContent(cm, line, measure);
  787. // IE does not cache element positions of inline elements between
  788. // calls to getBoundingClientRect. This makes the loop below,
  789. // which gathers the positions of all the characters on the line,
  790. // do an amount of layout work quadratic to the number of
  791. // characters. When line wrapping is off, we try to improve things
  792. // by first subdividing the line into a bunch of inline blocks, so
  793. // that IE can reuse most of the layout information from caches
  794. // for those blocks. This does interfere with line wrapping, so it
  795. // doesn't work when wrapping is on, but in that case the
  796. // situation is slightly better, since IE does cache line-wrapping
  797. // information and only recomputes per-line.
  798. if (ie && !ie_lt8 && !cm.options.lineWrapping && pre.childNodes.length > 100) {
  799. var fragment = document.createDocumentFragment();
  800. var chunk = 10, n = pre.childNodes.length;
  801. for (var i = 0, chunks = Math.ceil(n / chunk); i < chunks; ++i) {
  802. var wrap = elt("div", null, null, "display: inline-block");
  803. for (var j = 0; j < chunk && n; ++j) {
  804. wrap.appendChild(pre.firstChild);
  805. --n;
  806. }
  807. fragment.appendChild(wrap);
  808. }
  809. pre.appendChild(fragment);
  810. }
  811. removeChildrenAndAdd(display.measure, pre);
  812. var outer = display.lineDiv.getBoundingClientRect();
  813. var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHeight;
  814. for (var i = 0, cur; i < measure.length; ++i) if (cur = measure[i]) {
  815. var size = cur.getBoundingClientRect();
  816. var top = Math.max(0, size.top - outer.top), bot = Math.min(size.bottom - outer.top, maxBot);
  817. for (var j = 0; j < vranges.length; j += 2) {
  818. var rtop = vranges[j], rbot = vranges[j+1];
  819. if (rtop > bot || rbot < top) continue;
  820. if (rtop <= top && rbot >= bot ||
  821. top <= rtop && bot >= rbot ||
  822. Math.min(bot, rbot) - Math.max(top, rtop) >= (bot - top) >> 1) {
  823. vranges[j] = Math.min(top, rtop);
  824. vranges[j+1] = Math.max(bot, rbot);
  825. break;
  826. }
  827. }
  828. if (j == vranges.length) vranges.push(top, bot);
  829. data[i] = {left: size.left - outer.left, right: size.right - outer.left, top: j};
  830. }
  831. for (var i = 0, cur; i < data.length; ++i) if (cur = data[i]) {
  832. var vr = cur.top;
  833. cur.top = vranges[vr]; cur.bottom = vranges[vr+1];
  834. }
  835. return data;
  836. }
  837. function clearCaches(cm) {
  838. cm.display.measureLineCache.length = cm.display.measureLineCachePos = 0;
  839. cm.display.cachedCharWidth = cm.display.cachedTextHeight = null;
  840. cm.view.maxLineChanged = true;
  841. }
  842. // Context is one of "line", "div" (display.lineDiv), "local"/null (editor), or "page"
  843. function intoCoordSystem(cm, lineObj, rect, context) {
  844. if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
  845. var size = lineObj.widgets[i].node.offsetHeight;
  846. rect.top += size; rect.bottom += size;
  847. }
  848. if (context == "line") return rect;
  849. if (!context) context = "local";
  850. var yOff = heightAtLine(cm, lineObj);
  851. if (context != "local") yOff -= cm.display.viewOffset;
  852. if (context == "page") {
  853. var lOff = cm.display.lineSpace.getBoundingClientRect();
  854. yOff += lOff.top + (window.pageYOffset || (document.documentElement || document.body).scrollTop);
  855. var xOff = lOff.left + (window.pageXOffset || (document.documentElement || document.body).scrollLeft);
  856. rect.left += xOff; rect.right += xOff;
  857. }
  858. rect.top += yOff; rect.bottom += yOff;
  859. return rect;
  860. }
  861. function charCoords(cm, pos, context, lineObj) {
  862. if (!lineObj) lineObj = getLine(cm.view.doc, pos.line);
  863. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch), context);
  864. }
  865. function cursorCoords(cm, pos, context, lineObj, measurement) {
  866. lineObj = lineObj || getLine(cm.view.doc, pos.line);
  867. if (!measurement) measurement = measureLine(cm, lineObj);
  868. function get(ch, right) {
  869. var m = measureChar(cm, lineObj, ch, measurement);
  870. if (right) m.left = m.right; else m.right = m.left;
  871. return intoCoordSystem(cm, lineObj, m, context);
  872. }
  873. var order = getOrder(lineObj), ch = pos.ch;
  874. if (!order) return get(ch);
  875. var main, other, linedir = order[0].level;
  876. for (var i = 0; i < order.length; ++i) {
  877. var part = order[i], rtl = part.level % 2, nb, here;
  878. if (part.from < ch && part.to > ch) return get(ch, rtl);
  879. var left = rtl ? part.to : part.from, right = rtl ? part.from : part.to;
  880. if (left == ch) {
  881. // Opera and IE return bogus offsets and widths for edges
  882. // where the direction flips, but only for the side with the
  883. // lower level. So we try to use the side with the higher
  884. // level.
  885. if (i && part.level < (nb = order[i-1]).level) here = get(nb.level % 2 ? nb.from : nb.to - 1, true);
  886. else here = get(rtl && part.from != part.to ? ch - 1 : ch);
  887. if (rtl == linedir) main = here; else other = here;
  888. } else if (right == ch) {
  889. var nb = i < order.length - 1 && order[i+1];
  890. if (!rtl && nb && nb.from == nb.to) continue;
  891. if (nb && part.level < nb.level) here = get(nb.level % 2 ? nb.to - 1 : nb.from);
  892. else here = get(rtl ? ch : ch - 1, true);
  893. if (rtl == linedir) main = here; else other = here;
  894. }
  895. }
  896. if (linedir && !ch) other = get(order[0].to - 1);
  897. if (!main) return other;
  898. if (other) main.other = other;
  899. return main;
  900. }
  901. // Coords must be lineSpace-local
  902. function coordsChar(cm, x, y) {
  903. var doc = cm.view.doc;
  904. y += cm.display.viewOffset;
  905. if (y < 0) return {line: 0, ch: 0, outside: true};
  906. var lineNo = lineAtHeight(doc, y);
  907. if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc, doc.size - 1).text.length};
  908. if (x < 0) x = 0;
  909. for (;;) {
  910. var lineObj = getLine(doc, lineNo);
  911. var found = coordsCharInner(cm, lineObj, lineNo, x, y);
  912. var merged = collapsedSpanAtEnd(lineObj);
  913. if (merged && found.ch == lineRight(lineObj))
  914. lineNo = merged.find().to.line;
  915. else
  916. return found;
  917. }
  918. }
  919. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  920. var innerOff = y - heightAtLine(cm, lineObj);
  921. var wrongLine = false, cWidth = cm.display.wrapper.clientWidth;
  922. var measurement = measureLine(cm, lineObj);
  923. function getX(ch) {
  924. var sp = cursorCoords(cm, {line: lineNo, ch: ch}, "line",
  925. lineObj, measurement);
  926. wrongLine = true;
  927. if (innerOff > sp.bottom) return Math.max(0, sp.left - cWidth);
  928. else if (innerOff < sp.top) return sp.left + cWidth;
  929. else wrongLine = false;
  930. return sp.left;
  931. }
  932. var bidi = getOrder(lineObj), dist = lineObj.text.length;
  933. var from = lineLeft(lineObj), to = lineRight(lineObj);
  934. var fromX = paddingLeft(cm.display), toX = getX(to);
  935. if (x > toX) return {line: lineNo, ch: to, outside: wrongLine};
  936. // Do a binary search between these bounds.
  937. for (;;) {
  938. if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
  939. var after = x - fromX < toX - x, ch = after ? from : to;
  940. while (isExtendingChar.test(lineObj.text.charAt(ch))) ++ch;
  941. return {line: lineNo, ch: ch, after: after, outside: wrongLine};
  942. }
  943. var step = Math.ceil(dist / 2), middle = from + step;
  944. if (bidi) {
  945. middle = from;
  946. for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
  947. }
  948. var middleX = getX(middle);
  949. if (middleX > x) {to = middle; toX = middleX; if (wrongLine) toX += 1000; dist -= step;}
  950. else {from = middle; fromX = middleX; dist = step;}
  951. }
  952. }
  953. var measureText;
  954. function textHeight(display) {
  955. if (display.cachedTextHeight != null) return display.cachedTextHeight;
  956. if (measureText == null) {
  957. measureText = elt("pre");
  958. // Measure a bunch of lines, for browsers that compute
  959. // fractional heights.
  960. for (var i = 0; i < 49; ++i) {
  961. measureText.appendChild(document.createTextNode("x"));
  962. measureText.appendChild(elt("br"));
  963. }
  964. measureText.appendChild(document.createTextNode("x"));
  965. }
  966. removeChildrenAndAdd(display.measure, measureText);
  967. var height = measureText.offsetHeight / 50;
  968. if (height > 3) display.cachedTextHeight = height;
  969. removeChildren(display.measure);
  970. return height || 1;
  971. }
  972. function charWidth(display) {
  973. if (display.cachedCharWidth != null) return display.cachedCharWidth;
  974. var anchor = elt("span", "x");
  975. var pre = elt("pre", [anchor]);
  976. removeChildrenAndAdd(display.measure, pre);
  977. var width = anchor.offsetWidth;
  978. if (width > 2) display.cachedCharWidth = width;
  979. return width || 10;
  980. }
  981. // OPERATIONS
  982. // Operations are used to wrap changes in such a way that each
  983. // change won't have to update the cursor and display (which would
  984. // be awkward, slow, and error-prone), but instead updates are
  985. // batched and then all combined and executed at once.
  986. function startOperation(cm) {
  987. if (cm.curOp) ++cm.curOp.depth;
  988. else cm.curOp = {
  989. // Nested operations delay update until the outermost one
  990. // finishes.
  991. depth: 1,
  992. // An array of ranges of lines that have to be updated. See
  993. // updateDisplay.
  994. changes: [],
  995. delayedCallbacks: [],
  996. updateInput: null,
  997. userSelChange: null,
  998. textChanged: null,
  999. selectionChanged: false,
  1000. updateMaxLine: false,
  1001. id: ++cm.nextOpId
  1002. };
  1003. }
  1004. function endOperation(cm) {
  1005. var op = cm.curOp;
  1006. if (--op.depth) return;
  1007. cm.curOp = null;
  1008. var view = cm.view, display = cm.display;
  1009. if (op.updateMaxLine) computeMaxLength(view);
  1010. if (view.maxLineChanged && !cm.options.lineWrapping) {
  1011. var width = measureChar(cm, view.maxLine, view.maxLine.text.length).right;
  1012. display.sizer.style.minWidth = (width + 3 + scrollerCutOff) + "px";
  1013. view.maxLineChanged = false;
  1014. }
  1015. var newScrollPos, updated;
  1016. if (op.selectionChanged) {
  1017. var coords = cursorCoords(cm, view.sel.head);
  1018. newScrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom);
  1019. }
  1020. if (op.changes.length || newScrollPos && newScrollPos.scrollTop != null)
  1021. updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrollTop);
  1022. if (!updated && op.selectionChanged) updateSelection(cm);
  1023. if (newScrollPos) scrollCursorIntoView(cm);
  1024. if (op.selectionChanged) restartBlink(cm);
  1025. if (view.focused && op.updateInput)
  1026. resetInput(cm, op.userSelChange);
  1027. if (op.textChanged)
  1028. signal(cm, "change", cm, op.textChanged);
  1029. if (op.selectionChanged) signal(cm, "cursorActivity", cm);
  1030. for (var i = 0; i < op.delayedCallbacks.length; ++i) op.delayedCallbacks[i](cm);
  1031. }
  1032. // Wraps a function in an operation. Returns the wrapped function.
  1033. function operation(cm1, f) {
  1034. return function() {
  1035. var cm = cm1 || this;
  1036. startOperation(cm);
  1037. try {var result = f.apply(cm, arguments);}
  1038. finally {endOperation(cm);}
  1039. return result;
  1040. };
  1041. }
  1042. function regChange(cm, from, to, lendiff) {
  1043. cm.curOp.changes.push({from: from, to: to, diff: lendiff});
  1044. }
  1045. // INPUT HANDLING
  1046. function slowPoll(cm) {
  1047. if (cm.view.pollingFast) return;
  1048. cm.display.poll.set(cm.options.pollInterval, function() {
  1049. readInput(cm);
  1050. if (cm.view.focused) slowPoll(cm);
  1051. });
  1052. }
  1053. function fastPoll(cm) {
  1054. var missed = false;
  1055. cm.display.pollingFast = true;
  1056. function p() {
  1057. var changed = readInput(cm);
  1058. if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);}
  1059. else {cm.display.pollingFast = false; slowPoll(cm);}
  1060. }
  1061. cm.display.poll.set(20, p);
  1062. }
  1063. // prevInput is a hack to work with IME. If we reset the textarea
  1064. // on every change, that breaks IME. So we look for changes
  1065. // compared to the previous content instead. (Modern browsers have
  1066. // events that indicate IME taking place, but these are not widely
  1067. // supported or compatible enough yet to rely on.)
  1068. function readInput(cm) {
  1069. var input = cm.display.input, prevInput = cm.display.prevInput, view = cm.view, sel = view.sel;
  1070. if (!view.focused || hasSelection(input) || isReadOnly(cm)) return false;
  1071. var text = input.value;
  1072. if (text == prevInput && posEq(sel.from, sel.to)) return false;
  1073. startOperation(cm);
  1074. view.sel.shift = false;
  1075. var same = 0, l = Math.min(prevInput.length, text.length);
  1076. while (same < l && prevInput[same] == text[same]) ++same;
  1077. var from = sel.from, to = sel.to;
  1078. if (same < prevInput.length)
  1079. from = {line: from.line, ch: from.ch - (prevInput.length - same)};
  1080. else if (view.overwrite && posEq(from, to) && !cm.display.pasteIncoming)
  1081. to = {line: to.line, ch: Math.min(getLine(cm.view.doc, to.line).text.length, to.ch + (text.length - same))};
  1082. var updateInput = cm.curOp.updateInput;
  1083. updateDoc(cm, from, to, splitLines(text.slice(same)), "end",
  1084. cm.display.pasteIncoming ? "paste" : "input", {from: from, to: to});
  1085. cm.curOp.updateInput = updateInput;
  1086. if (text.length > 1000) input.value = cm.display.prevInput = "";
  1087. else cm.display.prevInput = text;
  1088. endOperation(cm);
  1089. cm.display.pasteIncoming = false;
  1090. return true;
  1091. }
  1092. function resetInput(cm, user) {
  1093. var view = cm.view, minimal, selected;
  1094. if (!posEq(view.sel.from, view.sel.to)) {
  1095. cm.display.prevInput = "";
  1096. minimal = hasCopyEvent &&
  1097. (view.sel.to.line - view.sel.from.line > 100 || (selected = cm.getSelection()).length > 1000);
  1098. if (minimal) cm.display.input.value = "-";
  1099. else cm.display.input.value = selected || cm.getSelection();
  1100. if (view.focused) selectInput(cm.display.input);
  1101. } else if (user) cm.display.prevInput = cm.display.input.value = "";
  1102. cm.display.inaccurateSelection = minimal;
  1103. }
  1104. function focusInput(cm) {
  1105. if (cm.options.readOnly != "nocursor" && (ie || document.activeElement != cm.display.input))
  1106. cm.display.input.focus();
  1107. }
  1108. function isReadOnly(cm) {
  1109. return cm.options.readOnly || cm.view.cantEdit;
  1110. }
  1111. // EVENT HANDLERS
  1112. function registerEventHandlers(cm) {
  1113. var d = cm.display;
  1114. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  1115. on(d.scroller, "dblclick", operation(cm, e_preventDefault));
  1116. on(d.lineSpace, "selectstart", function(e) {
  1117. if (!mouseEventInWidget(d, e)) e_preventDefault(e);
  1118. });
  1119. // Gecko browsers fire contextmenu *after* opening the menu, at
  1120. // which point we can't mess with it anymore. Context menu is
  1121. // handled in onMouseDown for Gecko.
  1122. if (!gecko) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
  1123. on(d.scroller, "scroll", function() {
  1124. setScrollTop(cm, d.scroller.scrollTop);
  1125. setScrollLeft(cm, d.scroller.scrollLeft, true);
  1126. signal(cm, "scroll", cm);
  1127. });
  1128. on(d.scrollbarV, "scroll", function() {
  1129. setScrollTop(cm, d.scrollbarV.scrollTop);
  1130. });
  1131. on(d.scrollbarH, "scroll", function() {
  1132. setScrollLeft(cm, d.scrollbarH.scrollLeft);
  1133. });
  1134. on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
  1135. on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
  1136. function reFocus() { if (cm.view.focused) setTimeout(bind(focusInput, cm), 0); }
  1137. on(d.scrollbarH, "mousedown", reFocus);
  1138. on(d.scrollbarV, "mousedown", reFocus);
  1139. // Prevent wrapper from ever scrolling
  1140. on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  1141. on(window, "resize", function resizeHandler() {
  1142. // Might be a text scaling operation, clear size caches.
  1143. d.cachedCharWidth = d.cachedTextHeight = null;
  1144. clearCaches(cm);
  1145. if (d.wrapper.parentNode) updateDisplay(cm, true);
  1146. else off(window, "resize", resizeHandler);
  1147. });
  1148. on(d.input, "keyup", operation(cm, function(e) {
  1149. if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
  1150. if (e_prop(e, "keyCode") == 16) cm.view.sel.shift = false;
  1151. }));
  1152. on(d.input, "input", bind(fastPoll, cm));
  1153. on(d.input, "keydown", operation(cm, onKeyDown));
  1154. on(d.input, "keypress", operation(cm, onKeyPress));
  1155. on(d.input, "focus", bind(onFocus, cm));
  1156. on(d.input, "blur", bind(onBlur, cm));
  1157. function drag_(e) {
  1158. if (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return;
  1159. e_stop(e);
  1160. }
  1161. if (cm.options.dragDrop) {
  1162. on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});
  1163. on(d.scroller, "dragenter", drag_);
  1164. on(d.scroller, "dragover", drag_);
  1165. on(d.scroller, "drop", operation(cm, onDrop));
  1166. }
  1167. on(d.scroller, "paste", function(){focusInput(cm); fastPoll(cm);});
  1168. on(d.input, "paste", function() {
  1169. d.pasteIncoming = true;
  1170. fastPoll(cm);
  1171. });
  1172. function prepareCopy() {
  1173. if (d.inaccurateSelection) {
  1174. d.prevInput = "";
  1175. d.inaccurateSelection = false;
  1176. d.input.value = cm.getSelection();
  1177. selectInput(d.input);
  1178. }
  1179. }
  1180. on(d.input, "cut", prepareCopy);
  1181. on(d.input, "copy", prepareCopy);
  1182. // Needed to handle Tab key in KHTML
  1183. if (khtml) on(d.sizer, "mouseup", function() {
  1184. if (document.activeElement == d.input) d.input.blur();
  1185. focusInput(cm);
  1186. });
  1187. }
  1188. function mouseEventInWidget(display, e) {
  1189. for (var n = e_target(e); n != display.wrapper; n = n.parentNode)
  1190. if (/\bCodeMirror-(?:line)?widget\b/.test(n.className) ||
  1191. n.parentNode == display.sizer && n != display.mover) return true;
  1192. }
  1193. function posFromMouse(cm, e, liberal) {
  1194. var display = cm.display;
  1195. if (!liberal) {
  1196. var target = e_target(e);
  1197. if (target == display.scrollbarH || target == display.scrollbarH.firstChild ||
  1198. target == display.scrollbarV || target == display.scrollbarV.firstChild ||
  1199. target == display.scrollbarFiller) return null;
  1200. }
  1201. var x, y, space = display.lineSpace.getBoundingClientRect();
  1202. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  1203. try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
  1204. return coordsChar(cm, x - space.left, y - space.top);
  1205. }
  1206. var lastClick, lastDoubleClick;
  1207. function onMouseDown(e) {
  1208. var cm = this, display = cm.display, view = cm.view, sel = view.sel, doc = view.doc;
  1209. sel.shift = e_prop(e, "shiftKey");
  1210. if (mouseEventInWidget(display, e)) {
  1211. if (!webkit) {
  1212. display.scroller.draggable = false;
  1213. setTimeout(function(){display.scroller.draggable = true;}, 100);
  1214. }
  1215. return;
  1216. }
  1217. if (clickInGutter(cm, e)) return;
  1218. var start = posFromMouse(cm, e);
  1219. switch (e_button(e)) {
  1220. case 3:
  1221. if (gecko) onContextMenu.call(cm, cm, e);
  1222. return;
  1223. case 2:
  1224. if (start) extendSelection(cm, start);
  1225. setTimeout(bind(focusInput, cm), 20);
  1226. e_preventDefault(e);
  1227. return;
  1228. }
  1229. // For button 1, if it was clicked inside the editor
  1230. // (posFromMouse returning non-null), we have to adjust the
  1231. // selection.
  1232. if (!start) {if (e_target(e) == display.scroller) e_preventDefault(e); return;}
  1233. if (!view.focused) onFocus(cm);
  1234. var now = +new Date, type = "single";
  1235. if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) {
  1236. type = "triple";
  1237. e_preventDefault(e);
  1238. setTimeout(bind(focusInput, cm), 20);
  1239. selectLine(cm, start.line);
  1240. } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) {
  1241. type = "double";
  1242. lastDoubleClick = {time: now, pos: start};
  1243. e_preventDefault(e);
  1244. var word = findWordAt(getLine(doc, start.line).text, start);
  1245. extendSelection(cm, word.from, word.to);
  1246. } else { lastClick = {time: now, pos: start}; }
  1247. var last = start;
  1248. if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && !posEq(sel.from, sel.to) &&
  1249. !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") {
  1250. var dragEnd = operation(cm, function(e2) {
  1251. if (webkit) display.scroller.draggable = false;
  1252. view.draggingText = false;
  1253. off(document, "mouseup", dragEnd);
  1254. off(display.scroller, "drop", dragEnd);
  1255. if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
  1256. e_preventDefault(e2);
  1257. extendSelection(cm, start);
  1258. focusInput(cm);
  1259. }
  1260. });
  1261. // Let the drag handler handle this.
  1262. if (webkit) display.scroller.draggable = true;
  1263. view.draggingText = dragEnd;
  1264. // IE's approach to draggable
  1265. if (display.scroller.dragDrop) display.scroller.dragDrop();
  1266. on(document, "mouseup", dragEnd);
  1267. on(display.scroller, "drop", dragEnd);
  1268. return;
  1269. }
  1270. e_preventDefault(e);
  1271. if (type == "single") extendSelection(cm, clipPos(doc, start));
  1272. var startstart = sel.from, startend = sel.to;
  1273. function doSelect(cur) {
  1274. if (type == "single") {
  1275. extendSelection(cm, clipPos(doc, start), cur);
  1276. return;
  1277. }
  1278. startstart = clipPos(doc, startstart);
  1279. startend = clipPos(doc, startend);
  1280. if (type == "double") {
  1281. var word = findWordAt(getLine(doc, cur.line).text, cur);
  1282. if (posLess(cur, startstart)) extendSelection(cm, word.from, startend);
  1283. else extendSelection(cm, startstart, word.to);
  1284. } else if (type == "triple") {
  1285. if (posLess(cur, startstart)) extendSelection(cm, startend, clipPos(doc, {line: cur.line, ch: 0}));
  1286. else extendSelection(cm, startstart, clipPos(doc, {line: cur.line + 1, ch: 0}));
  1287. }
  1288. }
  1289. var editorSize = display.wrapper.getBoundingClientRect();
  1290. // Used to ensure timeout re-tries don't fire when another extend
  1291. // happened in the meantime (clearTimeout isn't reliable -- at
  1292. // least on Chrome, the timeouts still happen even when cleared,
  1293. // if the clear happens after their scheduled firing time).
  1294. var counter = 0;
  1295. function extend(e) {
  1296. var curCount = ++counter;
  1297. var cur = posFromMouse(cm, e, true);
  1298. if (!cur) return;
  1299. if (!posEq(cur, last)) {
  1300. if (!view.focused) onFocus(cm);
  1301. last = cur;
  1302. doSelect(cur);
  1303. var visible = visibleLines(display, doc);
  1304. if (cur.line >= visible.to || cur.line < visible.from)
  1305. setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
  1306. } else {
  1307. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  1308. if (outside) setTimeout(operation(cm, function() {
  1309. if (counter != curCount) return;
  1310. display.scroller.scrollTop += outside;
  1311. extend(e);
  1312. }), 50);
  1313. }
  1314. }
  1315. function done(e) {
  1316. counter = Infinity;
  1317. var cur = posFromMouse(cm, e);
  1318. if (cur) doSelect(cur);
  1319. e_preventDefault(e);
  1320. focusInput(cm);
  1321. off(document, "mousemove", move);
  1322. off(document, "mouseup", up);
  1323. }
  1324. var move = operation(cm, function(e) {
  1325. if (!ie && !e_button(e)) done(e);
  1326. else extend(e);
  1327. });
  1328. var up = operation(cm, done);
  1329. on(document, "mousemove", move);
  1330. on(document, "mouseup", up);
  1331. }
  1332. function onDrop(e) {
  1333. var cm = this;
  1334. if (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return;
  1335. e_preventDefault(e);
  1336. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  1337. if (!pos || isReadOnly(cm)) return;
  1338. if (files && files.length && window.FileReader && window.File) {
  1339. var n = files.length, text = Array(n), read = 0;
  1340. var loadFile = function(file, i) {
  1341. var reader = new FileReader;
  1342. reader.onload = function() {
  1343. text[i] = reader.result;
  1344. if (++read == n) {
  1345. pos = clipPos(cm.view.doc, pos);
  1346. operation(cm, function() {
  1347. var end = replaceRange(cm, text.join(""), pos, pos, "paste");
  1348. setSelection(cm, pos, end);
  1349. })();
  1350. }
  1351. };
  1352. reader.readAsText(file);
  1353. };
  1354. for (var i = 0; i < n; ++i) loadFile(files[i], i);
  1355. } else {
  1356. // Don't do a replace if the drop happened inside of the selected text.
  1357. if (cm.view.draggingText && !(posLess(pos, cm.view.sel.from) || posLess(cm.view.sel.to, pos))) {
  1358. cm.view.draggingText(e);
  1359. if (ie) setTimeout(bind(focusInput, cm), 50);
  1360. return;
  1361. }
  1362. try {
  1363. var text = e.dataTransfer.getData("Text");
  1364. if (text) {
  1365. var curFrom = cm.view.sel.from, curTo = cm.view.sel.to;
  1366. setSelection(cm, pos, pos);
  1367. if (cm.view.draggingText) replaceRange(cm, "", curFrom, curTo, "paste");
  1368. cm.replaceSelection(text, null, "paste");
  1369. focusInput(cm);
  1370. onFocus(cm);
  1371. }
  1372. }
  1373. catch(e){}
  1374. }
  1375. }
  1376. function clickInGutter(cm, e) {
  1377. var display = cm.display;
  1378. try { var mX = e.clientX, mY = e.clientY; }
  1379. catch(e) { return false; }
  1380. if (mX >= Math.floor(display.gutters.getBoundingClientRect().right)) return false;
  1381. e_preventDefault(e);
  1382. if (!hasHandler(cm, "gutterClick")) return true;
  1383. var lineBox = display.lineDiv.getBoundingClientRect();
  1384. if (mY > lineBox.bottom) return true;
  1385. mY -= lineBox.top - display.viewOffset;
  1386. for (var i = 0; i < cm.options.gutters.length; ++i) {
  1387. var g = display.gutters.childNodes[i];
  1388. if (g && g.getBoundingClientRect().right >= mX) {
  1389. var line = lineAtHeight(cm.view.doc, mY);
  1390. var gutter = cm.options.gutters[i];
  1391. signalLater(cm, cm, "gutterClick", cm, line, gutter, e);
  1392. break;
  1393. }
  1394. }
  1395. return true;
  1396. }
  1397. function onDragStart(cm, e) {
  1398. var txt = cm.getSelection();
  1399. e.dataTransfer.setData("Text", txt);
  1400. // Use dummy image instead of default browsers image.
  1401. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  1402. if (e.dataTransfer.setDragImage && !safari)
  1403. e.dataTransfer.setDragImage(elt('img'), 0, 0);
  1404. }
  1405. function setScrollTop(cm, val) {
  1406. if (Math.abs(cm.view.scrollTop - val) < 2) return;
  1407. cm.view.scrollTop = val;
  1408. if (!gecko) updateDisplay(cm, [], val);
  1409. if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
  1410. if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val;
  1411. if (gecko) updateDisplay(cm, []);
  1412. }
  1413. function setScrollLeft(cm, val, isScroller) {
  1414. if (isScroller ? val == cm.view.scrollLeft : Math.abs(cm.view.scrollLeft - val) < 2) return;
  1415. cm.view.scrollLeft = val;
  1416. alignHorizontally(cm);
  1417. if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
  1418. if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val;
  1419. }
  1420. // Since the delta values reported on mouse wheel events are
  1421. // unstandardized between browsers and even browser versions, and
  1422. // generally horribly unpredictable, this code starts by measuring
  1423. // the scroll effect that the first few mouse wheel events have,
  1424. // and, from that, detects the way it can convert deltas to pixel
  1425. // offsets afterwards.
  1426. //
  1427. // The reason we want to know the amount a wheel event will scroll
  1428. // is that it gives us a chance to update the display before the
  1429. // actual scrolling happens, reducing flickering.
  1430. var wheelSamples = 0, wheelDX, wheelDY, wheelStartX, wheelStartY, wheelPixelsPerUnit = null;
  1431. // Fill in a browser-detected starting value on browsers where we
  1432. // know one. These don't have to be accurate -- the result of them
  1433. // being wrong would just be a slight flicker on the first wheel
  1434. // scroll (if it is large enough).
  1435. if (ie) wheelPixelsPerUnit = -.53;
  1436. else if (gecko) wheelPixelsPerUnit = 15;
  1437. else if (chrome) wheelPixelsPerUnit = -.7;
  1438. else if (safari) wheelPixelsPerUnit = -1/3;
  1439. function onScrollWheel(cm, e) {
  1440. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  1441. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
  1442. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
  1443. else if (dy == null) dy = e.wheelDelta;
  1444. // Webkit browsers on OS X abort momentum scrolls when the target
  1445. // of the scroll event is removed from the scrollable element.
  1446. // This hack (see related code in patchDisplay) makes sure the
  1447. // element is kept around.
  1448. if (dy && mac && webkit) {
  1449. for (var cur = e.target; cur != scroll; cur = cur.parentNode) {
  1450. if (cur.lineObj) {
  1451. cm.display.currentWheelTarget = cur;
  1452. break;
  1453. }
  1454. }
  1455. }
  1456. var scroll = cm.display.scroller;
  1457. // On some browsers, horizontal scrolling will cause redraws to
  1458. // happen before the gutter has been realigned, causing it to
  1459. // wriggle around in a most unseemly way. When we have an
  1460. // estimated pixels/delta value, we just handle horizontal
  1461. // scrolling entirely here. It'll be slightly off from native, but
  1462. // better than glitching out.
  1463. if (dx && !gecko && !opera && wheelPixelsPerUnit != null) {
  1464. if (dy)
  1465. setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
  1466. setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
  1467. e_preventDefault(e);
  1468. wheelStartX = null; // Abort measurement, if in progress
  1469. return;
  1470. }
  1471. if (dy && wheelPixelsPerUnit != null) {
  1472. var pixels = dy * wheelPixelsPerUnit;
  1473. var top = cm.view.scrollTop, bot = top + cm.display.wrapper.clientHeight;
  1474. if (pixels < 0) top = Math.max(0, top + pixels - 50);
  1475. else bot = Math.min(cm.view.doc.height, bot + pixels + 50);
  1476. updateDisplay(cm, [], {top: top, bottom: bot});
  1477. }
  1478. if (wheelSamples < 20) {
  1479. if (wheelStartX == null) {
  1480. wheelStartX = scroll.scrollLeft; wheelStartY = scroll.scrollTop;
  1481. wheelDX = dx; wheelDY = dy;
  1482. setTimeout(function() {
  1483. if (wheelStartX == null) return;
  1484. var movedX = scroll.scrollLeft - wheelStartX;
  1485. var movedY = scroll.scrollTop - wheelStartY;
  1486. var sample = (movedY && wheelDY && movedY / wheelDY) ||
  1487. (movedX && wheelDX && movedX / wheelDX);
  1488. wheelStartX = wheelStartY = null;
  1489. if (!sample) return;
  1490. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  1491. ++wheelSamples;
  1492. }, 200);
  1493. } else {
  1494. wheelDX += dx; wheelDY += dy;
  1495. }
  1496. }
  1497. }
  1498. function doHandleBinding(cm, bound, dropShift) {
  1499. if (typeof bound == "string") {
  1500. bound = commands[bound];
  1501. if (!bound) return false;
  1502. }
  1503. // Ensure previous input has been read, so that the handler sees a
  1504. // consistent view of the document
  1505. if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false;
  1506. var view = cm.view, prevShift = view.sel.shift;
  1507. try {
  1508. if (isReadOnly(cm)) view.suppressEdits = true;
  1509. if (dropShift) view.sel.shift = false;
  1510. bound(cm);
  1511. } catch(e) {
  1512. if (e != Pass) throw e;
  1513. return false;
  1514. } finally {
  1515. view.sel.shift = prevShift;
  1516. view.suppressEdits = false;
  1517. }
  1518. return true;
  1519. }
  1520. function allKeyMaps(cm) {
  1521. var maps = cm.view.keyMaps.slice(0);
  1522. maps.push(cm.options.keyMap);
  1523. if (cm.options.extraKeys) maps.unshift(cm.options.extraKeys);
  1524. return maps;
  1525. }
  1526. var maybeTransition;
  1527. function handleKeyBinding(cm, e) {
  1528. // Handle auto keymap transitions
  1529. var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto;
  1530. clearTimeout(maybeTransition);
  1531. if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
  1532. if (getKeyMap(cm.options.keyMap) == startMap)
  1533. cm.options.keyMap = (next.call ? next.call(null, cm) : next);
  1534. }, 50);
  1535. var name = keyNames[e_prop(e, "keyCode")], handled = false;
  1536. var flipCtrlCmd = mac && (opera || qtwebkit);
  1537. if (name == null || e.altGraphKey) return false;
  1538. if (e_prop(e, "altKey")) name = "Alt-" + name;
  1539. if (e_prop(e, flipCtrlCmd ? "metaKey" : "ctrlKey")) name = "Ctrl-" + name;
  1540. if (e_prop(e, flipCtrlCmd ? "ctrlKey" : "metaKey")) name = "Cmd-" + name;
  1541. var stopped = false;
  1542. function stop() { stopped = true; }
  1543. var keymaps = allKeyMaps(cm);
  1544. if (e_prop(e, "shiftKey")) {
  1545. handled = lookupKey("Shift-" + name, keymaps,
  1546. function(b) {return doHandleBinding(cm, b, true);}, stop)
  1547. || lookupKey(name, keymaps, function(b) {
  1548. if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(cm, b);
  1549. }, stop);
  1550. } else {
  1551. handled = lookupKey(name, keymaps,
  1552. function(b) { return doHandleBinding(cm, b); }, stop);
  1553. }
  1554. if (stopped) handled = false;
  1555. if (handled) {
  1556. e_preventDefault(e);
  1557. restartBlink(cm);
  1558. if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; }
  1559. }
  1560. return handled;
  1561. }
  1562. function handleCharBinding(cm, e, ch) {
  1563. var handled = lookupKey("'" + ch + "'", allKeyMaps(cm),
  1564. function(b) { return doHandleBinding(cm, b, true); });
  1565. if (handled) {
  1566. e_preventDefault(e);
  1567. restartBlink(cm);
  1568. }
  1569. return handled;
  1570. }
  1571. var lastStoppedKey = null;
  1572. function onKeyDown(e) {
  1573. var cm = this;
  1574. if (!cm.view.focused) onFocus(cm);
  1575. if (ie && e.keyCode == 27) { e.returnValue = false; }
  1576. if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
  1577. var code = e_prop(e, "keyCode");
  1578. // IE does strange things with escape.
  1579. cm.view.sel.shift = code == 16 || e_prop(e, "shiftKey");
  1580. // First give onKeyEvent option a chance to handle this.
  1581. var handled = handleKeyBinding(cm, e);
  1582. if (opera) {
  1583. lastStoppedKey = handled ? code : null;
  1584. // Opera has no cut event... we try to at least catch the key combo
  1585. if (!handled && code == 88 && !hasCopyEvent && e_prop(e, mac ? "metaKey" : "ctrlKey"))
  1586. cm.replaceSelection("");
  1587. }
  1588. }
  1589. function onKeyPress(e) {
  1590. var cm = this;
  1591. if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
  1592. var keyCode = e_prop(e, "keyCode"), charCode = e_prop(e, "charCode");
  1593. if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
  1594. if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return;
  1595. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  1596. if (this.options.electricChars && this.view.mode.electricChars &&
  1597. this.options.smartIndent && !isReadOnly(this) &&
  1598. this.view.mode.electricChars.indexOf(ch) > -1)
  1599. setTimeout(operation(cm, function() {indentLine(cm, cm.view.sel.to.line, "smart");}), 75);
  1600. if (handleCharBinding(cm, e, ch)) return;
  1601. fastPoll(cm);
  1602. }
  1603. function onFocus(cm) {
  1604. if (cm.options.readOnly == "nocursor") return;
  1605. if (!cm.view.focused) {
  1606. signal(cm, "focus", cm);
  1607. cm.view.focused = true;
  1608. if (cm.display.scroller.className.search(/\bCodeMirror-focused\b/) == -1)
  1609. cm.display.scroller.className += " CodeMirror-focused";
  1610. resetInput(cm, true);
  1611. }
  1612. slowPoll(cm);
  1613. restartBlink(cm);
  1614. }
  1615. function onBlur(cm) {
  1616. if (cm.view.focused) {
  1617. signal(cm, "blur", cm);
  1618. cm.view.focused = false;
  1619. cm.display.scroller.className = cm.display.scroller.className.replace(" CodeMirror-focused", "");
  1620. }
  1621. clearInterval(cm.display.blinker);
  1622. setTimeout(function() {if (!cm.view.focused) cm.view.sel.shift = false;}, 150);
  1623. }
  1624. var detectingSelectAll;
  1625. function onContextMenu(cm, e) {
  1626. var display = cm.display, sel = cm.view.sel;
  1627. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  1628. if (!pos || opera) return; // Opera is difficult.
  1629. if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
  1630. operation(cm, setSelection)(cm, pos, pos);
  1631. var oldCSS = display.input.style.cssText;
  1632. display.inputDiv.style.position = "absolute";
  1633. display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
  1634. "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; outline: none;" +
  1635. "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  1636. focusInput(cm);
  1637. resetInput(cm, true);
  1638. // Adds "Select all" to context menu in FF
  1639. if (posEq(sel.from, sel.to)) display.input.value = display.prevInput = " ";
  1640. function rehide() {
  1641. display.inputDiv.style.position = "relative";
  1642. display.input.style.cssText = oldCSS;
  1643. if (ie_lt9) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos;
  1644. slowPoll(cm);
  1645. // Try to detect the user choosing select-all
  1646. if (display.input.selectionStart != null) {
  1647. clearTimeout(detectingSelectAll);
  1648. var extval = display.input.value = " " + (posEq(sel.from, sel.to) ? "" : display.input.value), i = 0;
  1649. display.prevInput = " ";
  1650. display.input.selectionStart = 1; display.input.selectionEnd = extval.length;
  1651. detectingSelectAll = setTimeout(function poll(){
  1652. if (display.prevInput == " " && display.input.selectionStart == 0)
  1653. operation(cm, commands.selectAll)(cm);
  1654. else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500);
  1655. else resetInput(cm);
  1656. }, 200);
  1657. }
  1658. }
  1659. if (gecko) {
  1660. e_stop(e);
  1661. on(window, "mouseup", function mouseup() {
  1662. off(window, "mouseup", mouseup);
  1663. setTimeout(rehide, 20);
  1664. });
  1665. } else {
  1666. setTimeout(rehide, 50);
  1667. }
  1668. }
  1669. // UPDATING
  1670. // Replace the range from from to to by the strings in newText.
  1671. // Afterwards, set the selection to selFrom, selTo.
  1672. function updateDoc(cm, from, to, newText, selUpdate, origin) {
  1673. // Possibly split or suppress the update based on the presence
  1674. // of read-only spans in its range.
  1675. var split = sawReadOnlySpans &&
  1676. removeReadOnlyRanges(cm.view.doc, from, to);
  1677. if (split) {
  1678. for (var i = split.length - 1; i >= 1; --i)
  1679. updateDocInner(cm, split[i].from, split[i].to, [""], origin);
  1680. if (split.length)
  1681. return updateDocInner(cm, split[0].from, split[0].to, newText, selUpdate, origin);
  1682. } else {
  1683. return updateDocInner(cm, from, to, newText, selUpdate, origin);
  1684. }
  1685. }
  1686. function updateDocInner(cm, from, to, newText, selUpdate, origin) {
  1687. if (cm.view.suppressEdits) return;
  1688. var view = cm.view, doc = view.doc, old = [];
  1689. doc.iter(from.line, to.line + 1, function(line) {
  1690. old.push(newHL(line.text, line.markedSpans));
  1691. });
  1692. var startSelFrom = view.sel.from, startSelTo = view.sel.to;
  1693. var lines = updateMarkedSpans(hlSpans(old[0]), hlSpans(lst(old)), from.ch, to.ch, newText);
  1694. var retval = updateDocNoUndo(cm, from, to, lines, selUpdate, origin);
  1695. if (view.history) addChange(cm, from.line, newText.length, old, origin,
  1696. startSelFrom, startSelTo, view.sel.from, view.sel.to);
  1697. return retval;
  1698. }
  1699. function unredoHelper(cm, type) {
  1700. var doc = cm.view.doc, hist = cm.view.history;
  1701. var set = (type == "undo" ? hist.done : hist.undone).pop();
  1702. if (!set) return;
  1703. var anti = {events: [], fromBefore: set.fromAfter, toBefore: set.toAfter,
  1704. fromAfter: set.fromBefore, toAfter: set.toBefore};
  1705. for (var i = set.events.length - 1; i >= 0; i -= 1) {
  1706. hist.dirtyCounter += type == "undo" ? -1 : 1;
  1707. var change = set.events[i];
  1708. var replaced = [], end = change.start + change.added;
  1709. doc.iter(change.start, end, function(line) { replaced.push(newHL(line.text, line.markedSpans)); });
  1710. anti.events.push({start: change.start, added: change.old.length, old: replaced});
  1711. var selPos = i ? null : {from: set.fromBefore, to: set.toBefore};
  1712. updateDocNoUndo(cm, {line: change.start, ch: 0}, {line: end - 1, ch: getLine(doc, end-1).text.length},
  1713. change.old, selPos, type);
  1714. }
  1715. (type == "undo" ? hist.undone : hist.done).push(anti);
  1716. }
  1717. function updateDocNoUndo(cm, from, to, lines, selUpdate, origin) {
  1718. var view = cm.view, doc = view.doc, display = cm.display;
  1719. if (view.suppressEdits) return;
  1720. var nlines = to.line - from.line, firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  1721. var recomputeMaxLength = false, checkWidthStart = from.line;
  1722. if (!cm.options.lineWrapping) {
  1723. checkWidthStart = lineNo(visualLine(doc, firstLine));
  1724. doc.iter(checkWidthStart, to.line + 1, function(line) {
  1725. if (lineLength(doc, line) == view.maxLineLength) {
  1726. recomputeMaxLength = true;
  1727. return true;
  1728. }
  1729. });
  1730. }
  1731. var lastHL = lst(lines), th = textHeight(display);
  1732. // First adjust the line structure
  1733. if (from.ch == 0 && to.ch == 0 && hlText(lastHL) == "") {
  1734. // This is a whole-line replace. Treated specially to make
  1735. // sure line objects move the way they are supposed to.
  1736. var added = [];
  1737. for (var i = 0, e = lines.length - 1; i < e; ++i)
  1738. added.push(makeLine(hlText(lines[i]), hlSpans(lines[i]), th));
  1739. updateLine(cm, lastLine, lastLine.text, hlSpans(lastHL));
  1740. if (nlines) doc.remove(from.line, nlines, cm);
  1741. if (added.length) doc.insert(from.line, added);
  1742. } else if (firstLine == lastLine) {
  1743. if (lines.length == 1) {
  1744. updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]) +
  1745. firstLine.text.slice(to.ch), hlSpans(lines[0]));
  1746. } else {
  1747. for (var added = [], i = 1, e = lines.length - 1; i < e; ++i)
  1748. added.push(makeLine(hlText(lines[i]), hlSpans(lines[i]), th));
  1749. added.push(makeLine(hlText(lastHL) + firstLine.text.slice(to.ch), hlSpans(lastHL), th));
  1750. updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0]));
  1751. doc.insert(from.line + 1, added);
  1752. }
  1753. } else if (lines.length == 1) {
  1754. updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]) +
  1755. lastLine.text.slice(to.ch), hlSpans(lines[0]));
  1756. doc.remove(from.line + 1, nlines, cm);
  1757. } else {
  1758. var added = [];
  1759. updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0]));
  1760. updateLine(cm, lastLine, hlText(lastHL) + lastLine.text.slice(to.ch), hlSpans(lastHL));
  1761. for (var i = 1, e = lines.length - 1; i < e; ++i)
  1762. added.push(makeLine(hlText(lines[i]), hlSpans(lines[i]), th));
  1763. if (nlines > 1) doc.remove(from.line + 1, nlines - 1, cm);
  1764. doc.insert(from.line + 1, added);
  1765. }
  1766. if (cm.options.lineWrapping) {
  1767. var perLine = Math.max(5, display.scroller.clientWidth / charWidth(display) - 3);
  1768. doc.iter(from.line, from.line + lines.length, function(line) {
  1769. if (line.height == 0) return;
  1770. var guess = (Math.ceil(line.text.length / perLine) || 1) * th;
  1771. if (guess != line.height) updateLineHeight(line, guess);
  1772. });
  1773. } else {
  1774. doc.iter(checkWidthStart, from.line + lines.length, function(line) {
  1775. var len = lineLength(doc, line);
  1776. if (len > view.maxLineLength) {
  1777. view.maxLine = line;
  1778. view.maxLineLength = len;
  1779. view.maxLineChanged = true;
  1780. recomputeMaxLength = false;
  1781. }
  1782. });
  1783. if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
  1784. }
  1785. // Adjust frontier, schedule worker
  1786. view.frontier = Math.min(view.frontier, from.line);
  1787. startWorker(cm, 400);
  1788. var lendiff = lines.length - nlines - 1;
  1789. // Remember that these lines changed, for updating the display
  1790. regChange(cm, from.line, to.line + 1, lendiff);
  1791. if (hasHandler(cm, "change")) {
  1792. // Normalize lines to contain only strings, since that's what
  1793. // the change event handler expects
  1794. for (var i = 0; i < lines.length; ++i)
  1795. if (typeof lines[i] != "string") lines[i] = lines[i].text;
  1796. var changeObj = {from: from, to: to, text: lines, origin: origin};
  1797. if (cm.curOp.textChanged) {
  1798. for (var cur = cm.curOp.textChanged; cur.next; cur = cur.next) {}
  1799. cur.next = changeObj;
  1800. } else cm.curOp.textChanged = changeObj;
  1801. }
  1802. // Update the selection
  1803. var newSelFrom, newSelTo, end = {line: from.line + lines.length - 1,
  1804. ch: hlText(lastHL).length + (lines.length == 1 ? from.ch : 0)};
  1805. if (selUpdate && typeof selUpdate != "string") {
  1806. if (selUpdate.from) { newSelFrom = selUpdate.from; newSelTo = selUpdate.to; }
  1807. else newSelFrom = newSelTo = selUpdate;
  1808. } else if (selUpdate == "end") {
  1809. newSelFrom = newSelTo = end;
  1810. } else if (selUpdate == "start") {
  1811. newSelFrom = newSelTo = from;
  1812. } else if (selUpdate == "around") {
  1813. newSelFrom = from; newSelTo = end;
  1814. } else {
  1815. var adjustPos = function(pos) {
  1816. if (posLess(pos, from)) return pos;
  1817. if (!posLess(to, pos)) return end;
  1818. var line = pos.line + lendiff;
  1819. var ch = pos.ch;
  1820. if (pos.line == to.line)
  1821. ch += hlText(lastHL).length - (to.ch - (to.line == from.line ? from.ch : 0));
  1822. return {line: line, ch: ch};
  1823. };
  1824. newSelFrom = adjustPos(view.sel.from);
  1825. newSelTo = adjustPos(view.sel.to);
  1826. }
  1827. setSelection(cm, newSelFrom, newSelTo, null, true);
  1828. return end;
  1829. }
  1830. function replaceRange(cm, code, from, to, origin) {
  1831. if (!to) to = from;
  1832. if (posLess(to, from)) { var tmp = to; to = from; from = tmp; }
  1833. return updateDoc(cm, from, to, splitLines(code), null, origin);
  1834. }
  1835. // SELECTION
  1836. function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
  1837. function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
  1838. function copyPos(x) {return {line: x.line, ch: x.ch};}
  1839. function clipLine(doc, n) {return Math.max(0, Math.min(n, doc.size-1));}
  1840. function clipPos(doc, pos) {
  1841. if (pos.line < 0) return {line: 0, ch: 0};
  1842. if (pos.line >= doc.size) return {line: doc.size-1, ch: getLine(doc, doc.size-1).text.length};
  1843. var ch = pos.ch, linelen = getLine(doc, pos.line).text.length;
  1844. if (ch == null || ch > linelen) return {line: pos.line, ch: linelen};
  1845. else if (ch < 0) return {line: pos.line, ch: 0};
  1846. else return pos;
  1847. }
  1848. function isLine(doc, l) {return l >= 0 && l < doc.size;}
  1849. // If shift is held, this will move the selection anchor. Otherwise,
  1850. // it'll set the whole selection.
  1851. function extendSelection(cm, pos, other, bias) {
  1852. var sel = cm.view.sel;
  1853. if (sel.shift || sel.extend) {
  1854. var anchor = sel.anchor;
  1855. if (other) {
  1856. var posBefore = posLess(pos, anchor);
  1857. if (posBefore != posLess(other, anchor)) {
  1858. anchor = pos;
  1859. pos = other;
  1860. } else if (posBefore != posLess(pos, other)) {
  1861. pos = other;
  1862. }
  1863. }
  1864. setSelection(cm, anchor, pos, bias);
  1865. } else {
  1866. setSelection(cm, pos, other || pos, bias);
  1867. }
  1868. cm.curOp.userSelChange = true;
  1869. }
  1870. // Update the selection. Last two args are only used by
  1871. // updateDoc, since they have to be expressed in the line
  1872. // numbers before the update.
  1873. function setSelection(cm, anchor, head, bias, checkAtomic) {
  1874. cm.view.goalColumn = null;
  1875. var sel = cm.view.sel;
  1876. // Skip over atomic spans.
  1877. if (checkAtomic || !posEq(anchor, sel.anchor))
  1878. anchor = skipAtomic(cm, anchor, bias, checkAtomic != "push");
  1879. if (checkAtomic || !posEq(head, sel.head))
  1880. head = skipAtomic(cm, head, bias, checkAtomic != "push");
  1881. if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return;
  1882. sel.anchor = anchor; sel.head = head;
  1883. var inv = posLess(head, anchor);
  1884. sel.from = inv ? head : anchor;
  1885. sel.to = inv ? anchor : head;
  1886. cm.curOp.updateInput = true;
  1887. cm.curOp.selectionChanged = true;
  1888. }
  1889. function reCheckSelection(cm) {
  1890. setSelection(cm, cm.view.sel.from, cm.view.sel.to, null, "push");
  1891. }
  1892. function skipAtomic(cm, pos, bias, mayClear) {
  1893. var doc = cm.view.doc, flipped = false, curPos = pos;
  1894. var dir = bias || 1;
  1895. cm.view.cantEdit = false;
  1896. search: for (;;) {
  1897. var line = getLine(doc, curPos.line), toClear;
  1898. if (line.markedSpans) {
  1899. for (var i = 0; i < line.markedSpans.length; ++i) {
  1900. var sp = line.markedSpans[i], m = sp.marker;
  1901. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
  1902. (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
  1903. if (mayClear && m.clearOnEnter) {
  1904. (toClear || (toClear = [])).push(m);
  1905. continue;
  1906. } else if (!m.atomic) continue;
  1907. var newPos = m.find()[dir < 0 ? "from" : "to"];
  1908. if (posEq(newPos, curPos)) {
  1909. newPos.ch += dir;
  1910. if (newPos.ch < 0) {
  1911. if (newPos.line) newPos = clipPos(doc, {line: newPos.line - 1});
  1912. else newPos = null;
  1913. } else if (newPos.ch > line.text.length) {
  1914. if (newPos.line < doc.size - 1) newPos = {line: newPos.line + 1, ch: 0};
  1915. else newPos = null;
  1916. }
  1917. if (!newPos) {
  1918. if (flipped) {
  1919. // Driven in a corner -- no valid cursor position found at all
  1920. // -- try again *with* clearing, if we didn't already
  1921. if (!mayClear) return skipAtomic(cm, pos, bias, true);
  1922. // Otherwise, turn off editing until further notice, and return the start of the doc
  1923. cm.view.cantEdit = true;
  1924. return {line: 0, ch: 0};
  1925. }
  1926. flipped = true; newPos = pos; dir = -dir;
  1927. }
  1928. }
  1929. curPos = newPos;
  1930. continue search;
  1931. }
  1932. }
  1933. if (toClear) for (var i = 0; i < toClear.length; ++i) toClear[i].clear();
  1934. }
  1935. return curPos;
  1936. }
  1937. }
  1938. // SCROLLING
  1939. function scrollCursorIntoView(cm) {
  1940. var view = cm.view;
  1941. var coords = scrollPosIntoView(cm, view.sel.head);
  1942. if (!view.focused) return;
  1943. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  1944. if (coords.top + box.top < 0) doScroll = true;
  1945. else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
  1946. if (doScroll != null && !phantom) {
  1947. var hidden = display.cursor.style.display == "none";
  1948. if (hidden) {
  1949. display.cursor.style.display = "";
  1950. display.cursor.style.left = coords.left + "px";
  1951. display.cursor.style.top = (coords.top - display.viewOffset) + "px";
  1952. }
  1953. display.cursor.scrollIntoView(doScroll);
  1954. if (hidden) display.cursor.style.display = "none";
  1955. }
  1956. }
  1957. function scrollPosIntoView(cm, pos) {
  1958. for (;;) {
  1959. var changed = false, coords = cursorCoords(cm, pos);
  1960. var scrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom);
  1961. var startTop = cm.view.scrollTop, startLeft = cm.view.scrollLeft;
  1962. if (scrollPos.scrollTop != null) {
  1963. setScrollTop(cm, scrollPos.scrollTop);
  1964. if (Math.abs(cm.view.scrollTop - startTop) > 1) changed = true;
  1965. }
  1966. if (scrollPos.scrollLeft != null) {
  1967. setScrollLeft(cm, scrollPos.scrollLeft);
  1968. if (Math.abs(cm.view.scrollLeft - startLeft) > 1) changed = true;
  1969. }
  1970. if (!changed) return coords;
  1971. }
  1972. }
  1973. function scrollIntoView(cm, x1, y1, x2, y2) {
  1974. var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
  1975. if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
  1976. if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
  1977. }
  1978. function calculateScrollPos(cm, x1, y1, x2, y2) {
  1979. var display = cm.display, pt = paddingTop(display);
  1980. y1 += pt; y2 += pt;
  1981. var screen = display.scroller.clientHeight - scrollerCutOff, screentop = display.scroller.scrollTop, result = {};
  1982. var docBottom = cm.view.doc.height + 2 * pt;
  1983. var atTop = y1 < pt + 10, atBottom = y2 + pt > docBottom - 10;
  1984. if (y1 < screentop) result.scrollTop = atTop ? 0 : Math.max(0, y1);
  1985. else if (y2 > screentop + screen) result.scrollTop = (atBottom ? docBottom : y2) - screen;
  1986. var screenw = display.scroller.clientWidth - scrollerCutOff, screenleft = display.scroller.scrollLeft;
  1987. x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth;
  1988. var gutterw = display.gutters.offsetWidth;
  1989. var atLeft = x1 < gutterw + 10;
  1990. if (x1 < screenleft + gutterw || atLeft) {
  1991. if (atLeft) x1 = 0;
  1992. result.scrollLeft = Math.max(0, x1 - 10 - gutterw);
  1993. } else if (x2 > screenw + screenleft - 3) {
  1994. result.scrollLeft = x2 + 10 - screenw;
  1995. }
  1996. return result;
  1997. }
  1998. // API UTILITIES
  1999. function indentLine(cm, n, how, aggressive) {
  2000. var doc = cm.view.doc;
  2001. if (!how) how = "add";
  2002. if (how == "smart") {
  2003. if (!cm.view.mode.indent) how = "prev";
  2004. else var state = getStateBefore(cm, n);
  2005. }
  2006. var tabSize = cm.options.tabSize;
  2007. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  2008. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  2009. if (how == "smart") {
  2010. indentation = cm.view.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  2011. if (indentation == Pass) {
  2012. if (!aggressive) return;
  2013. how = "prev";
  2014. }
  2015. }
  2016. if (how == "prev") {
  2017. if (n) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
  2018. else indentation = 0;
  2019. }
  2020. else if (how == "add") indentation = curSpace + cm.options.indentUnit;
  2021. else if (how == "subtract") indentation = curSpace - cm.options.indentUnit;
  2022. indentation = Math.max(0, indentation);
  2023. var indentString = "", pos = 0;
  2024. if (cm.options.indentWithTabs)
  2025. for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
  2026. if (pos < indentation) indentString += spaceStr(indentation - pos);
  2027. if (indentString != curSpaceString)
  2028. replaceRange(cm, indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length}, "input");
  2029. line.stateAfter = null;
  2030. }
  2031. function changeLine(cm, handle, op) {
  2032. var no = handle, line = handle, doc = cm.view.doc;
  2033. if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
  2034. else no = lineNo(handle);
  2035. if (no == null) return null;
  2036. if (op(line, no)) regChange(cm, no, no + 1);
  2037. else return null;
  2038. return line;
  2039. }
  2040. function findPosH(cm, dir, unit, visually) {
  2041. var doc = cm.view.doc, end = cm.view.sel.head, line = end.line, ch = end.ch;
  2042. var lineObj = getLine(doc, line);
  2043. function findNextLine() {
  2044. var l = line + dir;
  2045. if (l < 0 || l == doc.size) return false;
  2046. line = l;
  2047. return lineObj = getLine(doc, l);
  2048. }
  2049. function moveOnce(boundToLine) {
  2050. var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
  2051. if (next == null) {
  2052. if (!boundToLine && findNextLine()) {
  2053. if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
  2054. else ch = dir < 0 ? lineObj.text.length : 0;
  2055. } else return false;
  2056. } else ch = next;
  2057. return true;
  2058. }
  2059. if (unit == "char") moveOnce();
  2060. else if (unit == "column") moveOnce(true);
  2061. else if (unit == "word") {
  2062. var sawWord = false;
  2063. for (;;) {
  2064. if (dir < 0) if (!moveOnce()) break;
  2065. if (isWordChar(lineObj.text.charAt(ch))) sawWord = true;
  2066. else if (sawWord) {if (dir < 0) {dir = 1; moveOnce();} break;}
  2067. if (dir > 0) if (!moveOnce()) break;
  2068. }
  2069. }
  2070. return skipAtomic(cm, {line: line, ch: ch}, dir, true);
  2071. }
  2072. function findWordAt(line, pos) {
  2073. var start = pos.ch, end = pos.ch;
  2074. if (line) {
  2075. if (pos.after === false || end == line.length) --start; else ++end;
  2076. var startChar = line.charAt(start);
  2077. var check = isWordChar(startChar) ? isWordChar :
  2078. /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} :
  2079. function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
  2080. while (start > 0 && check(line.charAt(start - 1))) --start;
  2081. while (end < line.length && check(line.charAt(end))) ++end;
  2082. }
  2083. return {from: {line: pos.line, ch: start}, to: {line: pos.line, ch: end}};
  2084. }
  2085. function selectLine(cm, line) {
  2086. extendSelection(cm, {line: line, ch: 0}, clipPos(cm.view.doc, {line: line + 1, ch: 0}));
  2087. }
  2088. // PROTOTYPE
  2089. // The publicly visible API. Note that operation(null, f) means
  2090. // 'wrap f in an operation, performed on its `this` parameter'
  2091. CodeMirror.prototype = {
  2092. getValue: function(lineSep) {
  2093. var text = [], doc = this.view.doc;
  2094. doc.iter(0, doc.size, function(line) { text.push(line.text); });
  2095. return text.join(lineSep || "\n");
  2096. },
  2097. setValue: operation(null, function(code) {
  2098. var doc = this.view.doc, top = {line: 0, ch: 0}, lastLen = getLine(doc, doc.size-1).text.length;
  2099. updateDocInner(this, top, {line: doc.size - 1, ch: lastLen}, splitLines(code), top, top, "setValue");
  2100. }),
  2101. getSelection: function(lineSep) { return this.getRange(this.view.sel.from, this.view.sel.to, lineSep); },
  2102. replaceSelection: operation(null, function(code, collapse, origin) {
  2103. var sel = this.view.sel;
  2104. updateDoc(this, sel.from, sel.to, splitLines(code), collapse || "around", origin);
  2105. }),
  2106. focus: function(){window.focus(); focusInput(this); onFocus(this); fastPoll(this);},
  2107. setOption: function(option, value) {
  2108. var options = this.options, old = options[option];
  2109. if (options[option] == value && option != "mode") return;
  2110. options[option] = value;
  2111. if (optionHandlers.hasOwnProperty(option))
  2112. operation(this, optionHandlers[option])(this, value, old);
  2113. },
  2114. getOption: function(option) {return this.options[option];},
  2115. getMode: function() {return this.view.mode;},
  2116. addKeyMap: function(map) {
  2117. this.view.keyMaps.push(map);
  2118. },
  2119. removeKeyMap: function(map) {
  2120. var maps = this.view.keyMaps;
  2121. for (var i = 0; i < maps.length; ++i)
  2122. if ((typeof map == "string" ? maps[i].name : maps[i]) == map) {
  2123. maps.splice(i, 1);
  2124. return true;
  2125. }
  2126. },
  2127. undo: operation(null, function() {unredoHelper(this, "undo");}),
  2128. redo: operation(null, function() {unredoHelper(this, "redo");}),
  2129. indentLine: operation(null, function(n, dir, aggressive) {
  2130. if (typeof dir != "string") {
  2131. if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
  2132. else dir = dir ? "add" : "subtract";
  2133. }
  2134. if (isLine(this.view.doc, n)) indentLine(this, n, dir, aggressive);
  2135. }),
  2136. indentSelection: operation(null, function(how) {
  2137. var sel = this.view.sel;
  2138. if (posEq(sel.from, sel.to)) return indentLine(this, sel.from.line, how);
  2139. var e = sel.to.line - (sel.to.ch ? 0 : 1);
  2140. for (var i = sel.from.line; i <= e; ++i) indentLine(this, i, how);
  2141. }),
  2142. historySize: function() {
  2143. var hist = this.view.history;
  2144. return {undo: hist.done.length, redo: hist.undone.length};
  2145. },
  2146. clearHistory: function() {this.view.history = makeHistory();},
  2147. markClean: function() {
  2148. this.view.history.dirtyCounter = 0;
  2149. this.view.history.lastOp = this.view.history.lastOrigin = null;
  2150. },
  2151. isClean: function () {return this.view.history.dirtyCounter == 0;},
  2152. getHistory: function() {
  2153. var hist = this.view.history;
  2154. function cp(arr) {
  2155. for (var i = 0, nw = [], nwelt; i < arr.length; ++i) {
  2156. var set = arr[i];
  2157. nw.push({events: nwelt = [], fromBefore: set.fromBefore, toBefore: set.toBefore,
  2158. fromAfter: set.fromAfter, toAfter: set.toAfter});
  2159. for (var j = 0, elt = set.events; j < elt.length; ++j) {
  2160. var old = [], cur = elt[j];
  2161. nwelt.push({start: cur.start, added: cur.added, old: old});
  2162. for (var k = 0; k < cur.old.length; ++k) old.push(hlText(cur.old[k]));
  2163. }
  2164. }
  2165. return nw;
  2166. }
  2167. return {done: cp(hist.done), undone: cp(hist.undone)};
  2168. },
  2169. setHistory: function(histData) {
  2170. var hist = this.view.history = makeHistory();
  2171. hist.done = histData.done;
  2172. hist.undone = histData.undone;
  2173. },
  2174. // Fetch the parser token for a given character. Useful for hacks
  2175. // that want to inspect the mode state (say, for completion).
  2176. getTokenAt: function(pos) {
  2177. var doc = this.view.doc;
  2178. pos = clipPos(doc, pos);
  2179. var state = getStateBefore(this, pos.line), mode = this.view.mode;
  2180. var line = getLine(doc, pos.line);
  2181. var stream = new StringStream(line.text, this.options.tabSize);
  2182. while (stream.pos < pos.ch && !stream.eol()) {
  2183. stream.start = stream.pos;
  2184. var style = mode.token(stream, state);
  2185. }
  2186. return {start: stream.start,
  2187. end: stream.pos,
  2188. string: stream.current(),
  2189. className: style || null, // Deprecated, use 'type' instead
  2190. type: style || null,
  2191. state: state};
  2192. },
  2193. getStateAfter: function(line) {
  2194. var doc = this.view.doc;
  2195. line = clipLine(doc, line == null ? doc.size - 1: line);
  2196. return getStateBefore(this, line + 1);
  2197. },
  2198. cursorCoords: function(start, mode) {
  2199. var pos, sel = this.view.sel;
  2200. if (start == null) pos = sel.head;
  2201. else if (typeof start == "object") pos = clipPos(this.view.doc, start);
  2202. else pos = start ? sel.from : sel.to;
  2203. return cursorCoords(this, pos, mode || "page");
  2204. },
  2205. charCoords: function(pos, mode) {
  2206. return charCoords(this, clipPos(this.view.doc, pos), mode || "page");
  2207. },
  2208. coordsChar: function(coords) {
  2209. var off = this.display.lineSpace.getBoundingClientRect();
  2210. return coordsChar(this, coords.left - off.left, coords.top - off.top);
  2211. },
  2212. defaultTextHeight: function() { return textHeight(this.display); },
  2213. markText: operation(null, function(from, to, options) {
  2214. return markText(this, clipPos(this.view.doc, from), clipPos(this.view.doc, to),
  2215. options, "range");
  2216. }),
  2217. setBookmark: operation(null, function(pos, widget) {
  2218. pos = clipPos(this.view.doc, pos);
  2219. return markText(this, pos, pos, widget ? {replacedWith: widget} : {}, "bookmark");
  2220. }),
  2221. findMarksAt: function(pos) {
  2222. var doc = this.view.doc;
  2223. pos = clipPos(doc, pos);
  2224. var markers = [], spans = getLine(doc, pos.line).markedSpans;
  2225. if (spans) for (var i = 0; i < spans.length; ++i) {
  2226. var span = spans[i];
  2227. if ((span.from == null || span.from <= pos.ch) &&
  2228. (span.to == null || span.to >= pos.ch))
  2229. markers.push(span.marker);
  2230. }
  2231. return markers;
  2232. },
  2233. setGutterMarker: operation(null, function(line, gutterID, value) {
  2234. return changeLine(this, line, function(line) {
  2235. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  2236. markers[gutterID] = value;
  2237. if (!value && isEmpty(markers)) line.gutterMarkers = null;
  2238. return true;
  2239. });
  2240. }),
  2241. clearGutter: operation(null, function(gutterID) {
  2242. var i = 0, cm = this, doc = cm.view.doc;
  2243. doc.iter(0, doc.size, function(line) {
  2244. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  2245. line.gutterMarkers[gutterID] = null;
  2246. regChange(cm, i, i + 1);
  2247. if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
  2248. }
  2249. ++i;
  2250. });
  2251. }),
  2252. addLineClass: operation(null, function(handle, where, cls) {
  2253. return changeLine(this, handle, function(line) {
  2254. var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
  2255. if (!line[prop]) line[prop] = cls;
  2256. else if (new RegExp("\\b" + cls + "\\b").test(line[prop])) return false;
  2257. else line[prop] += " " + cls;
  2258. return true;
  2259. });
  2260. }),
  2261. removeLineClass: operation(null, function(handle, where, cls) {
  2262. return changeLine(this, handle, function(line) {
  2263. var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
  2264. var cur = line[prop];
  2265. if (!cur) return false;
  2266. else if (cls == null) line[prop] = null;
  2267. else {
  2268. var upd = cur.replace(new RegExp("^" + cls + "\\b\\s*|\\s*\\b" + cls + "\\b"), "");
  2269. if (upd == cur) return false;
  2270. line[prop] = upd || null;
  2271. }
  2272. return true;
  2273. });
  2274. }),
  2275. addLineWidget: operation(null, function(handle, node, options) {
  2276. var widget = options || {};
  2277. widget.node = node;
  2278. if (widget.noHScroll) this.display.alignWidgets = true;
  2279. changeLine(this, handle, function(line) {
  2280. (line.widgets || (line.widgets = [])).push(widget);
  2281. widget.line = line;
  2282. return true;
  2283. });
  2284. return widget;
  2285. }),
  2286. removeLineWidget: operation(null, function(widget) {
  2287. var ws = widget.line.widgets, no = lineNo(widget.line);
  2288. if (no == null) return;
  2289. for (var i = 0; i < ws.length; ++i) if (ws[i] == widget) ws.splice(i--, 1);
  2290. regChange(this, no, no + 1);
  2291. }),
  2292. lineInfo: function(line) {
  2293. if (typeof line == "number") {
  2294. if (!isLine(this.view.doc, line)) return null;
  2295. var n = line;
  2296. line = getLine(this.view.doc, line);
  2297. if (!line) return null;
  2298. } else {
  2299. var n = lineNo(line);
  2300. if (n == null) return null;
  2301. }
  2302. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  2303. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  2304. widgets: line.widgets};
  2305. },
  2306. getViewport: function() { return {from: this.display.showingFrom, to: this.display.showingTo};},
  2307. addWidget: function(pos, node, scroll, vert, horiz) {
  2308. var display = this.display;
  2309. pos = cursorCoords(this, clipPos(this.view.doc, pos));
  2310. var top = pos.top, left = pos.left;
  2311. node.style.position = "absolute";
  2312. display.sizer.appendChild(node);
  2313. if (vert == "over") top = pos.top;
  2314. else if (vert == "near") {
  2315. var vspace = Math.max(display.wrapper.clientHeight, this.view.doc.height),
  2316. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  2317. if (pos.bottom + node.offsetHeight > vspace && pos.top > node.offsetHeight)
  2318. top = pos.top - node.offsetHeight;
  2319. if (left + node.offsetWidth > hspace)
  2320. left = hspace - node.offsetWidth;
  2321. }
  2322. node.style.top = (top + paddingTop(display)) + "px";
  2323. node.style.left = node.style.right = "";
  2324. if (horiz == "right") {
  2325. left = display.sizer.clientWidth - node.offsetWidth;
  2326. node.style.right = "0px";
  2327. } else {
  2328. if (horiz == "left") left = 0;
  2329. else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
  2330. node.style.left = left + "px";
  2331. }
  2332. if (scroll)
  2333. scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
  2334. },
  2335. lineCount: function() {return this.view.doc.size;},
  2336. clipPos: function(pos) {return clipPos(this.view.doc, pos);},
  2337. getCursor: function(start) {
  2338. var sel = this.view.sel, pos;
  2339. if (start == null || start == "head") pos = sel.head;
  2340. else if (start == "anchor") pos = sel.anchor;
  2341. else if (start == "end" || start === false) pos = sel.to;
  2342. else pos = sel.from;
  2343. return copyPos(pos);
  2344. },
  2345. somethingSelected: function() {return !posEq(this.view.sel.from, this.view.sel.to);},
  2346. setCursor: operation(null, function(line, ch, extend) {
  2347. var pos = clipPos(this.view.doc, typeof line == "number" ? {line: line, ch: ch || 0} : line);
  2348. if (extend) extendSelection(this, pos);
  2349. else setSelection(this, pos, pos);
  2350. }),
  2351. setSelection: operation(null, function(anchor, head) {
  2352. var doc = this.view.doc;
  2353. setSelection(this, clipPos(doc, anchor), clipPos(doc, head || anchor));
  2354. }),
  2355. extendSelection: operation(null, function(from, to) {
  2356. var doc = this.view.doc;
  2357. extendSelection(this, clipPos(doc, from), to && clipPos(doc, to));
  2358. }),
  2359. setExtending: function(val) {this.view.sel.extend = val;},
  2360. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
  2361. getLineHandle: function(line) {
  2362. var doc = this.view.doc;
  2363. if (isLine(doc, line)) return getLine(doc, line);
  2364. },
  2365. getLineNumber: function(line) {return lineNo(line);},
  2366. setLine: operation(null, function(line, text) {
  2367. if (isLine(this.view.doc, line))
  2368. replaceRange(this, text, {line: line, ch: 0}, {line: line, ch: getLine(this.view.doc, line).text.length});
  2369. }),
  2370. removeLine: operation(null, function(line) {
  2371. if (isLine(this.view.doc, line))
  2372. replaceRange(this, "", {line: line, ch: 0}, clipPos(this.view.doc, {line: line+1, ch: 0}));
  2373. }),
  2374. replaceRange: operation(null, function(code, from, to) {
  2375. var doc = this.view.doc;
  2376. from = clipPos(doc, from);
  2377. to = to ? clipPos(doc, to) : from;
  2378. return replaceRange(this, code, from, to);
  2379. }),
  2380. getRange: function(from, to, lineSep) {
  2381. var doc = this.view.doc;
  2382. from = clipPos(doc, from); to = clipPos(doc, to);
  2383. var l1 = from.line, l2 = to.line;
  2384. if (l1 == l2) return getLine(doc, l1).text.slice(from.ch, to.ch);
  2385. var code = [getLine(doc, l1).text.slice(from.ch)];
  2386. doc.iter(l1 + 1, l2, function(line) { code.push(line.text); });
  2387. code.push(getLine(doc, l2).text.slice(0, to.ch));
  2388. return code.join(lineSep || "\n");
  2389. },
  2390. triggerOnKeyDown: operation(null, onKeyDown),
  2391. execCommand: function(cmd) {return commands[cmd](this);},
  2392. // Stuff used by commands, probably not much use to outside code.
  2393. moveH: operation(null, function(dir, unit) {
  2394. var sel = this.view.sel, pos = dir < 0 ? sel.from : sel.to;
  2395. if (sel.shift || sel.extend || posEq(sel.from, sel.to)) pos = findPosH(this, dir, unit, true);
  2396. extendSelection(this, pos, pos, dir);
  2397. }),
  2398. deleteH: operation(null, function(dir, unit) {
  2399. var sel = this.view.sel;
  2400. if (!posEq(sel.from, sel.to)) replaceRange(this, "", sel.from, sel.to, "delete");
  2401. else replaceRange(this, "", sel.from, findPosH(this, dir, unit, false), "delete");
  2402. this.curOp.userSelChange = true;
  2403. }),
  2404. moveV: operation(null, function(dir, unit) {
  2405. var view = this.view, doc = view.doc, display = this.display;
  2406. var cur = view.sel.head, pos = cursorCoords(this, cur, "div");
  2407. var x = pos.left, y;
  2408. if (view.goalColumn != null) x = view.goalColumn;
  2409. if (unit == "page") {
  2410. var pageSize = Math.min(display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  2411. y = pos.top + dir * pageSize;
  2412. } else if (unit == "line") {
  2413. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  2414. }
  2415. do {
  2416. var target = coordsChar(this, x, y);
  2417. y += dir * 5;
  2418. } while (target.outside && (dir < 0 ? y > 0 : y < doc.height));
  2419. if (unit == "page") display.scrollbarV.scrollTop += charCoords(this, target, "div").top - pos.top;
  2420. extendSelection(this, target, target, dir);
  2421. view.goalColumn = x;
  2422. }),
  2423. toggleOverwrite: function() {
  2424. if (this.view.overwrite = !this.view.overwrite)
  2425. this.display.cursor.className += " CodeMirror-overwrite";
  2426. else
  2427. this.display.cursor.className = this.display.cursor.className.replace(" CodeMirror-overwrite", "");
  2428. },
  2429. posFromIndex: function(off) {
  2430. var lineNo = 0, ch, doc = this.view.doc;
  2431. doc.iter(0, doc.size, function(line) {
  2432. var sz = line.text.length + 1;
  2433. if (sz > off) { ch = off; return true; }
  2434. off -= sz;
  2435. ++lineNo;
  2436. });
  2437. return clipPos(doc, {line: lineNo, ch: ch});
  2438. },
  2439. indexFromPos: function (coords) {
  2440. if (coords.line < 0 || coords.ch < 0) return 0;
  2441. var index = coords.ch;
  2442. this.view.doc.iter(0, coords.line, function (line) {
  2443. index += line.text.length + 1;
  2444. });
  2445. return index;
  2446. },
  2447. scrollTo: function(x, y) {
  2448. if (x != null) this.display.scrollbarH.scrollLeft = this.display.scroller.scrollLeft = x;
  2449. if (y != null) this.display.scrollbarV.scrollTop = this.display.scroller.scrollTop = y;
  2450. updateDisplay(this, []);
  2451. },
  2452. getScrollInfo: function() {
  2453. var scroller = this.display.scroller, co = scrollerCutOff;
  2454. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  2455. height: scroller.scrollHeight - co, width: scroller.scrollWidth - co,
  2456. clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co};
  2457. },
  2458. scrollIntoView: function(pos) {
  2459. if (typeof pos == "number") pos = {line: pos, ch: 0};
  2460. pos = pos ? clipPos(this.view.doc, pos) : this.view.sel.head;
  2461. scrollPosIntoView(this, pos);
  2462. },
  2463. setSize: function(width, height) {
  2464. function interpret(val) {
  2465. return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
  2466. }
  2467. if (width != null) this.display.wrapper.style.width = interpret(width);
  2468. if (height != null) this.display.wrapper.style.height = interpret(height);
  2469. this.refresh();
  2470. },
  2471. on: function(type, f) {on(this, type, f);},
  2472. off: function(type, f) {off(this, type, f);},
  2473. operation: function(f){return operation(this, f)();},
  2474. refresh: function() {
  2475. clearCaches(this);
  2476. if (this.display.scroller.scrollHeight > this.view.scrollTop)
  2477. this.display.scrollbarV.scrollTop = this.display.scroller.scrollTop = this.view.scrollTop;
  2478. updateDisplay(this, true);
  2479. },
  2480. getInputField: function(){return this.display.input;},
  2481. getWrapperElement: function(){return this.display.wrapper;},
  2482. getScrollerElement: function(){return this.display.scroller;},
  2483. getGutterElement: function(){return this.display.gutters;}
  2484. };
  2485. // OPTION DEFAULTS
  2486. var optionHandlers = CodeMirror.optionHandlers = {};
  2487. // The default configuration options.
  2488. var defaults = CodeMirror.defaults = {};
  2489. function option(name, deflt, handle, notOnInit) {
  2490. CodeMirror.defaults[name] = deflt;
  2491. if (handle) optionHandlers[name] =
  2492. notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
  2493. }
  2494. var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
  2495. // These two are, on init, called from the constructor because they
  2496. // have to be initialized before the editor can start at all.
  2497. option("value", "", function(cm, val) {cm.setValue(val);}, true);
  2498. option("mode", null, loadMode, true);
  2499. option("indentUnit", 2, loadMode, true);
  2500. option("indentWithTabs", false);
  2501. option("smartIndent", true);
  2502. option("tabSize", 4, function(cm) {
  2503. loadMode(cm);
  2504. clearCaches(cm);
  2505. updateDisplay(cm, true);
  2506. }, true);
  2507. option("electricChars", true);
  2508. option("theme", "default", function(cm) {
  2509. themeChanged(cm);
  2510. guttersChanged(cm);
  2511. }, true);
  2512. option("keyMap", "default", keyMapChanged);
  2513. option("extraKeys", null);
  2514. option("onKeyEvent", null);
  2515. option("onDragEvent", null);
  2516. option("lineWrapping", false, wrappingChanged, true);
  2517. option("gutters", [], function(cm) {
  2518. setGuttersForLineNumbers(cm.options);
  2519. guttersChanged(cm);
  2520. }, true);
  2521. option("lineNumbers", false, function(cm) {
  2522. setGuttersForLineNumbers(cm.options);
  2523. guttersChanged(cm);
  2524. }, true);
  2525. option("firstLineNumber", 1, guttersChanged, true);
  2526. option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
  2527. option("showCursorWhenSelecting", false, updateSelection, true);
  2528. option("readOnly", false, function(cm, val) {
  2529. if (val == "nocursor") {onBlur(cm); cm.display.input.blur();}
  2530. else if (!val) resetInput(cm, true);
  2531. });
  2532. option("dragDrop", true);
  2533. option("cursorBlinkRate", 530);
  2534. option("cursorHeight", 1);
  2535. option("workTime", 100);
  2536. option("workDelay", 100);
  2537. option("flattenSpans", true);
  2538. option("pollInterval", 100);
  2539. option("undoDepth", 40);
  2540. option("viewportMargin", 10, function(cm){cm.refresh();}, true);
  2541. option("tabindex", null, function(cm, val) {
  2542. cm.display.input.tabIndex = val || "";
  2543. });
  2544. option("autofocus", null);
  2545. // MODE DEFINITION AND QUERYING
  2546. // Known modes, by name and by MIME
  2547. var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
  2548. CodeMirror.defineMode = function(name, mode) {
  2549. if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
  2550. if (arguments.length > 2) {
  2551. mode.dependencies = [];
  2552. for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
  2553. }
  2554. modes[name] = mode;
  2555. };
  2556. CodeMirror.defineMIME = function(mime, spec) {
  2557. mimeModes[mime] = spec;
  2558. };
  2559. CodeMirror.resolveMode = function(spec) {
  2560. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
  2561. spec = mimeModes[spec];
  2562. else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec))
  2563. return CodeMirror.resolveMode("application/xml");
  2564. if (typeof spec == "string") return {name: spec};
  2565. else return spec || {name: "null"};
  2566. };
  2567. CodeMirror.getMode = function(options, spec) {
  2568. var spec = CodeMirror.resolveMode(spec);
  2569. var mfactory = modes[spec.name];
  2570. if (!mfactory) return CodeMirror.getMode(options, "text/plain");
  2571. var modeObj = mfactory(options, spec);
  2572. if (modeExtensions.hasOwnProperty(spec.name)) {
  2573. var exts = modeExtensions[spec.name];
  2574. for (var prop in exts) {
  2575. if (!exts.hasOwnProperty(prop)) continue;
  2576. if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
  2577. modeObj[prop] = exts[prop];
  2578. }
  2579. }
  2580. modeObj.name = spec.name;
  2581. return modeObj;
  2582. };
  2583. CodeMirror.defineMode("null", function() {
  2584. return {token: function(stream) {stream.skipToEnd();}};
  2585. });
  2586. CodeMirror.defineMIME("text/plain", "null");
  2587. var modeExtensions = CodeMirror.modeExtensions = {};
  2588. CodeMirror.extendMode = function(mode, properties) {
  2589. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  2590. for (var prop in properties) if (properties.hasOwnProperty(prop))
  2591. exts[prop] = properties[prop];
  2592. };
  2593. // EXTENSIONS
  2594. CodeMirror.defineExtension = function(name, func) {
  2595. CodeMirror.prototype[name] = func;
  2596. };
  2597. CodeMirror.defineOption = option;
  2598. var initHooks = [];
  2599. CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
  2600. // MODE STATE HANDLING
  2601. // Utility functions for working with state. Exported because modes
  2602. // sometimes need to do this.
  2603. function copyState(mode, state) {
  2604. if (state === true) return state;
  2605. if (mode.copyState) return mode.copyState(state);
  2606. var nstate = {};
  2607. for (var n in state) {
  2608. var val = state[n];
  2609. if (val instanceof Array) val = val.concat([]);
  2610. nstate[n] = val;
  2611. }
  2612. return nstate;
  2613. }
  2614. CodeMirror.copyState = copyState;
  2615. function startState(mode, a1, a2) {
  2616. return mode.startState ? mode.startState(a1, a2) : true;
  2617. }
  2618. CodeMirror.startState = startState;
  2619. CodeMirror.innerMode = function(mode, state) {
  2620. while (mode.innerMode) {
  2621. var info = mode.innerMode(state);
  2622. state = info.state;
  2623. mode = info.mode;
  2624. }
  2625. return info || {mode: mode, state: state};
  2626. };
  2627. // STANDARD COMMANDS
  2628. var commands = CodeMirror.commands = {
  2629. selectAll: function(cm) {cm.setSelection({line: 0, ch: 0}, {line: cm.lineCount() - 1});},
  2630. killLine: function(cm) {
  2631. var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
  2632. if (!sel && cm.getLine(from.line).length == from.ch)
  2633. cm.replaceRange("", from, {line: from.line + 1, ch: 0}, "delete");
  2634. else cm.replaceRange("", from, sel ? to : {line: from.line}, "delete");
  2635. },
  2636. deleteLine: function(cm) {
  2637. var l = cm.getCursor().line;
  2638. cm.replaceRange("", {line: l, ch: 0}, {line: l}, "delete");
  2639. },
  2640. undo: function(cm) {cm.undo();},
  2641. redo: function(cm) {cm.redo();},
  2642. goDocStart: function(cm) {cm.extendSelection({line: 0, ch: 0});},
  2643. goDocEnd: function(cm) {cm.extendSelection({line: cm.lineCount() - 1});},
  2644. goLineStart: function(cm) {
  2645. cm.extendSelection(lineStart(cm, cm.getCursor().line));
  2646. },
  2647. goLineStartSmart: function(cm) {
  2648. var cur = cm.getCursor(), start = lineStart(cm, cur.line);
  2649. var line = cm.getLineHandle(start.line);
  2650. var order = getOrder(line);
  2651. if (!order || order[0].level == 0) {
  2652. var firstNonWS = Math.max(0, line.text.search(/\S/));
  2653. var inWS = cur.line == start.line && cur.ch <= firstNonWS && cur.ch;
  2654. cm.extendSelection({line: start.line, ch: inWS ? 0 : firstNonWS});
  2655. } else cm.extendSelection(start);
  2656. },
  2657. goLineEnd: function(cm) {
  2658. cm.extendSelection(lineEnd(cm, cm.getCursor().line));
  2659. },
  2660. goLineUp: function(cm) {cm.moveV(-1, "line");},
  2661. goLineDown: function(cm) {cm.moveV(1, "line");},
  2662. goPageUp: function(cm) {cm.moveV(-1, "page");},
  2663. goPageDown: function(cm) {cm.moveV(1, "page");},
  2664. goCharLeft: function(cm) {cm.moveH(-1, "char");},
  2665. goCharRight: function(cm) {cm.moveH(1, "char");},
  2666. goColumnLeft: function(cm) {cm.moveH(-1, "column");},
  2667. goColumnRight: function(cm) {cm.moveH(1, "column");},
  2668. goWordLeft: function(cm) {cm.moveH(-1, "word");},
  2669. goWordRight: function(cm) {cm.moveH(1, "word");},
  2670. delCharBefore: function(cm) {cm.deleteH(-1, "char");},
  2671. delCharAfter: function(cm) {cm.deleteH(1, "char");},
  2672. delWordBefore: function(cm) {cm.deleteH(-1, "word");},
  2673. delWordAfter: function(cm) {cm.deleteH(1, "word");},
  2674. indentAuto: function(cm) {cm.indentSelection("smart");},
  2675. indentMore: function(cm) {cm.indentSelection("add");},
  2676. indentLess: function(cm) {cm.indentSelection("subtract");},
  2677. insertTab: function(cm) {cm.replaceSelection("\t", "end", "input");},
  2678. defaultTab: function(cm) {
  2679. if (cm.somethingSelected()) cm.indentSelection("add");
  2680. else cm.replaceSelection("\t", "end", "input");
  2681. },
  2682. transposeChars: function(cm) {
  2683. var cur = cm.getCursor(), line = cm.getLine(cur.line);
  2684. if (cur.ch > 0 && cur.ch < line.length - 1)
  2685. cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1),
  2686. {line: cur.line, ch: cur.ch - 1}, {line: cur.line, ch: cur.ch + 1});
  2687. },
  2688. newlineAndIndent: function(cm) {
  2689. operation(cm, function() {
  2690. cm.replaceSelection("\n", "end", "input");
  2691. cm.indentLine(cm.getCursor().line, null, true);
  2692. })();
  2693. },
  2694. toggleOverwrite: function(cm) {cm.toggleOverwrite();}
  2695. };
  2696. // STANDARD KEYMAPS
  2697. var keyMap = CodeMirror.keyMap = {};
  2698. keyMap.basic = {
  2699. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  2700. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  2701. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  2702. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite"
  2703. };
  2704. // Note that the save and find-related commands aren't defined by
  2705. // default. Unknown commands are simply ignored.
  2706. keyMap.pcDefault = {
  2707. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  2708. "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
  2709. "Ctrl-Left": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  2710. "Ctrl-Backspace": "delWordBefore", "Ctrl-Delete": "delWordAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  2711. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  2712. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  2713. fallthrough: "basic"
  2714. };
  2715. keyMap.macDefault = {
  2716. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  2717. "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goWordLeft",
  2718. "Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordBefore",
  2719. "Ctrl-Alt-Backspace": "delWordAfter", "Alt-Delete": "delWordAfter", "Cmd-S": "save", "Cmd-F": "find",
  2720. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  2721. "Cmd-[": "indentLess", "Cmd-]": "indentMore",
  2722. fallthrough: ["basic", "emacsy"]
  2723. };
  2724. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  2725. keyMap.emacsy = {
  2726. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  2727. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  2728. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  2729. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
  2730. };
  2731. // KEYMAP DISPATCH
  2732. function getKeyMap(val) {
  2733. if (typeof val == "string") return keyMap[val];
  2734. else return val;
  2735. }
  2736. function lookupKey(name, maps, handle, stop) {
  2737. function lookup(map) {
  2738. map = getKeyMap(map);
  2739. var found = map[name];
  2740. if (found === false) {
  2741. if (stop) stop();
  2742. return true;
  2743. }
  2744. if (found != null && handle(found)) return true;
  2745. if (map.nofallthrough) {
  2746. if (stop) stop();
  2747. return true;
  2748. }
  2749. var fallthrough = map.fallthrough;
  2750. if (fallthrough == null) return false;
  2751. if (Object.prototype.toString.call(fallthrough) != "[object Array]")
  2752. return lookup(fallthrough);
  2753. for (var i = 0, e = fallthrough.length; i < e; ++i) {
  2754. if (lookup(fallthrough[i])) return true;
  2755. }
  2756. return false;
  2757. }
  2758. for (var i = 0; i < maps.length; ++i)
  2759. if (lookup(maps[i])) return true;
  2760. }
  2761. function isModifierKey(event) {
  2762. var name = keyNames[e_prop(event, "keyCode")];
  2763. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
  2764. }
  2765. CodeMirror.isModifierKey = isModifierKey;
  2766. // FROMTEXTAREA
  2767. CodeMirror.fromTextArea = function(textarea, options) {
  2768. if (!options) options = {};
  2769. options.value = textarea.value;
  2770. if (!options.tabindex && textarea.tabindex)
  2771. options.tabindex = textarea.tabindex;
  2772. // Set autofocus to true if this textarea is focused, or if it has
  2773. // autofocus and no other element is focused.
  2774. if (options.autofocus == null) {
  2775. var hasFocus = document.body;
  2776. // doc.activeElement occasionally throws on IE
  2777. try { hasFocus = document.activeElement; } catch(e) {}
  2778. options.autofocus = hasFocus == textarea ||
  2779. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  2780. }
  2781. function save() {textarea.value = cm.getValue();}
  2782. if (textarea.form) {
  2783. // Deplorable hack to make the submit method do the right thing.
  2784. on(textarea.form, "submit", save);
  2785. var form = textarea.form, realSubmit = form.submit;
  2786. try {
  2787. form.submit = function wrappedSubmit() {
  2788. save();
  2789. form.submit = realSubmit;
  2790. form.submit();
  2791. form.submit = wrappedSubmit;
  2792. };
  2793. } catch(e) {}
  2794. }
  2795. textarea.style.display = "none";
  2796. var cm = CodeMirror(function(node) {
  2797. textarea.parentNode.insertBefore(node, textarea.nextSibling);
  2798. }, options);
  2799. cm.save = save;
  2800. cm.getTextArea = function() { return textarea; };
  2801. cm.toTextArea = function() {
  2802. save();
  2803. textarea.parentNode.removeChild(cm.getWrapperElement());
  2804. textarea.style.display = "";
  2805. if (textarea.form) {
  2806. off(textarea.form, "submit", save);
  2807. if (typeof textarea.form.submit == "function")
  2808. textarea.form.submit = realSubmit;
  2809. }
  2810. };
  2811. return cm;
  2812. };
  2813. // STRING STREAM
  2814. // Fed to the mode parsers, provides helper functions to make
  2815. // parsers more succinct.
  2816. // The character stream used by a mode's parser.
  2817. function StringStream(string, tabSize) {
  2818. this.pos = this.start = 0;
  2819. this.string = string;
  2820. this.tabSize = tabSize || 8;
  2821. }
  2822. StringStream.prototype = {
  2823. eol: function() {return this.pos >= this.string.length;},
  2824. sol: function() {return this.pos == 0;},
  2825. peek: function() {return this.string.charAt(this.pos) || undefined;},
  2826. next: function() {
  2827. if (this.pos < this.string.length)
  2828. return this.string.charAt(this.pos++);
  2829. },
  2830. eat: function(match) {
  2831. var ch = this.string.charAt(this.pos);
  2832. if (typeof match == "string") var ok = ch == match;
  2833. else var ok = ch && (match.test ? match.test(ch) : match(ch));
  2834. if (ok) {++this.pos; return ch;}
  2835. },
  2836. eatWhile: function(match) {
  2837. var start = this.pos;
  2838. while (this.eat(match)){}
  2839. return this.pos > start;
  2840. },
  2841. eatSpace: function() {
  2842. var start = this.pos;
  2843. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
  2844. return this.pos > start;
  2845. },
  2846. skipToEnd: function() {this.pos = this.string.length;},
  2847. skipTo: function(ch) {
  2848. var found = this.string.indexOf(ch, this.pos);
  2849. if (found > -1) {this.pos = found; return true;}
  2850. },
  2851. backUp: function(n) {this.pos -= n;},
  2852. column: function() {return countColumn(this.string, this.start, this.tabSize);},
  2853. indentation: function() {return countColumn(this.string, null, this.tabSize);},
  2854. match: function(pattern, consume, caseInsensitive) {
  2855. if (typeof pattern == "string") {
  2856. var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
  2857. if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
  2858. if (consume !== false) this.pos += pattern.length;
  2859. return true;
  2860. }
  2861. } else {
  2862. var match = this.string.slice(this.pos).match(pattern);
  2863. if (match && match.index > 0) return null;
  2864. if (match && consume !== false) this.pos += match[0].length;
  2865. return match;
  2866. }
  2867. },
  2868. current: function(){return this.string.slice(this.start, this.pos);}
  2869. };
  2870. CodeMirror.StringStream = StringStream;
  2871. // TEXTMARKERS
  2872. function TextMarker(cm, type) {
  2873. this.lines = [];
  2874. this.type = type;
  2875. this.cm = cm;
  2876. }
  2877. TextMarker.prototype.clear = function() {
  2878. if (this.explicitlyCleared) return;
  2879. startOperation(this.cm);
  2880. var min = null, max = null;
  2881. for (var i = 0; i < this.lines.length; ++i) {
  2882. var line = this.lines[i];
  2883. var span = getMarkedSpanFor(line.markedSpans, this);
  2884. if (span.to != null) max = lineNo(line);
  2885. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  2886. if (span.from != null)
  2887. min = lineNo(line);
  2888. else if (this.collapsed && !lineIsHidden(line))
  2889. updateLineHeight(line, textHeight(this.cm.display));
  2890. }
  2891. if (min != null) regChange(this.cm, min, max + 1);
  2892. this.lines.length = 0;
  2893. this.explicitlyCleared = true;
  2894. if (this.collapsed && this.cm.view.cantEdit) {
  2895. this.cm.view.cantEdit = false;
  2896. reCheckSelection(this.cm);
  2897. }
  2898. endOperation(this.cm);
  2899. signalLater(this.cm, this, "clear");
  2900. };
  2901. TextMarker.prototype.find = function() {
  2902. var from, to;
  2903. for (var i = 0; i < this.lines.length; ++i) {
  2904. var line = this.lines[i];
  2905. var span = getMarkedSpanFor(line.markedSpans, this);
  2906. if (span.from != null || span.to != null) {
  2907. var found = lineNo(line);
  2908. if (span.from != null) from = {line: found, ch: span.from};
  2909. if (span.to != null) to = {line: found, ch: span.to};
  2910. }
  2911. }
  2912. if (this.type == "bookmark") return from;
  2913. return from && {from: from, to: to};
  2914. };
  2915. function markText(cm, from, to, options, type) {
  2916. var doc = cm.view.doc;
  2917. var marker = new TextMarker(cm, type);
  2918. if (type == "range" && !posLess(from, to)) return marker;
  2919. if (options) for (var opt in options) if (options.hasOwnProperty(opt))
  2920. marker[opt] = options[opt];
  2921. if (marker.replacedWith) {
  2922. marker.collapsed = true;
  2923. marker.replacedWith = elt("span", [marker.replacedWith], "CodeMirror-widget");
  2924. }
  2925. if (marker.collapsed) sawCollapsedSpans = true;
  2926. var curLine = from.line, size = 0, collapsedAtStart, collapsedAtEnd;
  2927. doc.iter(curLine, to.line + 1, function(line) {
  2928. var span = {from: null, to: null, marker: marker};
  2929. size += line.text.length;
  2930. if (curLine == from.line) {span.from = from.ch; size -= from.ch;}
  2931. if (curLine == to.line) {span.to = to.ch; size -= line.text.length - to.ch;}
  2932. if (marker.collapsed) {
  2933. if (curLine == to.line) collapsedAtEnd = collapsedSpanAt(line, to.ch);
  2934. if (curLine == from.line) collapsedAtStart = collapsedSpanAt(line, from.ch);
  2935. else updateLineHeight(line, 0);
  2936. }
  2937. addMarkedSpan(line, span);
  2938. if (marker.collapsed && curLine == from.line && lineIsHidden(line))
  2939. updateLineHeight(line, 0);
  2940. ++curLine;
  2941. });
  2942. if (marker.readOnly) {
  2943. sawReadOnlySpans = true;
  2944. if (cm.view.history.done.length || cm.view.history.undone.length)
  2945. cm.clearHistory();
  2946. }
  2947. if (marker.collapsed) {
  2948. if (collapsedAtStart != collapsedAtEnd)
  2949. throw new Error("Inserting collapsed marker overlapping an existing one");
  2950. marker.size = size;
  2951. marker.atomic = true;
  2952. }
  2953. if (marker.className || marker.startStyle || marker.endStyle || marker.collapsed)
  2954. regChange(cm, from.line, to.line + 1);
  2955. if (marker.atomic) reCheckSelection(cm);
  2956. return marker;
  2957. }
  2958. // TEXTMARKER SPANS
  2959. function getMarkedSpanFor(spans, marker) {
  2960. if (spans) for (var i = 0; i < spans.length; ++i) {
  2961. var span = spans[i];
  2962. if (span.marker == marker) return span;
  2963. }
  2964. }
  2965. function removeMarkedSpan(spans, span) {
  2966. for (var r, i = 0; i < spans.length; ++i)
  2967. if (spans[i] != span) (r || (r = [])).push(spans[i]);
  2968. return r;
  2969. }
  2970. function addMarkedSpan(line, span) {
  2971. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  2972. span.marker.lines.push(line);
  2973. }
  2974. function markedSpansBefore(old, startCh) {
  2975. if (old) for (var i = 0, nw; i < old.length; ++i) {
  2976. var span = old[i], marker = span.marker;
  2977. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  2978. if (startsBefore || marker.type == "bookmark" && span.from == startCh) {
  2979. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
  2980. (nw || (nw = [])).push({from: span.from,
  2981. to: endsAfter ? null : span.to,
  2982. marker: marker});
  2983. }
  2984. }
  2985. return nw;
  2986. }
  2987. function markedSpansAfter(old, startCh, endCh) {
  2988. if (old) for (var i = 0, nw; i < old.length; ++i) {
  2989. var span = old[i], marker = span.marker;
  2990. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  2991. if (endsAfter || marker.type == "bookmark" && span.from == endCh && span.from != startCh) {
  2992. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
  2993. (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh,
  2994. to: span.to == null ? null : span.to - endCh,
  2995. marker: marker});
  2996. }
  2997. }
  2998. return nw;
  2999. }
  3000. function updateMarkedSpans(oldFirst, oldLast, startCh, endCh, newText) {
  3001. if (!oldFirst && !oldLast) return newText;
  3002. // Get the spans that 'stick out' on both sides
  3003. var first = markedSpansBefore(oldFirst, startCh);
  3004. var last = markedSpansAfter(oldLast, startCh, endCh);
  3005. // Next, merge those two ends
  3006. var sameLine = newText.length == 1, offset = lst(newText).length + (sameLine ? startCh : 0);
  3007. if (first) {
  3008. // Fix up .to properties of first
  3009. for (var i = 0; i < first.length; ++i) {
  3010. var span = first[i];
  3011. if (span.to == null) {
  3012. var found = getMarkedSpanFor(last, span.marker);
  3013. if (!found) span.to = startCh;
  3014. else if (sameLine) span.to = found.to == null ? null : found.to + offset;
  3015. }
  3016. }
  3017. }
  3018. if (last) {
  3019. // Fix up .from in last (or move them into first in case of sameLine)
  3020. for (var i = 0; i < last.length; ++i) {
  3021. var span = last[i];
  3022. if (span.to != null) span.to += offset;
  3023. if (span.from == null) {
  3024. var found = getMarkedSpanFor(first, span.marker);
  3025. if (!found) {
  3026. span.from = offset;
  3027. if (sameLine) (first || (first = [])).push(span);
  3028. }
  3029. } else {
  3030. span.from += offset;
  3031. if (sameLine) (first || (first = [])).push(span);
  3032. }
  3033. }
  3034. }
  3035. var newMarkers = [newHL(newText[0], first)];
  3036. if (!sameLine) {
  3037. // Fill gap with whole-line-spans
  3038. var gap = newText.length - 2, gapMarkers;
  3039. if (gap > 0 && first)
  3040. for (var i = 0; i < first.length; ++i)
  3041. if (first[i].to == null)
  3042. (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker});
  3043. for (var i = 0; i < gap; ++i)
  3044. newMarkers.push(newHL(newText[i+1], gapMarkers));
  3045. newMarkers.push(newHL(lst(newText), last));
  3046. }
  3047. return newMarkers;
  3048. }
  3049. function removeReadOnlyRanges(doc, from, to) {
  3050. var markers = null;
  3051. doc.iter(from.line, to.line + 1, function(line) {
  3052. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  3053. var mark = line.markedSpans[i].marker;
  3054. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  3055. (markers || (markers = [])).push(mark);
  3056. }
  3057. });
  3058. if (!markers) return null;
  3059. var parts = [{from: from, to: to}];
  3060. for (var i = 0; i < markers.length; ++i) {
  3061. var m = markers[i].find();
  3062. for (var j = 0; j < parts.length; ++j) {
  3063. var p = parts[j];
  3064. if (!posLess(m.from, p.to) || posLess(m.to, p.from)) continue;
  3065. var newParts = [j, 1];
  3066. if (posLess(p.from, m.from)) newParts.push({from: p.from, to: m.from});
  3067. if (posLess(m.to, p.to)) newParts.push({from: m.to, to: p.to});
  3068. parts.splice.apply(parts, newParts);
  3069. j += newParts.length - 1;
  3070. }
  3071. }
  3072. return parts;
  3073. }
  3074. function collapsedSpanAt(line, ch) {
  3075. var sps = sawCollapsedSpans && line.markedSpans, found;
  3076. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  3077. sp = sps[i];
  3078. if (!sp.marker.collapsed) continue;
  3079. if ((sp.from == null || sp.from < ch) &&
  3080. (sp.to == null || sp.to > ch) &&
  3081. (!found || found.width < sp.marker.width))
  3082. found = sp.marker;
  3083. }
  3084. return found;
  3085. }
  3086. function collapsedSpanAtStart(line) { return collapsedSpanAt(line, -1); }
  3087. function collapsedSpanAtEnd(line) { return collapsedSpanAt(line, line.text.length + 1); }
  3088. function visualLine(doc, line) {
  3089. var merged;
  3090. while (merged = collapsedSpanAtStart(line))
  3091. line = getLine(doc, merged.find().from.line);
  3092. return line;
  3093. }
  3094. function lineIsHidden(line) {
  3095. var sps = sawCollapsedSpans && line.markedSpans;
  3096. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  3097. sp = sps[i];
  3098. if (!sp.marker.collapsed) continue;
  3099. if (sp.from == null) return true;
  3100. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(line, sp))
  3101. return true;
  3102. }
  3103. }
  3104. window.lineIsHidden = lineIsHidden;
  3105. function lineIsHiddenInner(line, span) {
  3106. if (span.to == null || span.marker.inclusiveRight && span.to == line.text.length)
  3107. return true;
  3108. for (var sp, i = 0; i < line.markedSpans.length; ++i) {
  3109. sp = line.markedSpans[i];
  3110. if (sp.marker.collapsed && sp.from == span.to &&
  3111. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  3112. lineIsHiddenInner(line, sp)) return true;
  3113. }
  3114. }
  3115. // hl stands for history-line, a data structure that can be either a
  3116. // string (line without markers) or a {text, markedSpans} object.
  3117. function hlText(val) { return typeof val == "string" ? val : val.text; }
  3118. function hlSpans(val) {
  3119. if (typeof val == "string") return null;
  3120. var spans = val.markedSpans, out = null;
  3121. for (var i = 0; i < spans.length; ++i) {
  3122. if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
  3123. else if (out) out.push(spans[i]);
  3124. }
  3125. return !out ? spans : out.length ? out : null;
  3126. }
  3127. function newHL(text, spans) { return spans ? {text: text, markedSpans: spans} : text; }
  3128. function detachMarkedSpans(line) {
  3129. var spans = line.markedSpans;
  3130. if (!spans) return;
  3131. for (var i = 0; i < spans.length; ++i) {
  3132. var lines = spans[i].marker.lines;
  3133. var ix = indexOf(lines, line);
  3134. lines.splice(ix, 1);
  3135. }
  3136. line.markedSpans = null;
  3137. }
  3138. function attachMarkedSpans(line, spans) {
  3139. if (!spans) return;
  3140. for (var i = 0; i < spans.length; ++i)
  3141. spans[i].marker.lines.push(line);
  3142. line.markedSpans = spans;
  3143. }
  3144. // LINE DATA STRUCTURE
  3145. // Line objects. These hold state related to a line, including
  3146. // highlighting info (the styles array).
  3147. function makeLine(text, markedSpans, height) {
  3148. var line = {text: text, height: height};
  3149. attachMarkedSpans(line, markedSpans);
  3150. if (lineIsHidden(line)) line.height = 0;
  3151. return line;
  3152. }
  3153. function updateLine(cm, line, text, markedSpans) {
  3154. line.text = text;
  3155. line.stateAfter = line.styles = null;
  3156. if (line.order != null) line.order = null;
  3157. detachMarkedSpans(line);
  3158. attachMarkedSpans(line, markedSpans);
  3159. if (lineIsHidden(line)) line.height = 0;
  3160. else if (!line.height) line.height = textHeight(cm.display);
  3161. signalLater(cm, line, "change");
  3162. }
  3163. function cleanUpLine(line) {
  3164. line.parent = null;
  3165. detachMarkedSpans(line);
  3166. }
  3167. // Run the given mode's parser over a line, update the styles
  3168. // array, which contains alternating fragments of text and CSS
  3169. // classes.
  3170. function highlightLine(cm, line, state) {
  3171. var mode = cm.view.mode, flattenSpans = cm.options.flattenSpans;
  3172. var changed = !line.styles, pos = 0, curText = "", curStyle = null;
  3173. var stream = new StringStream(line.text, cm.options.tabSize), st = line.styles || (line.styles = []);
  3174. if (line.text == "" && mode.blankLine) mode.blankLine(state);
  3175. while (!stream.eol()) {
  3176. var style = mode.token(stream, state), substr = stream.current();
  3177. stream.start = stream.pos;
  3178. if (!flattenSpans || curStyle != style) {
  3179. if (curText) {
  3180. changed = changed || pos >= st.length || curText != st[pos] || curStyle != st[pos+1];
  3181. st[pos++] = curText; st[pos++] = curStyle;
  3182. }
  3183. curText = substr; curStyle = style;
  3184. } else curText = curText + substr;
  3185. // Give up when line is ridiculously long
  3186. if (stream.pos > 5000) break;
  3187. }
  3188. if (curText) {
  3189. changed = changed || pos >= st.length || curText != st[pos] || curStyle != st[pos+1];
  3190. st[pos++] = curText; st[pos++] = curStyle;
  3191. }
  3192. if (stream.pos > 5000) { st[pos++] = line.text.slice(stream.pos); st[pos++] = null; }
  3193. if (pos != st.length) { st.length = pos; changed = true; }
  3194. return changed;
  3195. }
  3196. // Lightweight form of highlight -- proceed over this line and
  3197. // update state, but don't save a style array.
  3198. function processLine(cm, line, state) {
  3199. var mode = cm.view.mode;
  3200. var stream = new StringStream(line.text, cm.options.tabSize);
  3201. if (line.text == "" && mode.blankLine) mode.blankLine(state);
  3202. while (!stream.eol() && stream.pos <= 5000) {
  3203. mode.token(stream, state);
  3204. stream.start = stream.pos;
  3205. }
  3206. }
  3207. var styleToClassCache = {};
  3208. function styleToClass(style) {
  3209. if (!style) return null;
  3210. return styleToClassCache[style] ||
  3211. (styleToClassCache[style] = "cm-" + style.replace(/ +/g, " cm-"));
  3212. }
  3213. function lineContent(cm, realLine, measure) {
  3214. var merged, line = realLine, lineBefore, sawBefore, simple = true;
  3215. while (merged = collapsedSpanAtStart(line)) {
  3216. simple = false;
  3217. line = getLine(cm.view.doc, merged.find().from.line);
  3218. if (!lineBefore) lineBefore = line;
  3219. }
  3220. var builder = {pre: elt("pre"), col: 0, pos: 0, display: !measure,
  3221. measure: null, addedOne: false, cm: cm};
  3222. if (line.textClass) builder.pre.className = line.textClass;
  3223. do {
  3224. if (!line.styles)
  3225. highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
  3226. builder.measure = line == realLine && measure;
  3227. builder.pos = 0;
  3228. builder.addToken = builder.measure ? buildTokenMeasure : buildToken;
  3229. if (measure && sawBefore && line != realLine && !builder.addedOne) {
  3230. measure[0] = builder.pre.appendChild(zeroWidthElement(cm.display.measure));
  3231. builder.addedOne = true;
  3232. }
  3233. var next = insertLineContent(line, builder);
  3234. sawBefore = line == lineBefore;
  3235. if (next) {
  3236. line = getLine(cm.view.doc, next.to.line);
  3237. simple = false;
  3238. }
  3239. } while (next);
  3240. if (measure && !builder.addedOne)
  3241. measure[0] = builder.pre.appendChild(simple ? elt("span", "\u00a0") : zeroWidthElement(cm.display.measure));
  3242. if (!builder.pre.firstChild && !lineIsHidden(realLine))
  3243. builder.pre.appendChild(document.createTextNode("\u00a0"));
  3244. return builder.pre;
  3245. }
  3246. var tokenSpecialChars = /[\t\u0000-\u0019\u200b\u2028\u2029\uFEFF]/g;
  3247. function buildToken(builder, text, style, startStyle, endStyle) {
  3248. if (!text) return;
  3249. if (!tokenSpecialChars.test(text)) {
  3250. builder.col += text.length;
  3251. var content = document.createTextNode(text);
  3252. } else {
  3253. var content = document.createDocumentFragment(), pos = 0;
  3254. while (true) {
  3255. tokenSpecialChars.lastIndex = pos;
  3256. var m = tokenSpecialChars.exec(text);
  3257. var skipped = m ? m.index - pos : text.length - pos;
  3258. if (skipped) {
  3259. content.appendChild(document.createTextNode(text.slice(pos, pos + skipped)));
  3260. builder.col += skipped;
  3261. }
  3262. if (!m) break;
  3263. pos += skipped + 1;
  3264. if (m[0] == "\t") {
  3265. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  3266. content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  3267. builder.col += tabWidth;
  3268. } else {
  3269. var token = elt("span", "\u2022", "cm-invalidchar");
  3270. token.title = "\\u" + m[0].charCodeAt(0).toString(16);
  3271. content.appendChild(token);
  3272. builder.col += 1;
  3273. }
  3274. }
  3275. }
  3276. if (style || startStyle || endStyle || builder.measure) {
  3277. var fullStyle = style || "";
  3278. if (startStyle) fullStyle += startStyle;
  3279. if (endStyle) fullStyle += endStyle;
  3280. return builder.pre.appendChild(elt("span", [content], fullStyle));
  3281. }
  3282. builder.pre.appendChild(content);
  3283. }
  3284. function buildTokenMeasure(builder, text, style, startStyle, endStyle) {
  3285. for (var i = 0; i < text.length; ++i) {
  3286. if (i && i < text.length - 1 &&
  3287. builder.cm.options.lineWrapping &&
  3288. spanAffectsWrapping.test(text.slice(i - 1, i + 1)))
  3289. builder.pre.appendChild(elt("wbr"));
  3290. builder.measure[builder.pos++] =
  3291. buildToken(builder, text.charAt(i), style,
  3292. i == 0 && startStyle, i == text.length - 1 && endStyle);
  3293. }
  3294. if (text.length) builder.addedOne = true;
  3295. }
  3296. function buildCollapsedSpan(builder, size, widget) {
  3297. if (widget) {
  3298. if (!builder.display) widget = widget.cloneNode(true);
  3299. builder.pre.appendChild(widget);
  3300. if (builder.measure && size) {
  3301. builder.measure[builder.pos] = widget;
  3302. builder.addedOne = true;
  3303. }
  3304. }
  3305. builder.pos += size;
  3306. }
  3307. // Outputs a number of spans to make up a line, taking highlighting
  3308. // and marked text into account.
  3309. function insertLineContent(line, builder) {
  3310. var st = line.styles, spans = line.markedSpans;
  3311. if (!spans) {
  3312. for (var i = 0; i < st.length; i+=2)
  3313. builder.addToken(builder, st[i], styleToClass(st[i+1]));
  3314. return;
  3315. }
  3316. var allText = line.text, len = allText.length;
  3317. var pos = 0, i = 0, text = "", style;
  3318. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed;
  3319. for (;;) {
  3320. if (nextChange == pos) { // Update current marker set
  3321. spanStyle = spanEndStyle = spanStartStyle = "";
  3322. collapsed = null; nextChange = Infinity;
  3323. var foundBookmark = null;
  3324. for (var j = 0; j < spans.length; ++j) {
  3325. var sp = spans[j], m = sp.marker;
  3326. if (sp.from <= pos && (sp.to == null || sp.to > pos)) {
  3327. if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }
  3328. if (m.className) spanStyle += " " + m.className;
  3329. if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
  3330. if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
  3331. if (m.collapsed && (!collapsed || collapsed.marker.width < m.width))
  3332. collapsed = sp;
  3333. } else if (sp.from > pos && nextChange > sp.from) {
  3334. nextChange = sp.from;
  3335. }
  3336. if (m.type == "bookmark" && sp.from == pos && m.replacedWith)
  3337. foundBookmark = m.replacedWith;
  3338. }
  3339. if (collapsed && (collapsed.from || 0) == pos) {
  3340. buildCollapsedSpan(builder, (collapsed.to == null ? len : collapsed.to) - pos,
  3341. collapsed.from != null && collapsed.marker.replacedWith);
  3342. if (collapsed.to == null) return collapsed.marker.find();
  3343. }
  3344. if (foundBookmark && !collapsed) buildCollapsedSpan(builder, 0, foundBookmark);
  3345. }
  3346. if (pos >= len) break;
  3347. var upto = Math.min(len, nextChange);
  3348. while (true) {
  3349. if (text) {
  3350. var end = pos + text.length;
  3351. if (!collapsed) {
  3352. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  3353. builder.addToken(builder, tokenText, style + spanStyle,
  3354. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "");
  3355. }
  3356. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
  3357. pos = end;
  3358. spanStartStyle = "";
  3359. }
  3360. text = st[i++]; style = styleToClass(st[i++]);
  3361. }
  3362. }
  3363. }
  3364. // DOCUMENT DATA STRUCTURE
  3365. function LeafChunk(lines) {
  3366. this.lines = lines;
  3367. this.parent = null;
  3368. for (var i = 0, e = lines.length, height = 0; i < e; ++i) {
  3369. lines[i].parent = this;
  3370. height += lines[i].height;
  3371. }
  3372. this.height = height;
  3373. }
  3374. LeafChunk.prototype = {
  3375. chunkSize: function() { return this.lines.length; },
  3376. remove: function(at, n, cm) {
  3377. for (var i = at, e = at + n; i < e; ++i) {
  3378. var line = this.lines[i];
  3379. this.height -= line.height;
  3380. cleanUpLine(line);
  3381. signalLater(cm, line, "delete");
  3382. }
  3383. this.lines.splice(at, n);
  3384. },
  3385. collapse: function(lines) {
  3386. lines.splice.apply(lines, [lines.length, 0].concat(this.lines));
  3387. },
  3388. insertHeight: function(at, lines, height) {
  3389. this.height += height;
  3390. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  3391. for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this;
  3392. },
  3393. iterN: function(at, n, op) {
  3394. for (var e = at + n; at < e; ++at)
  3395. if (op(this.lines[at])) return true;
  3396. }
  3397. };
  3398. function BranchChunk(children) {
  3399. this.children = children;
  3400. var size = 0, height = 0;
  3401. for (var i = 0, e = children.length; i < e; ++i) {
  3402. var ch = children[i];
  3403. size += ch.chunkSize(); height += ch.height;
  3404. ch.parent = this;
  3405. }
  3406. this.size = size;
  3407. this.height = height;
  3408. this.parent = null;
  3409. }
  3410. BranchChunk.prototype = {
  3411. chunkSize: function() { return this.size; },
  3412. remove: function(at, n, callbacks) {
  3413. this.size -= n;
  3414. for (var i = 0; i < this.children.length; ++i) {
  3415. var child = this.children[i], sz = child.chunkSize();
  3416. if (at < sz) {
  3417. var rm = Math.min(n, sz - at), oldHeight = child.height;
  3418. child.remove(at, rm, callbacks);
  3419. this.height -= oldHeight - child.height;
  3420. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  3421. if ((n -= rm) == 0) break;
  3422. at = 0;
  3423. } else at -= sz;
  3424. }
  3425. if (this.size - n < 25) {
  3426. var lines = [];
  3427. this.collapse(lines);
  3428. this.children = [new LeafChunk(lines)];
  3429. this.children[0].parent = this;
  3430. }
  3431. },
  3432. collapse: function(lines) {
  3433. for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines);
  3434. },
  3435. insert: function(at, lines) {
  3436. var height = 0;
  3437. for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height;
  3438. this.insertHeight(at, lines, height);
  3439. },
  3440. insertHeight: function(at, lines, height) {
  3441. this.size += lines.length;
  3442. this.height += height;
  3443. for (var i = 0, e = this.children.length; i < e; ++i) {
  3444. var child = this.children[i], sz = child.chunkSize();
  3445. if (at <= sz) {
  3446. child.insertHeight(at, lines, height);
  3447. if (child.lines && child.lines.length > 50) {
  3448. while (child.lines.length > 50) {
  3449. var spilled = child.lines.splice(child.lines.length - 25, 25);
  3450. var newleaf = new LeafChunk(spilled);
  3451. child.height -= newleaf.height;
  3452. this.children.splice(i + 1, 0, newleaf);
  3453. newleaf.parent = this;
  3454. }
  3455. this.maybeSpill();
  3456. }
  3457. break;
  3458. }
  3459. at -= sz;
  3460. }
  3461. },
  3462. maybeSpill: function() {
  3463. if (this.children.length <= 10) return;
  3464. var me = this;
  3465. do {
  3466. var spilled = me.children.splice(me.children.length - 5, 5);
  3467. var sibling = new BranchChunk(spilled);
  3468. if (!me.parent) { // Become the parent node
  3469. var copy = new BranchChunk(me.children);
  3470. copy.parent = me;
  3471. me.children = [copy, sibling];
  3472. me = copy;
  3473. } else {
  3474. me.size -= sibling.size;
  3475. me.height -= sibling.height;
  3476. var myIndex = indexOf(me.parent.children, me);
  3477. me.parent.children.splice(myIndex + 1, 0, sibling);
  3478. }
  3479. sibling.parent = me.parent;
  3480. } while (me.children.length > 10);
  3481. me.parent.maybeSpill();
  3482. },
  3483. iter: function(from, to, op) { this.iterN(from, to - from, op); },
  3484. iterN: function(at, n, op) {
  3485. for (var i = 0, e = this.children.length; i < e; ++i) {
  3486. var child = this.children[i], sz = child.chunkSize();
  3487. if (at < sz) {
  3488. var used = Math.min(n, sz - at);
  3489. if (child.iterN(at, used, op)) return true;
  3490. if ((n -= used) == 0) break;
  3491. at = 0;
  3492. } else at -= sz;
  3493. }
  3494. }
  3495. };
  3496. // LINE UTILITIES
  3497. function getLine(chunk, n) {
  3498. while (!chunk.lines) {
  3499. for (var i = 0;; ++i) {
  3500. var child = chunk.children[i], sz = child.chunkSize();
  3501. if (n < sz) { chunk = child; break; }
  3502. n -= sz;
  3503. }
  3504. }
  3505. return chunk.lines[n];
  3506. }
  3507. function updateLineHeight(line, height) {
  3508. var diff = height - line.height;
  3509. for (var n = line; n; n = n.parent) n.height += diff;
  3510. }
  3511. function lineNo(line) {
  3512. if (line.parent == null) return null;
  3513. var cur = line.parent, no = indexOf(cur.lines, line);
  3514. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  3515. for (var i = 0;; ++i) {
  3516. if (chunk.children[i] == cur) break;
  3517. no += chunk.children[i].chunkSize();
  3518. }
  3519. }
  3520. return no;
  3521. }
  3522. function lineAtHeight(chunk, h) {
  3523. var n = 0;
  3524. outer: do {
  3525. for (var i = 0, e = chunk.children.length; i < e; ++i) {
  3526. var child = chunk.children[i], ch = child.height;
  3527. if (h < ch) { chunk = child; continue outer; }
  3528. h -= ch;
  3529. n += child.chunkSize();
  3530. }
  3531. return n;
  3532. } while (!chunk.lines);
  3533. for (var i = 0, e = chunk.lines.length; i < e; ++i) {
  3534. var line = chunk.lines[i], lh = line.height;
  3535. if (h < lh) break;
  3536. h -= lh;
  3537. }
  3538. return n + i;
  3539. }
  3540. function heightAtLine(cm, lineObj) {
  3541. lineObj = visualLine(cm.view.doc, lineObj);
  3542. var h = 0, chunk = lineObj.parent;
  3543. for (var i = 0; i < chunk.lines.length; ++i) {
  3544. var line = chunk.lines[i];
  3545. if (line == lineObj) break;
  3546. else h += line.height;
  3547. }
  3548. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  3549. for (var i = 0; i < p.children.length; ++i) {
  3550. var cur = p.children[i];
  3551. if (cur == chunk) break;
  3552. else h += cur.height;
  3553. }
  3554. }
  3555. return h;
  3556. }
  3557. function getOrder(line) {
  3558. var order = line.order;
  3559. if (order == null) order = line.order = bidiOrdering(line.text);
  3560. return order;
  3561. }
  3562. // HISTORY
  3563. function makeHistory() {
  3564. return {
  3565. // Arrays of history events. Doing something adds an event to
  3566. // done and clears undo. Undoing moves events from done to
  3567. // undone, redoing moves them in the other direction.
  3568. done: [], undone: [],
  3569. // Used to track when changes can be merged into a single undo
  3570. // event
  3571. lastTime: 0, lastOp: null, lastOrigin: null,
  3572. // Used by the isClean() method
  3573. dirtyCounter: 0
  3574. };
  3575. }
  3576. function addChange(cm, start, added, old, origin, fromBefore, toBefore, fromAfter, toAfter) {
  3577. var history = cm.view.history;
  3578. history.undone.length = 0;
  3579. var time = +new Date, cur = lst(history.done);
  3580. if (cur &&
  3581. (history.lastOp == cm.curOp.id ||
  3582. history.lastOrigin == origin && (origin == "input" || origin == "delete") &&
  3583. history.lastTime > time - 600)) {
  3584. // Merge this change into the last event
  3585. var last = lst(cur.events);
  3586. if (last.start > start + old.length || last.start + last.added < start) {
  3587. // Doesn't intersect with last sub-event, add new sub-event
  3588. cur.events.push({start: start, added: added, old: old});
  3589. } else {
  3590. // Patch up the last sub-event
  3591. var startBefore = Math.max(0, last.start - start),
  3592. endAfter = Math.max(0, (start + old.length) - (last.start + last.added));
  3593. for (var i = startBefore; i > 0; --i) last.old.unshift(old[i - 1]);
  3594. for (var i = endAfter; i > 0; --i) last.old.push(old[old.length - i]);
  3595. if (startBefore) last.start = start;
  3596. last.added += added - (old.length - startBefore - endAfter);
  3597. }
  3598. cur.fromAfter = fromAfter; cur.toAfter = toAfter;
  3599. } else {
  3600. // Can not be merged, start a new event.
  3601. cur = {events: [{start: start, added: added, old: old}],
  3602. fromBefore: fromBefore, toBefore: toBefore, fromAfter: fromAfter, toAfter: toAfter};
  3603. history.done.push(cur);
  3604. while (history.done.length > cm.options.undoDepth)
  3605. history.done.shift();
  3606. if (history.dirtyCounter < 0)
  3607. // The user has made a change after undoing past the last clean state.
  3608. // We can never get back to a clean state now until markClean() is called.
  3609. history.dirtyCounter = NaN;
  3610. else
  3611. history.dirtyCounter++;
  3612. }
  3613. history.lastTime = time;
  3614. history.lastOp = cm.curOp.id;
  3615. history.lastOrigin = origin;
  3616. }
  3617. // EVENT OPERATORS
  3618. function stopMethod() {e_stop(this);}
  3619. // Ensure an event has a stop method.
  3620. function addStop(event) {
  3621. if (!event.stop) event.stop = stopMethod;
  3622. return event;
  3623. }
  3624. function e_preventDefault(e) {
  3625. if (e.preventDefault) e.preventDefault();
  3626. else e.returnValue = false;
  3627. }
  3628. function e_stopPropagation(e) {
  3629. if (e.stopPropagation) e.stopPropagation();
  3630. else e.cancelBubble = true;
  3631. }
  3632. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  3633. CodeMirror.e_stop = e_stop;
  3634. CodeMirror.e_preventDefault = e_preventDefault;
  3635. CodeMirror.e_stopPropagation = e_stopPropagation;
  3636. function e_target(e) {return e.target || e.srcElement;}
  3637. function e_button(e) {
  3638. var b = e.which;
  3639. if (b == null) {
  3640. if (e.button & 1) b = 1;
  3641. else if (e.button & 2) b = 3;
  3642. else if (e.button & 4) b = 2;
  3643. }
  3644. if (mac && e.ctrlKey && b == 1) b = 3;
  3645. return b;
  3646. }
  3647. // Allow 3rd-party code to override event properties by adding an override
  3648. // object to an event object.
  3649. function e_prop(e, prop) {
  3650. var overridden = e.override && e.override.hasOwnProperty(prop);
  3651. return overridden ? e.override[prop] : e[prop];
  3652. }
  3653. // EVENT HANDLING
  3654. function on(emitter, type, f) {
  3655. if (emitter.addEventListener)
  3656. emitter.addEventListener(type, f, false);
  3657. else if (emitter.attachEvent)
  3658. emitter.attachEvent("on" + type, f);
  3659. else {
  3660. var map = emitter._handlers || (emitter._handlers = {});
  3661. var arr = map[type] || (map[type] = []);
  3662. arr.push(f);
  3663. }
  3664. }
  3665. function off(emitter, type, f) {
  3666. if (emitter.removeEventListener)
  3667. emitter.removeEventListener(type, f, false);
  3668. else if (emitter.detachEvent)
  3669. emitter.detachEvent("on" + type, f);
  3670. else {
  3671. var arr = emitter._handlers && emitter._handlers[type];
  3672. if (!arr) return;
  3673. for (var i = 0; i < arr.length; ++i)
  3674. if (arr[i] == f) { arr.splice(i, 1); break; }
  3675. }
  3676. }
  3677. function signal(emitter, type /*, values...*/) {
  3678. var arr = emitter._handlers && emitter._handlers[type];
  3679. if (!arr) return;
  3680. var args = Array.prototype.slice.call(arguments, 2);
  3681. for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
  3682. }
  3683. function signalLater(cm, emitter, type /*, values...*/) {
  3684. var arr = emitter._handlers && emitter._handlers[type];
  3685. if (!arr) return;
  3686. var args = Array.prototype.slice.call(arguments, 3), flist = cm.curOp && cm.curOp.delayedCallbacks;
  3687. function bnd(f) {return function(){f.apply(null, args);};};
  3688. for (var i = 0; i < arr.length; ++i)
  3689. if (flist) flist.push(bnd(arr[i]));
  3690. else arr[i].apply(null, args);
  3691. }
  3692. function hasHandler(emitter, type) {
  3693. var arr = emitter._handlers && emitter._handlers[type];
  3694. return arr && arr.length > 0;
  3695. }
  3696. CodeMirror.on = on; CodeMirror.off = off; CodeMirror.signal = signal;
  3697. // MISC UTILITIES
  3698. // Number of pixels added to scroller and sizer to hide scrollbar
  3699. var scrollerCutOff = 30;
  3700. // Returned or thrown by various protocols to signal 'I'm not
  3701. // handling this'.
  3702. var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
  3703. function Delayed() {this.id = null;}
  3704. Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
  3705. // Counts the column offset in a string, taking tabs into account.
  3706. // Used mostly to find indentation.
  3707. function countColumn(string, end, tabSize) {
  3708. if (end == null) {
  3709. end = string.search(/[^\s\u00a0]/);
  3710. if (end == -1) end = string.length;
  3711. }
  3712. for (var i = 0, n = 0; i < end; ++i) {
  3713. if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
  3714. else ++n;
  3715. }
  3716. return n;
  3717. }
  3718. CodeMirror.countColumn = countColumn;
  3719. var spaceStrs = [""];
  3720. function spaceStr(n) {
  3721. while (spaceStrs.length <= n)
  3722. spaceStrs.push(lst(spaceStrs) + " ");
  3723. return spaceStrs[n];
  3724. }
  3725. function lst(arr) { return arr[arr.length-1]; }
  3726. function selectInput(node) {
  3727. if (ios) { // Mobile Safari apparently has a bug where select() is broken.
  3728. node.selectionStart = 0;
  3729. node.selectionEnd = node.value.length;
  3730. } else node.select();
  3731. }
  3732. function indexOf(collection, elt) {
  3733. if (collection.indexOf) return collection.indexOf(elt);
  3734. for (var i = 0, e = collection.length; i < e; ++i)
  3735. if (collection[i] == elt) return i;
  3736. return -1;
  3737. }
  3738. function emptyArray(size) {
  3739. for (var a = [], i = 0; i < size; ++i) a.push(undefined);
  3740. return a;
  3741. }
  3742. function bind(f) {
  3743. var args = Array.prototype.slice.call(arguments, 1);
  3744. return function(){return f.apply(null, args);};
  3745. }
  3746. var nonASCIISingleCaseWordChar = /[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc]/;
  3747. function isWordChar(ch) {
  3748. return /\w/.test(ch) || ch > "\x80" &&
  3749. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
  3750. }
  3751. function isEmpty(obj) {
  3752. var c = 0;
  3753. for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) ++c;
  3754. return !c;
  3755. }
  3756. var isExtendingChar = /[\u0300-\u036F\u0483-\u0487\u0488-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\uA66F\uA670-\uA672\uA674-\uA67D\uA69F]/;
  3757. // DOM UTILITIES
  3758. function elt(tag, content, className, style) {
  3759. var e = document.createElement(tag);
  3760. if (className) e.className = className;
  3761. if (style) e.style.cssText = style;
  3762. if (typeof content == "string") setTextContent(e, content);
  3763. else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
  3764. return e;
  3765. }
  3766. function removeChildren(e) {
  3767. e.innerHTML = "";
  3768. return e;
  3769. }
  3770. function removeChildrenAndAdd(parent, e) {
  3771. return removeChildren(parent).appendChild(e);
  3772. }
  3773. function setTextContent(e, str) {
  3774. if (ie_lt9) {
  3775. e.innerHTML = "";
  3776. e.appendChild(document.createTextNode(str));
  3777. } else e.textContent = str;
  3778. }
  3779. // FEATURE DETECTION
  3780. // Detect drag-and-drop
  3781. var dragAndDrop = function() {
  3782. // There is *some* kind of drag-and-drop support in IE6-8, but I
  3783. // couldn't get it to work yet.
  3784. if (ie_lt9) return false;
  3785. var div = elt('div');
  3786. return "draggable" in div || "dragDrop" in div;
  3787. }();
  3788. // For a reason I have yet to figure out, some browsers disallow
  3789. // word wrapping between certain characters *only* if a new inline
  3790. // element is started between them. This makes it hard to reliably
  3791. // measure the position of things, since that requires inserting an
  3792. // extra span. This terribly fragile set of regexps matches the
  3793. // character combinations that suffer from this phenomenon on the
  3794. // various browsers.
  3795. var spanAffectsWrapping = /^$/; // Won't match any two-character string
  3796. if (gecko) spanAffectsWrapping = /$'/;
  3797. else if (safari) spanAffectsWrapping = /\-[^ \-?]|\?[^ !'\"\),.\-\/:;\?\]\}]/;
  3798. else if (chrome) spanAffectsWrapping = /\-[^ \-\.?]|\?[^ \-\.?\]\}:;!'\"\),\/]|[\.!\"#&%\)*+,:;=>\]|\}~][\(\{\[<]|\$'/;
  3799. var knownScrollbarWidth;
  3800. function scrollbarWidth(measure) {
  3801. if (knownScrollbarWidth != null) return knownScrollbarWidth;
  3802. var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll");
  3803. removeChildrenAndAdd(measure, test);
  3804. if (test.offsetWidth)
  3805. knownScrollbarWidth = test.offsetHeight - test.clientHeight;
  3806. return knownScrollbarWidth || 0;
  3807. }
  3808. var zwspSupported;
  3809. function zeroWidthElement(measure) {
  3810. if (zwspSupported == null) {
  3811. var test = elt("span", "\u200b");
  3812. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  3813. if (measure.firstChild.offsetHeight != 0)
  3814. zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_lt8;
  3815. }
  3816. if (zwspSupported) return elt("span", "\u200b");
  3817. else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  3818. }
  3819. // See if "".split is the broken IE version, if so, provide an
  3820. // alternative way to split lines.
  3821. var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
  3822. var pos = 0, result = [], l = string.length;
  3823. while (pos <= l) {
  3824. var nl = string.indexOf("\n", pos);
  3825. if (nl == -1) nl = string.length;
  3826. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  3827. var rt = line.indexOf("\r");
  3828. if (rt != -1) {
  3829. result.push(line.slice(0, rt));
  3830. pos += rt + 1;
  3831. } else {
  3832. result.push(line);
  3833. pos = nl + 1;
  3834. }
  3835. }
  3836. return result;
  3837. } : function(string){return string.split(/\r\n?|\n/);};
  3838. CodeMirror.splitLines = splitLines;
  3839. var hasSelection = window.getSelection ? function(te) {
  3840. try { return te.selectionStart != te.selectionEnd; }
  3841. catch(e) { return false; }
  3842. } : function(te) {
  3843. try {var range = te.ownerDocument.selection.createRange();}
  3844. catch(e) {}
  3845. if (!range || range.parentElement() != te) return false;
  3846. return range.compareEndPoints("StartToEnd", range) != 0;
  3847. };
  3848. var hasCopyEvent = (function() {
  3849. var e = elt("div");
  3850. if ("oncopy" in e) return true;
  3851. e.setAttribute("oncopy", "return;");
  3852. return typeof e.oncopy == 'function';
  3853. })();
  3854. // KEY NAMING
  3855. var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  3856. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  3857. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  3858. 46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete",
  3859. 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  3860. 221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home",
  3861. 63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"};
  3862. CodeMirror.keyNames = keyNames;
  3863. (function() {
  3864. // Number keys
  3865. for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i);
  3866. // Alphabetic keys
  3867. for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
  3868. // Function keys
  3869. for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
  3870. })();
  3871. // BIDI HELPERS
  3872. function iterateBidiSections(order, from, to, f) {
  3873. if (!order) return f(from, to, "ltr");
  3874. for (var i = 0; i < order.length; ++i) {
  3875. var part = order[i];
  3876. if (part.from < to && part.to > from)
  3877. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
  3878. }
  3879. }
  3880. function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
  3881. function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
  3882. function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
  3883. function lineRight(line) {
  3884. var order = getOrder(line);
  3885. if (!order) return line.text.length;
  3886. return bidiRight(lst(order));
  3887. }
  3888. function lineStart(cm, lineN) {
  3889. var line = getLine(cm.view.doc, lineN);
  3890. var visual = visualLine(cm.view.doc, line);
  3891. if (visual != line) lineN = lineNo(visual);
  3892. var order = getOrder(visual);
  3893. var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
  3894. return {line: lineN, ch: ch};
  3895. }
  3896. function lineEnd(cm, lineNo) {
  3897. var merged, line;
  3898. while (merged = collapsedSpanAtEnd(line = getLine(cm.view.doc, lineNo)))
  3899. lineNo = merged.find().to.line;
  3900. var order = getOrder(line);
  3901. var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
  3902. return {line: lineNo, ch: ch};
  3903. }
  3904. // This is somewhat involved. It is needed in order to move
  3905. // 'visually' through bi-directional text -- i.e., pressing left
  3906. // should make the cursor go left, even when in RTL text. The
  3907. // tricky part is the 'jumps', where RTL and LTR text touch each
  3908. // other. This often requires the cursor offset to move more than
  3909. // one unit, in order to visually move one unit.
  3910. function moveVisually(line, start, dir, byUnit) {
  3911. var bidi = getOrder(line);
  3912. if (!bidi) return moveLogically(line, start, dir, byUnit);
  3913. var moveOneUnit = byUnit ? function(pos, dir) {
  3914. do pos += dir;
  3915. while (pos > 0 && isExtendingChar.test(line.text.charAt(pos)));
  3916. return pos;
  3917. } : function(pos, dir) { return pos + dir; };
  3918. var linedir = bidi[0].level;
  3919. for (var i = 0; i < bidi.length; ++i) {
  3920. var part = bidi[i], sticky = part.level % 2 == linedir;
  3921. if ((part.from < start && part.to > start) ||
  3922. (sticky && (part.from == start || part.to == start))) break;
  3923. }
  3924. var target = moveOneUnit(start, part.level % 2 ? -dir : dir);
  3925. while (target != null) {
  3926. if (part.level % 2 == linedir) {
  3927. if (target < part.from || target > part.to) {
  3928. part = bidi[i += dir];
  3929. target = part && (dir > 0 == part.level % 2 ? moveOneUnit(part.to, -1) : moveOneUnit(part.from, 1));
  3930. } else break;
  3931. } else {
  3932. if (target == bidiLeft(part)) {
  3933. part = bidi[--i];
  3934. target = part && bidiRight(part);
  3935. } else if (target == bidiRight(part)) {
  3936. part = bidi[++i];
  3937. target = part && bidiLeft(part);
  3938. } else break;
  3939. }
  3940. }
  3941. return target < 0 || target > line.text.length ? null : target;
  3942. }
  3943. function moveLogically(line, start, dir, byUnit) {
  3944. var target = start + dir;
  3945. if (byUnit) while (target > 0 && isExtendingChar.test(line.text.charAt(target))) target += dir;
  3946. return target < 0 || target > line.text.length ? null : target;
  3947. }
  3948. // Bidirectional ordering algorithm
  3949. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  3950. // that this (partially) implements.
  3951. // One-char codes used for character types:
  3952. // L (L): Left-to-Right
  3953. // R (R): Right-to-Left
  3954. // r (AL): Right-to-Left Arabic
  3955. // 1 (EN): European Number
  3956. // + (ES): European Number Separator
  3957. // % (ET): European Number Terminator
  3958. // n (AN): Arabic Number
  3959. // , (CS): Common Number Separator
  3960. // m (NSM): Non-Spacing Mark
  3961. // b (BN): Boundary Neutral
  3962. // s (B): Paragraph Separator
  3963. // t (S): Segment Separator
  3964. // w (WS): Whitespace
  3965. // N (ON): Other Neutrals
  3966. // Returns null if characters are ordered as they appear
  3967. // (left-to-right), or an array of sections ({from, to, level}
  3968. // objects) in the order in which they occur visually.
  3969. var bidiOrdering = (function() {
  3970. // Character types for codepoints 0 to 0xff
  3971. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLL";
  3972. // Character types for codepoints 0x600 to 0x6ff
  3973. var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmmrrrrrrrrrrrrrrrrrr";
  3974. function charType(code) {
  3975. if (code <= 0xff) return lowTypes.charAt(code);
  3976. else if (0x590 <= code && code <= 0x5f4) return "R";
  3977. else if (0x600 <= code && code <= 0x6ff) return arabicTypes.charAt(code - 0x600);
  3978. else if (0x700 <= code && code <= 0x8ac) return "r";
  3979. else return "L";
  3980. }
  3981. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  3982. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  3983. return function charOrdering(str) {
  3984. if (!bidiRE.test(str)) return false;
  3985. var len = str.length, types = [], startType = null;
  3986. for (var i = 0, type; i < len; ++i) {
  3987. types.push(type = charType(str.charCodeAt(i)));
  3988. if (startType == null) {
  3989. if (type == "L") startType = "L";
  3990. else if (type == "R" || type == "r") startType = "R";
  3991. }
  3992. }
  3993. if (startType == null) startType = "L";
  3994. // W1. Examine each non-spacing mark (NSM) in the level run, and
  3995. // change the type of the NSM to the type of the previous
  3996. // character. If the NSM is at the start of the level run, it will
  3997. // get the type of sor.
  3998. for (var i = 0, prev = startType; i < len; ++i) {
  3999. var type = types[i];
  4000. if (type == "m") types[i] = prev;
  4001. else prev = type;
  4002. }
  4003. // W2. Search backwards from each instance of a European number
  4004. // until the first strong type (R, L, AL, or sor) is found. If an
  4005. // AL is found, change the type of the European number to Arabic
  4006. // number.
  4007. // W3. Change all ALs to R.
  4008. for (var i = 0, cur = startType; i < len; ++i) {
  4009. var type = types[i];
  4010. if (type == "1" && cur == "r") types[i] = "n";
  4011. else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
  4012. }
  4013. // W4. A single European separator between two European numbers
  4014. // changes to a European number. A single common separator between
  4015. // two numbers of the same type changes to that type.
  4016. for (var i = 1, prev = types[0]; i < len - 1; ++i) {
  4017. var type = types[i];
  4018. if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
  4019. else if (type == "," && prev == types[i+1] &&
  4020. (prev == "1" || prev == "n")) types[i] = prev;
  4021. prev = type;
  4022. }
  4023. // W5. A sequence of European terminators adjacent to European
  4024. // numbers changes to all European numbers.
  4025. // W6. Otherwise, separators and terminators change to Other
  4026. // Neutral.
  4027. for (var i = 0; i < len; ++i) {
  4028. var type = types[i];
  4029. if (type == ",") types[i] = "N";
  4030. else if (type == "%") {
  4031. for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
  4032. var replace = (i && types[i-1] == "!") || (end < len - 1 && types[end] == "1") ? "1" : "N";
  4033. for (var j = i; j < end; ++j) types[j] = replace;
  4034. i = end - 1;
  4035. }
  4036. }
  4037. // W7. Search backwards from each instance of a European number
  4038. // until the first strong type (R, L, or sor) is found. If an L is
  4039. // found, then change the type of the European number to L.
  4040. for (var i = 0, cur = startType; i < len; ++i) {
  4041. var type = types[i];
  4042. if (cur == "L" && type == "1") types[i] = "L";
  4043. else if (isStrong.test(type)) cur = type;
  4044. }
  4045. // N1. A sequence of neutrals takes the direction of the
  4046. // surrounding strong text if the text on both sides has the same
  4047. // direction. European and Arabic numbers act as if they were R in
  4048. // terms of their influence on neutrals. Start-of-level-run (sor)
  4049. // and end-of-level-run (eor) are used at level run boundaries.
  4050. // N2. Any remaining neutrals take the embedding direction.
  4051. for (var i = 0; i < len; ++i) {
  4052. if (isNeutral.test(types[i])) {
  4053. for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
  4054. var before = (i ? types[i-1] : startType) == "L";
  4055. var after = (end < len - 1 ? types[end] : startType) == "L";
  4056. var replace = before || after ? "L" : "R";
  4057. for (var j = i; j < end; ++j) types[j] = replace;
  4058. i = end - 1;
  4059. }
  4060. }
  4061. // Here we depart from the documented algorithm, in order to avoid
  4062. // building up an actual levels array. Since there are only three
  4063. // levels (0, 1, 2) in an implementation that doesn't take
  4064. // explicit embedding into account, we can build up the order on
  4065. // the fly, without following the level-based algorithm.
  4066. var order = [], m;
  4067. for (var i = 0; i < len;) {
  4068. if (countsAsLeft.test(types[i])) {
  4069. var start = i;
  4070. for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
  4071. order.push({from: start, to: i, level: 0});
  4072. } else {
  4073. var pos = i, at = order.length;
  4074. for (++i; i < len && types[i] != "L"; ++i) {}
  4075. for (var j = pos; j < i;) {
  4076. if (countsAsNum.test(types[j])) {
  4077. if (pos < j) order.splice(at, 0, {from: pos, to: j, level: 1});
  4078. var nstart = j;
  4079. for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
  4080. order.splice(at, 0, {from: nstart, to: j, level: 2});
  4081. pos = j;
  4082. } else ++j;
  4083. }
  4084. if (pos < i) order.splice(at, 0, {from: pos, to: i, level: 1});
  4085. }
  4086. }
  4087. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  4088. order[0].from = m[0].length;
  4089. order.unshift({from: 0, to: m[0].length, level: 0});
  4090. }
  4091. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  4092. lst(order).to -= m[0].length;
  4093. order.push({from: len - m[0].length, to: len, level: 0});
  4094. }
  4095. if (order[0].level != lst(order).level)
  4096. order.push({from: len, to: len, level: order[0].level});
  4097. return order;
  4098. };
  4099. })();
  4100. // THE END
  4101. CodeMirror.version = "3.0";
  4102. return CodeMirror;
  4103. })();