codemirror.js 224 KB

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