codemirror.js 211 KB

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