codemirror.js 337 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. // This is CodeMirror (http://codemirror.net), a code editor
  4. // implemented in JavaScript on top of the browser's DOM.
  5. //
  6. // You can find some technical background for some of the code below
  7. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  8. (function(mod) {
  9. if (typeof exports == "object" && typeof module == "object") // CommonJS
  10. module.exports = mod();
  11. else if (typeof define == "function" && define.amd) // AMD
  12. return define([], mod);
  13. else // Plain browser env
  14. this.CodeMirror = mod();
  15. })(function() {
  16. "use strict";
  17. // BROWSER SNIFFING
  18. // Kludges for bugs and behavior differences that can't be feature
  19. // detected are enabled based on userAgent etc sniffing.
  20. var gecko = /gecko\/\d/i.test(navigator.userAgent);
  21. var ie_upto10 = /MSIE \d/.test(navigator.userAgent);
  22. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
  23. var ie = ie_upto10 || ie_11up;
  24. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
  25. var webkit = /WebKit\//.test(navigator.userAgent);
  26. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
  27. var chrome = /Chrome\//.test(navigator.userAgent);
  28. var presto = /Opera\//.test(navigator.userAgent);
  29. var safari = /Apple Computer/.test(navigator.vendor);
  30. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
  31. var phantom = /PhantomJS/.test(navigator.userAgent);
  32. var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
  33. // This is woefully incomplete. Suggestions for alternative methods welcome.
  34. var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
  35. var mac = ios || /Mac/.test(navigator.platform);
  36. var windows = /win/i.test(navigator.platform);
  37. var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
  38. if (presto_version) presto_version = Number(presto_version[1]);
  39. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  40. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  41. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  42. var captureRightClick = gecko || (ie && ie_version >= 9);
  43. // Optimize some code when these features are not used.
  44. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  45. // EDITOR CONSTRUCTOR
  46. // A CodeMirror instance represents an editor. This is the object
  47. // that user code is usually dealing with.
  48. function CodeMirror(place, options) {
  49. if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
  50. this.options = options = options ? copyObj(options) : {};
  51. // Determine effective options based on given values and defaults.
  52. copyObj(defaults, options, false);
  53. setGuttersForLineNumbers(options);
  54. var doc = options.value;
  55. if (typeof doc == "string") doc = new Doc(doc, options.mode);
  56. this.doc = doc;
  57. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  58. var display = this.display = new Display(place, doc, input);
  59. display.wrapper.CodeMirror = this;
  60. updateGutters(this);
  61. themeChanged(this);
  62. if (options.lineWrapping)
  63. this.display.wrapper.className += " CodeMirror-wrap";
  64. if (options.autofocus && !mobile) display.input.focus();
  65. initScrollbars(this);
  66. this.state = {
  67. keyMaps: [], // stores maps added by addKeyMap
  68. overlays: [], // highlighting overlays, as added by addOverlay
  69. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  70. overwrite: false,
  71. delayingBlurEvent: false,
  72. focused: false,
  73. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  74. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  75. draggingText: false,
  76. highlight: new Delayed(), // stores highlight worker timeout
  77. keySeq: null, // Unfinished key sequence
  78. specialChars: null
  79. };
  80. var cm = this;
  81. // Override magic textarea content restore that IE sometimes does
  82. // on our hidden textarea on reload
  83. if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
  84. registerEventHandlers(this);
  85. ensureGlobalHandlers();
  86. startOperation(this);
  87. this.curOp.forceUpdate = true;
  88. attachDoc(this, doc);
  89. if ((options.autofocus && !mobile) || cm.hasFocus())
  90. setTimeout(bind(onFocus, this), 20);
  91. else
  92. onBlur(this);
  93. for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
  94. optionHandlers[opt](this, options[opt], Init);
  95. maybeUpdateLineNumberWidth(this);
  96. if (options.finishInit) options.finishInit(this);
  97. for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
  98. endOperation(this);
  99. // Suppress optimizelegibility in Webkit, since it breaks text
  100. // measuring on line wrapping boundaries.
  101. if (webkit && options.lineWrapping &&
  102. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  103. display.lineDiv.style.textRendering = "auto";
  104. }
  105. // DISPLAY CONSTRUCTOR
  106. // The display handles the DOM integration, both for input reading
  107. // and content drawing. It holds references to DOM nodes and
  108. // display-related state.
  109. function Display(place, doc, input) {
  110. var d = this;
  111. this.input = input;
  112. // Covers bottom-right square when both scrollbars are present.
  113. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  114. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  115. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  116. // and h scrollbar is present.
  117. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  118. d.gutterFiller.setAttribute("cm-not-content", "true");
  119. // Will contain the actual code, positioned to cover the viewport.
  120. d.lineDiv = elt("div", null, "CodeMirror-code");
  121. // Elements are added to these to represent selection and cursors.
  122. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  123. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  124. // A visibility: hidden element used to find the size of things.
  125. d.measure = elt("div", null, "CodeMirror-measure");
  126. // When lines outside of the viewport are measured, they are drawn in this.
  127. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  128. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  129. d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  130. null, "position: relative; outline: none");
  131. // Moved around its parent to cover visible view.
  132. d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
  133. // Set to the height of the document, allowing scrolling.
  134. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  135. d.sizerWidth = null;
  136. // Behavior of elts with overflow: auto and padding is
  137. // inconsistent across browsers. This is used to ensure the
  138. // scrollable area is big enough.
  139. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  140. // Will contain the gutters, if any.
  141. d.gutters = elt("div", null, "CodeMirror-gutters");
  142. d.lineGutter = null;
  143. // Actual scrollable element.
  144. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  145. d.scroller.setAttribute("tabIndex", "-1");
  146. // The element in which the editor lives.
  147. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  148. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  149. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  150. if (!webkit && !(gecko && mobile)) d.scroller.draggable = true;
  151. if (place) {
  152. if (place.appendChild) place.appendChild(d.wrapper);
  153. else place(d.wrapper);
  154. }
  155. // Current rendered range (may be bigger than the view window).
  156. d.viewFrom = d.viewTo = doc.first;
  157. d.reportedViewFrom = d.reportedViewTo = doc.first;
  158. // Information about the rendered lines.
  159. d.view = [];
  160. d.renderedView = null;
  161. // Holds info about a single rendered line when it was rendered
  162. // for measurement, while not in view.
  163. d.externalMeasured = null;
  164. // Empty space (in pixels) above the view
  165. d.viewOffset = 0;
  166. d.lastWrapHeight = d.lastWrapWidth = 0;
  167. d.updateLineNumbers = null;
  168. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  169. d.scrollbarsClipped = false;
  170. // Used to only resize the line number gutter when necessary (when
  171. // the amount of lines crosses a boundary that makes its width change)
  172. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  173. // Set to true when a non-horizontal-scrolling line widget is
  174. // added. As an optimization, line widget aligning is skipped when
  175. // this is false.
  176. d.alignWidgets = false;
  177. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  178. // Tracks the maximum line length so that the horizontal scrollbar
  179. // can be kept static when scrolling.
  180. d.maxLine = null;
  181. d.maxLineLength = 0;
  182. d.maxLineChanged = false;
  183. // Used for measuring wheel scrolling granularity
  184. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  185. // True when shift is held down.
  186. d.shift = false;
  187. // Used to track whether anything happened since the context menu
  188. // was opened.
  189. d.selForContextMenu = null;
  190. d.activeTouch = null;
  191. input.init(d);
  192. }
  193. // STATE UPDATES
  194. // Used to get the editor into a consistent state again when options change.
  195. function loadMode(cm) {
  196. cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
  197. resetModeState(cm);
  198. }
  199. function resetModeState(cm) {
  200. cm.doc.iter(function(line) {
  201. if (line.stateAfter) line.stateAfter = null;
  202. if (line.styles) line.styles = null;
  203. });
  204. cm.doc.frontier = cm.doc.first;
  205. startWorker(cm, 100);
  206. cm.state.modeGen++;
  207. if (cm.curOp) regChange(cm);
  208. }
  209. function wrappingChanged(cm) {
  210. if (cm.options.lineWrapping) {
  211. addClass(cm.display.wrapper, "CodeMirror-wrap");
  212. cm.display.sizer.style.minWidth = "";
  213. cm.display.sizerWidth = null;
  214. } else {
  215. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  216. findMaxLine(cm);
  217. }
  218. estimateLineHeights(cm);
  219. regChange(cm);
  220. clearCaches(cm);
  221. setTimeout(function(){updateScrollbars(cm);}, 100);
  222. }
  223. // Returns a function that estimates the height of a line, to use as
  224. // first approximation until the line becomes visible (and is thus
  225. // properly measurable).
  226. function estimateHeight(cm) {
  227. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  228. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  229. return function(line) {
  230. if (lineIsHidden(cm.doc, line)) return 0;
  231. var widgetsHeight = 0;
  232. if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
  233. if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
  234. }
  235. if (wrapping)
  236. return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
  237. else
  238. return widgetsHeight + th;
  239. };
  240. }
  241. function estimateLineHeights(cm) {
  242. var doc = cm.doc, est = estimateHeight(cm);
  243. doc.iter(function(line) {
  244. var estHeight = est(line);
  245. if (estHeight != line.height) updateLineHeight(line, estHeight);
  246. });
  247. }
  248. function themeChanged(cm) {
  249. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  250. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  251. clearCaches(cm);
  252. }
  253. function guttersChanged(cm) {
  254. updateGutters(cm);
  255. regChange(cm);
  256. setTimeout(function(){alignHorizontally(cm);}, 20);
  257. }
  258. // Rebuild the gutter elements, ensure the margin to the left of the
  259. // code matches their width.
  260. function updateGutters(cm) {
  261. var gutters = cm.display.gutters, specs = cm.options.gutters;
  262. removeChildren(gutters);
  263. for (var i = 0; i < specs.length; ++i) {
  264. var gutterClass = specs[i];
  265. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
  266. if (gutterClass == "CodeMirror-linenumbers") {
  267. cm.display.lineGutter = gElt;
  268. gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
  269. }
  270. }
  271. gutters.style.display = i ? "" : "none";
  272. updateGutterSpace(cm);
  273. }
  274. function updateGutterSpace(cm) {
  275. var width = cm.display.gutters.offsetWidth;
  276. cm.display.sizer.style.marginLeft = width + "px";
  277. }
  278. // Compute the character length of a line, taking into account
  279. // collapsed ranges (see markText) that might hide parts, and join
  280. // other lines onto it.
  281. function lineLength(line) {
  282. if (line.height == 0) return 0;
  283. var len = line.text.length, merged, cur = line;
  284. while (merged = collapsedSpanAtStart(cur)) {
  285. var found = merged.find(0, true);
  286. cur = found.from.line;
  287. len += found.from.ch - found.to.ch;
  288. }
  289. cur = line;
  290. while (merged = collapsedSpanAtEnd(cur)) {
  291. var found = merged.find(0, true);
  292. len -= cur.text.length - found.from.ch;
  293. cur = found.to.line;
  294. len += cur.text.length - found.to.ch;
  295. }
  296. return len;
  297. }
  298. // Find the longest line in the document.
  299. function findMaxLine(cm) {
  300. var d = cm.display, doc = cm.doc;
  301. d.maxLine = getLine(doc, doc.first);
  302. d.maxLineLength = lineLength(d.maxLine);
  303. d.maxLineChanged = true;
  304. doc.iter(function(line) {
  305. var len = lineLength(line);
  306. if (len > d.maxLineLength) {
  307. d.maxLineLength = len;
  308. d.maxLine = line;
  309. }
  310. });
  311. }
  312. // Make sure the gutters options contains the element
  313. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  314. function setGuttersForLineNumbers(options) {
  315. var found = indexOf(options.gutters, "CodeMirror-linenumbers");
  316. if (found == -1 && options.lineNumbers) {
  317. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
  318. } else if (found > -1 && !options.lineNumbers) {
  319. options.gutters = options.gutters.slice(0);
  320. options.gutters.splice(found, 1);
  321. }
  322. }
  323. // SCROLLBARS
  324. // Prepare DOM reads needed to update the scrollbars. Done in one
  325. // shot to minimize update/measure roundtrips.
  326. function measureForScrollbars(cm) {
  327. var d = cm.display, gutterW = d.gutters.offsetWidth;
  328. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  329. return {
  330. clientHeight: d.scroller.clientHeight,
  331. viewHeight: d.wrapper.clientHeight,
  332. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  333. viewWidth: d.wrapper.clientWidth,
  334. barLeft: cm.options.fixedGutter ? gutterW : 0,
  335. docHeight: docH,
  336. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  337. nativeBarWidth: d.nativeBarWidth,
  338. gutterWidth: gutterW
  339. };
  340. }
  341. function NativeScrollbars(place, scroll, cm) {
  342. this.cm = cm;
  343. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  344. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  345. place(vert); place(horiz);
  346. on(vert, "scroll", function() {
  347. if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
  348. });
  349. on(horiz, "scroll", function() {
  350. if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
  351. });
  352. this.checkedOverlay = false;
  353. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  354. if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
  355. }
  356. NativeScrollbars.prototype = copyObj({
  357. update: function(measure) {
  358. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  359. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  360. var sWidth = measure.nativeBarWidth;
  361. if (needsV) {
  362. this.vert.style.display = "block";
  363. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  364. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  365. // A bug in IE8 can cause this value to be negative, so guard it.
  366. this.vert.firstChild.style.height =
  367. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  368. } else {
  369. this.vert.style.display = "";
  370. this.vert.firstChild.style.height = "0";
  371. }
  372. if (needsH) {
  373. this.horiz.style.display = "block";
  374. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  375. this.horiz.style.left = measure.barLeft + "px";
  376. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  377. this.horiz.firstChild.style.width =
  378. (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  379. } else {
  380. this.horiz.style.display = "";
  381. this.horiz.firstChild.style.width = "0";
  382. }
  383. if (!this.checkedOverlay && measure.clientHeight > 0) {
  384. if (sWidth == 0) this.overlayHack();
  385. this.checkedOverlay = true;
  386. }
  387. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
  388. },
  389. setScrollLeft: function(pos) {
  390. if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
  391. },
  392. setScrollTop: function(pos) {
  393. if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
  394. },
  395. overlayHack: function() {
  396. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  397. this.horiz.style.minHeight = this.vert.style.minWidth = w;
  398. var self = this;
  399. var barMouseDown = function(e) {
  400. if (e_target(e) != self.vert && e_target(e) != self.horiz)
  401. operation(self.cm, onMouseDown)(e);
  402. };
  403. on(this.vert, "mousedown", barMouseDown);
  404. on(this.horiz, "mousedown", barMouseDown);
  405. },
  406. clear: function() {
  407. var parent = this.horiz.parentNode;
  408. parent.removeChild(this.horiz);
  409. parent.removeChild(this.vert);
  410. }
  411. }, NativeScrollbars.prototype);
  412. function NullScrollbars() {}
  413. NullScrollbars.prototype = copyObj({
  414. update: function() { return {bottom: 0, right: 0}; },
  415. setScrollLeft: function() {},
  416. setScrollTop: function() {},
  417. clear: function() {}
  418. }, NullScrollbars.prototype);
  419. CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  420. function initScrollbars(cm) {
  421. if (cm.display.scrollbars) {
  422. cm.display.scrollbars.clear();
  423. if (cm.display.scrollbars.addClass)
  424. rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  425. }
  426. cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
  427. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  428. // Prevent clicks in the scrollbars from killing focus
  429. on(node, "mousedown", function() {
  430. if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
  431. });
  432. node.setAttribute("cm-not-content", "true");
  433. }, function(pos, axis) {
  434. if (axis == "horizontal") setScrollLeft(cm, pos);
  435. else setScrollTop(cm, pos);
  436. }, cm);
  437. if (cm.display.scrollbars.addClass)
  438. addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  439. }
  440. function updateScrollbars(cm, measure) {
  441. if (!measure) measure = measureForScrollbars(cm);
  442. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  443. updateScrollbarsInner(cm, measure);
  444. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  445. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  446. updateHeightsInViewport(cm);
  447. updateScrollbarsInner(cm, measureForScrollbars(cm));
  448. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  449. }
  450. }
  451. // Re-synchronize the fake scrollbars with the actual size of the
  452. // content.
  453. function updateScrollbarsInner(cm, measure) {
  454. var d = cm.display;
  455. var sizes = d.scrollbars.update(measure);
  456. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  457. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  458. if (sizes.right && sizes.bottom) {
  459. d.scrollbarFiller.style.display = "block";
  460. d.scrollbarFiller.style.height = sizes.bottom + "px";
  461. d.scrollbarFiller.style.width = sizes.right + "px";
  462. } else d.scrollbarFiller.style.display = "";
  463. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  464. d.gutterFiller.style.display = "block";
  465. d.gutterFiller.style.height = sizes.bottom + "px";
  466. d.gutterFiller.style.width = measure.gutterWidth + "px";
  467. } else d.gutterFiller.style.display = "";
  468. }
  469. // Compute the lines that are visible in a given viewport (defaults
  470. // the the current scroll position). viewport may contain top,
  471. // height, and ensure (see op.scrollToPos) properties.
  472. function visibleLines(display, doc, viewport) {
  473. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  474. top = Math.floor(top - paddingTop(display));
  475. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  476. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  477. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  478. // forces those lines into the viewport (if possible).
  479. if (viewport && viewport.ensure) {
  480. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  481. if (ensureFrom < from) {
  482. from = ensureFrom;
  483. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  484. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  485. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  486. to = ensureTo;
  487. }
  488. }
  489. return {from: from, to: Math.max(to, from + 1)};
  490. }
  491. // LINE NUMBERS
  492. // Re-align line numbers and gutter marks to compensate for
  493. // horizontal scrolling.
  494. function alignHorizontally(cm) {
  495. var display = cm.display, view = display.view;
  496. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
  497. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  498. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  499. for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
  500. if (cm.options.fixedGutter && view[i].gutter)
  501. view[i].gutter.style.left = left;
  502. var align = view[i].alignable;
  503. if (align) for (var j = 0; j < align.length; j++)
  504. align[j].style.left = left;
  505. }
  506. if (cm.options.fixedGutter)
  507. display.gutters.style.left = (comp + gutterW) + "px";
  508. }
  509. // Used to ensure that the line number gutter is still the right
  510. // size for the current document size. Returns true when an update
  511. // is needed.
  512. function maybeUpdateLineNumberWidth(cm) {
  513. if (!cm.options.lineNumbers) return false;
  514. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  515. if (last.length != display.lineNumChars) {
  516. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  517. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  518. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  519. display.lineGutter.style.width = "";
  520. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  521. display.lineNumWidth = display.lineNumInnerWidth + padding;
  522. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  523. display.lineGutter.style.width = display.lineNumWidth + "px";
  524. updateGutterSpace(cm);
  525. return true;
  526. }
  527. return false;
  528. }
  529. function lineNumberFor(options, i) {
  530. return String(options.lineNumberFormatter(i + options.firstLineNumber));
  531. }
  532. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  533. // but using getBoundingClientRect to get a sub-pixel-accurate
  534. // result.
  535. function compensateForHScroll(display) {
  536. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
  537. }
  538. // DISPLAY DRAWING
  539. function DisplayUpdate(cm, viewport, force) {
  540. var display = cm.display;
  541. this.viewport = viewport;
  542. // Store some values that we'll need later (but don't want to force a relayout for)
  543. this.visible = visibleLines(display, cm.doc, viewport);
  544. this.editorIsHidden = !display.wrapper.offsetWidth;
  545. this.wrapperHeight = display.wrapper.clientHeight;
  546. this.wrapperWidth = display.wrapper.clientWidth;
  547. this.oldDisplayWidth = displayWidth(cm);
  548. this.force = force;
  549. this.dims = getDimensions(cm);
  550. this.events = [];
  551. }
  552. DisplayUpdate.prototype.signal = function(emitter, type) {
  553. if (hasHandler(emitter, type))
  554. this.events.push(arguments);
  555. };
  556. DisplayUpdate.prototype.finish = function() {
  557. for (var i = 0; i < this.events.length; i++)
  558. signal.apply(null, this.events[i]);
  559. };
  560. function maybeClipScrollbars(cm) {
  561. var display = cm.display;
  562. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  563. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  564. display.heightForcer.style.height = scrollGap(cm) + "px";
  565. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  566. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  567. display.scrollbarsClipped = true;
  568. }
  569. }
  570. // Does the actual updating of the line display. Bails out
  571. // (returning false) when there is nothing to be done and forced is
  572. // false.
  573. function updateDisplayIfNeeded(cm, update) {
  574. var display = cm.display, doc = cm.doc;
  575. if (update.editorIsHidden) {
  576. resetView(cm);
  577. return false;
  578. }
  579. // Bail out if the visible area is already rendered and nothing changed.
  580. if (!update.force &&
  581. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  582. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  583. display.renderedView == display.view && countDirtyView(cm) == 0)
  584. return false;
  585. if (maybeUpdateLineNumberWidth(cm)) {
  586. resetView(cm);
  587. update.dims = getDimensions(cm);
  588. }
  589. // Compute a suitable new viewport (from & to)
  590. var end = doc.first + doc.size;
  591. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  592. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  593. if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
  594. if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
  595. if (sawCollapsedSpans) {
  596. from = visualLineNo(cm.doc, from);
  597. to = visualLineEndNo(cm.doc, to);
  598. }
  599. var different = from != display.viewFrom || to != display.viewTo ||
  600. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  601. adjustView(cm, from, to);
  602. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  603. // Position the mover div to align with the current scroll position
  604. cm.display.mover.style.top = display.viewOffset + "px";
  605. var toUpdate = countDirtyView(cm);
  606. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  607. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  608. return false;
  609. // For big changes, we hide the enclosing element during the
  610. // update, since that speeds up the operations on most browsers.
  611. var focused = activeElt();
  612. if (toUpdate > 4) display.lineDiv.style.display = "none";
  613. patchDisplay(cm, display.updateLineNumbers, update.dims);
  614. if (toUpdate > 4) display.lineDiv.style.display = "";
  615. display.renderedView = display.view;
  616. // There might have been a widget with a focused element that got
  617. // hidden or updated, if so re-focus it.
  618. if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
  619. // Prevent selection and cursors from interfering with the scroll
  620. // width and height.
  621. removeChildren(display.cursorDiv);
  622. removeChildren(display.selectionDiv);
  623. display.gutters.style.height = 0;
  624. if (different) {
  625. display.lastWrapHeight = update.wrapperHeight;
  626. display.lastWrapWidth = update.wrapperWidth;
  627. startWorker(cm, 400);
  628. }
  629. display.updateLineNumbers = null;
  630. return true;
  631. }
  632. function postUpdateDisplay(cm, update) {
  633. var force = update.force, viewport = update.viewport;
  634. for (var first = true;; first = false) {
  635. if (first && cm.options.lineWrapping && update.oldDisplayWidth != displayWidth(cm)) {
  636. force = true;
  637. } else {
  638. force = false;
  639. // Clip forced viewport to actual scrollable area.
  640. if (viewport && viewport.top != null)
  641. viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
  642. // Updated line heights might result in the drawn area not
  643. // actually covering the viewport. Keep looping until it does.
  644. update.visible = visibleLines(cm.display, cm.doc, viewport);
  645. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  646. break;
  647. }
  648. if (!updateDisplayIfNeeded(cm, update)) break;
  649. updateHeightsInViewport(cm);
  650. var barMeasure = measureForScrollbars(cm);
  651. updateSelection(cm);
  652. setDocumentHeight(cm, barMeasure);
  653. updateScrollbars(cm, barMeasure);
  654. }
  655. update.signal(cm, "update", cm);
  656. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  657. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  658. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  659. }
  660. }
  661. function updateDisplaySimple(cm, viewport) {
  662. var update = new DisplayUpdate(cm, viewport);
  663. if (updateDisplayIfNeeded(cm, update)) {
  664. updateHeightsInViewport(cm);
  665. postUpdateDisplay(cm, update);
  666. var barMeasure = measureForScrollbars(cm);
  667. updateSelection(cm);
  668. setDocumentHeight(cm, barMeasure);
  669. updateScrollbars(cm, barMeasure);
  670. update.finish();
  671. }
  672. }
  673. function setDocumentHeight(cm, measure) {
  674. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  675. var total = measure.docHeight + cm.display.barHeight;
  676. cm.display.heightForcer.style.top = total + "px";
  677. cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + "px";
  678. }
  679. // Read the actual heights of the rendered lines, and update their
  680. // stored heights to match.
  681. function updateHeightsInViewport(cm) {
  682. var display = cm.display;
  683. var prevBottom = display.lineDiv.offsetTop;
  684. for (var i = 0; i < display.view.length; i++) {
  685. var cur = display.view[i], height;
  686. if (cur.hidden) continue;
  687. if (ie && ie_version < 8) {
  688. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  689. height = bot - prevBottom;
  690. prevBottom = bot;
  691. } else {
  692. var box = cur.node.getBoundingClientRect();
  693. height = box.bottom - box.top;
  694. }
  695. var diff = cur.line.height - height;
  696. if (height < 2) height = textHeight(display);
  697. if (diff > .001 || diff < -.001) {
  698. updateLineHeight(cur.line, height);
  699. updateWidgetHeight(cur.line);
  700. if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
  701. updateWidgetHeight(cur.rest[j]);
  702. }
  703. }
  704. }
  705. // Read and store the height of line widgets associated with the
  706. // given line.
  707. function updateWidgetHeight(line) {
  708. if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
  709. line.widgets[i].height = line.widgets[i].node.offsetHeight;
  710. }
  711. // Do a bulk-read of the DOM positions and sizes needed to draw the
  712. // view, so that we don't interleave reading and writing to the DOM.
  713. function getDimensions(cm) {
  714. var d = cm.display, left = {}, width = {};
  715. var gutterLeft = d.gutters.clientLeft;
  716. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  717. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
  718. width[cm.options.gutters[i]] = n.clientWidth;
  719. }
  720. return {fixedPos: compensateForHScroll(d),
  721. gutterTotalWidth: d.gutters.offsetWidth,
  722. gutterLeft: left,
  723. gutterWidth: width,
  724. wrapperWidth: d.wrapper.clientWidth};
  725. }
  726. // Sync the actual display DOM structure with display.view, removing
  727. // nodes for lines that are no longer in view, and creating the ones
  728. // that are not there yet, and updating the ones that are out of
  729. // date.
  730. function patchDisplay(cm, updateNumbersFrom, dims) {
  731. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  732. var container = display.lineDiv, cur = container.firstChild;
  733. function rm(node) {
  734. var next = node.nextSibling;
  735. // Works around a throw-scroll bug in OS X Webkit
  736. if (webkit && mac && cm.display.currentWheelTarget == node)
  737. node.style.display = "none";
  738. else
  739. node.parentNode.removeChild(node);
  740. return next;
  741. }
  742. var view = display.view, lineN = display.viewFrom;
  743. // Loop over the elements in the view, syncing cur (the DOM nodes
  744. // in display.lineDiv) with the view as we go.
  745. for (var i = 0; i < view.length; i++) {
  746. var lineView = view[i];
  747. if (lineView.hidden) {
  748. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  749. var node = buildLineElement(cm, lineView, lineN, dims);
  750. container.insertBefore(node, cur);
  751. } else { // Already drawn
  752. while (cur != lineView.node) cur = rm(cur);
  753. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  754. updateNumbersFrom <= lineN && lineView.lineNumber;
  755. if (lineView.changes) {
  756. if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
  757. updateLineForChanges(cm, lineView, lineN, dims);
  758. }
  759. if (updateNumber) {
  760. removeChildren(lineView.lineNumber);
  761. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  762. }
  763. cur = lineView.node.nextSibling;
  764. }
  765. lineN += lineView.size;
  766. }
  767. while (cur) cur = rm(cur);
  768. }
  769. // When an aspect of a line changes, a string is added to
  770. // lineView.changes. This updates the relevant part of the line's
  771. // DOM structure.
  772. function updateLineForChanges(cm, lineView, lineN, dims) {
  773. for (var j = 0; j < lineView.changes.length; j++) {
  774. var type = lineView.changes[j];
  775. if (type == "text") updateLineText(cm, lineView);
  776. else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
  777. else if (type == "class") updateLineClasses(lineView);
  778. else if (type == "widget") updateLineWidgets(cm, lineView, dims);
  779. }
  780. lineView.changes = null;
  781. }
  782. // Lines with gutter elements, widgets or a background class need to
  783. // be wrapped, and have the extra elements added to the wrapper div
  784. function ensureLineWrapped(lineView) {
  785. if (lineView.node == lineView.text) {
  786. lineView.node = elt("div", null, null, "position: relative");
  787. if (lineView.text.parentNode)
  788. lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
  789. lineView.node.appendChild(lineView.text);
  790. if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
  791. }
  792. return lineView.node;
  793. }
  794. function updateLineBackground(lineView) {
  795. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  796. if (cls) cls += " CodeMirror-linebackground";
  797. if (lineView.background) {
  798. if (cls) lineView.background.className = cls;
  799. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  800. } else if (cls) {
  801. var wrap = ensureLineWrapped(lineView);
  802. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  803. }
  804. }
  805. // Wrapper around buildLineContent which will reuse the structure
  806. // in display.externalMeasured when possible.
  807. function getLineContent(cm, lineView) {
  808. var ext = cm.display.externalMeasured;
  809. if (ext && ext.line == lineView.line) {
  810. cm.display.externalMeasured = null;
  811. lineView.measure = ext.measure;
  812. return ext.built;
  813. }
  814. return buildLineContent(cm, lineView);
  815. }
  816. // Redraw the line's text. Interacts with the background and text
  817. // classes because the mode may output tokens that influence these
  818. // classes.
  819. function updateLineText(cm, lineView) {
  820. var cls = lineView.text.className;
  821. var built = getLineContent(cm, lineView);
  822. if (lineView.text == lineView.node) lineView.node = built.pre;
  823. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  824. lineView.text = built.pre;
  825. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  826. lineView.bgClass = built.bgClass;
  827. lineView.textClass = built.textClass;
  828. updateLineClasses(lineView);
  829. } else if (cls) {
  830. lineView.text.className = cls;
  831. }
  832. }
  833. function updateLineClasses(lineView) {
  834. updateLineBackground(lineView);
  835. if (lineView.line.wrapClass)
  836. ensureLineWrapped(lineView).className = lineView.line.wrapClass;
  837. else if (lineView.node != lineView.text)
  838. lineView.node.className = "";
  839. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  840. lineView.text.className = textClass || "";
  841. }
  842. function updateLineGutter(cm, lineView, lineN, dims) {
  843. if (lineView.gutter) {
  844. lineView.node.removeChild(lineView.gutter);
  845. lineView.gutter = null;
  846. }
  847. var markers = lineView.line.gutterMarkers;
  848. if (cm.options.lineNumbers || markers) {
  849. var wrap = ensureLineWrapped(lineView);
  850. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
  851. (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
  852. "px; width: " + dims.gutterTotalWidth + "px");
  853. cm.display.input.setUneditable(gutterWrap);
  854. wrap.insertBefore(gutterWrap, lineView.text);
  855. if (lineView.line.gutterClass)
  856. gutterWrap.className += " " + lineView.line.gutterClass;
  857. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  858. lineView.lineNumber = gutterWrap.appendChild(
  859. elt("div", lineNumberFor(cm.options, lineN),
  860. "CodeMirror-linenumber CodeMirror-gutter-elt",
  861. "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
  862. + cm.display.lineNumInnerWidth + "px"));
  863. if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
  864. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
  865. if (found)
  866. gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
  867. dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
  868. }
  869. }
  870. }
  871. function updateLineWidgets(cm, lineView, dims) {
  872. if (lineView.alignable) lineView.alignable = null;
  873. for (var node = lineView.node.firstChild, next; node; node = next) {
  874. var next = node.nextSibling;
  875. if (node.className == "CodeMirror-linewidget")
  876. lineView.node.removeChild(node);
  877. }
  878. insertLineWidgets(cm, lineView, dims);
  879. }
  880. // Build a line's DOM representation from scratch
  881. function buildLineElement(cm, lineView, lineN, dims) {
  882. var built = getLineContent(cm, lineView);
  883. lineView.text = lineView.node = built.pre;
  884. if (built.bgClass) lineView.bgClass = built.bgClass;
  885. if (built.textClass) lineView.textClass = built.textClass;
  886. updateLineClasses(lineView);
  887. updateLineGutter(cm, lineView, lineN, dims);
  888. insertLineWidgets(cm, lineView, dims);
  889. return lineView.node;
  890. }
  891. // A lineView may contain multiple logical lines (when merged by
  892. // collapsed spans). The widgets for all of them need to be drawn.
  893. function insertLineWidgets(cm, lineView, dims) {
  894. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  895. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  896. insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
  897. }
  898. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  899. if (!line.widgets) return;
  900. var wrap = ensureLineWrapped(lineView);
  901. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  902. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  903. if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
  904. positionLineWidget(widget, node, lineView, dims);
  905. cm.display.input.setUneditable(node);
  906. if (allowAbove && widget.above)
  907. wrap.insertBefore(node, lineView.gutter || lineView.text);
  908. else
  909. wrap.appendChild(node);
  910. signalLater(widget, "redraw");
  911. }
  912. }
  913. function positionLineWidget(widget, node, lineView, dims) {
  914. if (widget.noHScroll) {
  915. (lineView.alignable || (lineView.alignable = [])).push(node);
  916. var width = dims.wrapperWidth;
  917. node.style.left = dims.fixedPos + "px";
  918. if (!widget.coverGutter) {
  919. width -= dims.gutterTotalWidth;
  920. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  921. }
  922. node.style.width = width + "px";
  923. }
  924. if (widget.coverGutter) {
  925. node.style.zIndex = 5;
  926. node.style.position = "relative";
  927. if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
  928. }
  929. }
  930. // POSITION OBJECT
  931. // A Pos instance represents a position within the text.
  932. var Pos = CodeMirror.Pos = function(line, ch) {
  933. if (!(this instanceof Pos)) return new Pos(line, ch);
  934. this.line = line; this.ch = ch;
  935. };
  936. // Compare two positions, return 0 if they are the same, a negative
  937. // number when a is less, and a positive number otherwise.
  938. var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
  939. function copyPos(x) {return Pos(x.line, x.ch);}
  940. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
  941. function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
  942. // INPUT HANDLING
  943. function ensureFocus(cm) {
  944. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
  945. }
  946. function isReadOnly(cm) {
  947. return cm.options.readOnly || cm.doc.cantEdit;
  948. }
  949. // This will be set to an array of strings when copying, so that,
  950. // when pasting, we know what kind of selections the copied text
  951. // was made out of.
  952. var lastCopied = null;
  953. function applyTextInput(cm, inserted, deleted, sel) {
  954. var doc = cm.doc;
  955. cm.display.shift = false;
  956. if (!sel) sel = doc.sel;
  957. var textLines = splitLines(inserted), multiPaste = null;
  958. // When pasing N lines into N selections, insert one line per selection
  959. if (cm.state.pasteIncoming && sel.ranges.length > 1) {
  960. if (lastCopied && lastCopied.join("\n") == inserted)
  961. multiPaste = sel.ranges.length % lastCopied.length == 0 && map(lastCopied, splitLines);
  962. else if (textLines.length == sel.ranges.length)
  963. multiPaste = map(textLines, function(l) { return [l]; });
  964. }
  965. // Normal behavior is to insert the new text into every selection
  966. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  967. var range = sel.ranges[i];
  968. var from = range.from(), to = range.to();
  969. if (range.empty()) {
  970. if (deleted && deleted > 0) // Handle deletion
  971. from = Pos(from.line, from.ch - deleted);
  972. else if (cm.state.overwrite && !cm.state.pasteIncoming) // Handle overwrite
  973. to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
  974. }
  975. var updateInput = cm.curOp.updateInput;
  976. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
  977. origin: cm.state.pasteIncoming ? "paste" : cm.state.cutIncoming ? "cut" : "+input"};
  978. makeChange(cm.doc, changeEvent);
  979. signalLater(cm, "inputRead", cm, changeEvent);
  980. // When an 'electric' character is inserted, immediately trigger a reindent
  981. if (inserted && !cm.state.pasteIncoming && cm.options.electricChars &&
  982. cm.options.smartIndent && range.head.ch < 100 &&
  983. (!i || sel.ranges[i - 1].head.line != range.head.line)) {
  984. var mode = cm.getModeAt(range.head);
  985. var end = changeEnd(changeEvent);
  986. if (mode.electricChars) {
  987. for (var j = 0; j < mode.electricChars.length; j++)
  988. if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  989. indentLine(cm, end.line, "smart");
  990. break;
  991. }
  992. } else if (mode.electricInput) {
  993. if (mode.electricInput.test(getLine(doc, end.line).text.slice(0, end.ch)))
  994. indentLine(cm, end.line, "smart");
  995. }
  996. }
  997. }
  998. ensureCursorVisible(cm);
  999. cm.curOp.updateInput = updateInput;
  1000. cm.curOp.typing = true;
  1001. cm.state.pasteIncoming = cm.state.cutIncoming = false;
  1002. }
  1003. function copyableRanges(cm) {
  1004. var text = [], ranges = [];
  1005. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  1006. var line = cm.doc.sel.ranges[i].head.line;
  1007. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  1008. ranges.push(lineRange);
  1009. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  1010. }
  1011. return {text: text, ranges: ranges};
  1012. }
  1013. function disableBrowserMagic(field) {
  1014. field.setAttribute("autocorrect", "off");
  1015. field.setAttribute("autocapitalize", "off");
  1016. field.setAttribute("spellcheck", "false");
  1017. }
  1018. // TEXTAREA INPUT STYLE
  1019. function TextareaInput(cm) {
  1020. this.cm = cm;
  1021. // See input.poll and input.reset
  1022. this.prevInput = "";
  1023. // Flag that indicates whether we expect input to appear real soon
  1024. // now (after some event like 'keypress' or 'input') and are
  1025. // polling intensively.
  1026. this.pollingFast = false;
  1027. // Self-resetting timeout for the poller
  1028. this.polling = new Delayed();
  1029. // Tracks when input.reset has punted to just putting a short
  1030. // string into the textarea instead of the full selection.
  1031. this.inaccurateSelection = false;
  1032. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  1033. this.hasSelection = false;
  1034. };
  1035. function hiddenTextarea() {
  1036. var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
  1037. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  1038. // The textarea is kept positioned near the cursor to prevent the
  1039. // fact that it'll be scrolled into view on input from scrolling
  1040. // our fake cursor out of view. On webkit, when wrap=off, paste is
  1041. // very slow. So make the area wide instead.
  1042. if (webkit) te.style.width = "1000px";
  1043. else te.setAttribute("wrap", "off");
  1044. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  1045. if (ios) te.style.border = "1px solid black";
  1046. disableBrowserMagic(te);
  1047. return div;
  1048. }
  1049. TextareaInput.prototype = copyObj({
  1050. init: function(display) {
  1051. var input = this, cm = this.cm;
  1052. // Wraps and hides input textarea
  1053. var div = this.wrapper = hiddenTextarea();
  1054. // The semihidden textarea that is focused when the editor is
  1055. // focused, and receives input.
  1056. var te = this.textarea = div.firstChild;
  1057. display.wrapper.insertBefore(div, display.wrapper.firstChild);
  1058. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  1059. if (ios) te.style.width = "0px";
  1060. on(te, "input", function() {
  1061. if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null;
  1062. input.poll();
  1063. });
  1064. on(te, "paste", function() {
  1065. // Workaround for webkit bug https://bugs.webkit.org/show_bug.cgi?id=90206
  1066. // Add a char to the end of textarea before paste occur so that
  1067. // selection doesn't span to the end of textarea.
  1068. if (webkit && !cm.state.fakedLastChar && !(new Date - cm.state.lastMiddleDown < 200)) {
  1069. var start = te.selectionStart, end = te.selectionEnd;
  1070. te.value += "$";
  1071. // The selection end needs to be set before the start, otherwise there
  1072. // can be an intermediate non-empty selection between the two, which
  1073. // can override the middle-click paste buffer on linux and cause the
  1074. // wrong thing to get pasted.
  1075. te.selectionEnd = end;
  1076. te.selectionStart = start;
  1077. cm.state.fakedLastChar = true;
  1078. }
  1079. cm.state.pasteIncoming = true;
  1080. input.fastPoll();
  1081. });
  1082. function prepareCopyCut(e) {
  1083. if (cm.somethingSelected()) {
  1084. lastCopied = cm.getSelections();
  1085. if (input.inaccurateSelection) {
  1086. input.prevInput = "";
  1087. input.inaccurateSelection = false;
  1088. te.value = lastCopied.join("\n");
  1089. selectInput(te);
  1090. }
  1091. } else {
  1092. var ranges = copyableRanges(cm);
  1093. lastCopied = ranges.text;
  1094. if (e.type == "cut") {
  1095. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  1096. } else {
  1097. input.prevInput = "";
  1098. te.value = ranges.text.join("\n");
  1099. selectInput(te);
  1100. }
  1101. }
  1102. if (e.type == "cut") cm.state.cutIncoming = true;
  1103. }
  1104. on(te, "cut", prepareCopyCut);
  1105. on(te, "copy", prepareCopyCut);
  1106. on(display.scroller, "paste", function(e) {
  1107. if (eventInWidget(display, e)) return;
  1108. cm.state.pasteIncoming = true;
  1109. input.focus();
  1110. });
  1111. // Prevent normal selection in the editor (we handle our own)
  1112. on(display.lineSpace, "selectstart", function(e) {
  1113. if (!eventInWidget(display, e)) e_preventDefault(e);
  1114. });
  1115. },
  1116. prepareSelection: function() {
  1117. // Redraw the selection and/or cursor
  1118. var cm = this.cm, display = cm.display, doc = cm.doc;
  1119. var result = prepareSelection(cm);
  1120. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  1121. if (cm.options.moveInputWithCursor) {
  1122. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  1123. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  1124. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  1125. headPos.top + lineOff.top - wrapOff.top));
  1126. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  1127. headPos.left + lineOff.left - wrapOff.left));
  1128. }
  1129. return result;
  1130. },
  1131. showSelection: function(drawn) {
  1132. var cm = this.cm, display = cm.display;
  1133. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  1134. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  1135. if (drawn.teTop != null) {
  1136. this.wrapper.style.top = drawn.teTop + "px";
  1137. this.wrapper.style.left = drawn.teLeft + "px";
  1138. }
  1139. },
  1140. // Reset the input to correspond to the selection (or to be empty,
  1141. // when not typing and nothing is selected)
  1142. reset: function(typing) {
  1143. if (this.contextMenuPending) return;
  1144. var minimal, selected, cm = this.cm, doc = cm.doc;
  1145. if (cm.somethingSelected()) {
  1146. this.prevInput = "";
  1147. var range = doc.sel.primary();
  1148. minimal = hasCopyEvent &&
  1149. (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
  1150. var content = minimal ? "-" : selected || cm.getSelection();
  1151. this.textarea.value = content;
  1152. if (cm.state.focused) selectInput(this.textarea);
  1153. if (ie && ie_version >= 9) this.hasSelection = content;
  1154. } else if (!typing) {
  1155. this.prevInput = this.textarea.value = "";
  1156. if (ie && ie_version >= 9) this.hasSelection = null;
  1157. }
  1158. this.inaccurateSelection = minimal;
  1159. },
  1160. getField: function() { return this.textarea; },
  1161. supportsTouch: function() { return false; },
  1162. focus: function() {
  1163. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  1164. try { this.textarea.focus(); }
  1165. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  1166. }
  1167. },
  1168. blur: function() { this.textarea.blur(); },
  1169. resetPosition: function() {
  1170. this.wrapper.style.top = this.wrapper.style.left = 0;
  1171. },
  1172. receivedFocus: function() { this.slowPoll(); },
  1173. // Poll for input changes, using the normal rate of polling. This
  1174. // runs as long as the editor is focused.
  1175. slowPoll: function() {
  1176. var input = this;
  1177. if (input.pollingFast) return;
  1178. input.polling.set(this.cm.options.pollInterval, function() {
  1179. input.poll();
  1180. if (input.cm.state.focused) input.slowPoll();
  1181. });
  1182. },
  1183. // When an event has just come in that is likely to add or change
  1184. // something in the input textarea, we poll faster, to ensure that
  1185. // the change appears on the screen quickly.
  1186. fastPoll: function() {
  1187. var missed = false, input = this;
  1188. input.pollingFast = true;
  1189. function p() {
  1190. var changed = input.poll();
  1191. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  1192. else {input.pollingFast = false; input.slowPoll();}
  1193. }
  1194. input.polling.set(20, p);
  1195. },
  1196. // Read input from the textarea, and update the document to match.
  1197. // When something is selected, it is present in the textarea, and
  1198. // selected (unless it is huge, in which case a placeholder is
  1199. // used). When nothing is selected, the cursor sits after previously
  1200. // seen text (can be empty), which is stored in prevInput (we must
  1201. // not reset the textarea when typing, because that breaks IME).
  1202. poll: function() {
  1203. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  1204. // Since this is called a *lot*, try to bail out as cheaply as
  1205. // possible when it is clear that nothing happened. hasSelection
  1206. // will be the case when there is a lot of text in the textarea,
  1207. // in which case reading its value would be expensive.
  1208. if (!cm.state.focused || (hasSelection(input) && !prevInput) ||
  1209. isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq)
  1210. return false;
  1211. // See paste handler for more on the fakedLastChar kludge
  1212. if (cm.state.pasteIncoming && cm.state.fakedLastChar) {
  1213. input.value = input.value.substring(0, input.value.length - 1);
  1214. cm.state.fakedLastChar = false;
  1215. }
  1216. var text = input.value;
  1217. // If nothing changed, bail.
  1218. if (text == prevInput && !cm.somethingSelected()) return false;
  1219. // Work around nonsensical selection resetting in IE9/10, and
  1220. // inexplicable appearance of private area unicode characters on
  1221. // some key combos in Mac (#2689).
  1222. if (ie && ie_version >= 9 && this.hasSelection === text ||
  1223. mac && /[\uf700-\uf7ff]/.test(text)) {
  1224. cm.display.input.reset();
  1225. return false;
  1226. }
  1227. if (cm.doc.sel == cm.display.selForContextMenu) {
  1228. if (text.charCodeAt(0) == 0x200b) {
  1229. if (!prevInput) prevInput = "\u200b";
  1230. } else if (prevInput == "\u200b") {
  1231. text = text.slice(1);
  1232. prevInput = "";
  1233. }
  1234. }
  1235. // Find the part of the input that is actually new
  1236. var same = 0, l = Math.min(prevInput.length, text.length);
  1237. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
  1238. var self = this;
  1239. runInOp(cm, function() {
  1240. applyTextInput(cm, text.slice(same), prevInput.length - same);
  1241. // Don't leave long text in the textarea, since it makes further polling slow
  1242. if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
  1243. else self.prevInput = text;
  1244. });
  1245. return true;
  1246. },
  1247. ensurePolled: function() {
  1248. if (this.pollingFast && this.poll()) this.pollingFast = false;
  1249. },
  1250. onKeyPress: function() {
  1251. if (ie && ie_version >= 9) this.hasSelection = null;
  1252. this.fastPoll();
  1253. },
  1254. onContextMenu: function(e) {
  1255. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  1256. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  1257. if (!pos || presto) return; // Opera is difficult.
  1258. // Reset the current text selection only if the click is done outside of the selection
  1259. // and 'resetSelectionOnContextMenu' option is true.
  1260. var reset = cm.options.resetSelectionOnContextMenu;
  1261. if (reset && cm.doc.sel.contains(pos) == -1)
  1262. operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
  1263. var oldCSS = te.style.cssText;
  1264. input.wrapper.style.position = "absolute";
  1265. te.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
  1266. "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " +
  1267. (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
  1268. "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  1269. if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
  1270. display.input.focus();
  1271. if (webkit) window.scrollTo(null, oldScrollY);
  1272. display.input.reset();
  1273. // Adds "Select all" to context menu in FF
  1274. if (!cm.somethingSelected()) te.value = input.prevInput = " ";
  1275. input.contextMenuPending = true;
  1276. display.selForContextMenu = cm.doc.sel;
  1277. clearTimeout(display.detectingSelectAll);
  1278. // Select-all will be greyed out if there's nothing to select, so
  1279. // this adds a zero-width space so that we can later check whether
  1280. // it got selected.
  1281. function prepareSelectAllHack() {
  1282. if (te.selectionStart != null) {
  1283. var selected = cm.somethingSelected();
  1284. var extval = te.value = "\u200b" + (selected ? te.value : "");
  1285. input.prevInput = selected ? "" : "\u200b";
  1286. te.selectionStart = 1; te.selectionEnd = extval.length;
  1287. // Re-set this, in case some other handler touched the
  1288. // selection in the meantime.
  1289. display.selForContextMenu = cm.doc.sel;
  1290. }
  1291. }
  1292. function rehide() {
  1293. input.contextMenuPending = false;
  1294. input.wrapper.style.position = "relative";
  1295. te.style.cssText = oldCSS;
  1296. if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
  1297. // Try to detect the user choosing select-all
  1298. if (te.selectionStart != null) {
  1299. if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
  1300. var i = 0, poll = function() {
  1301. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && input.prevInput == "\u200b")
  1302. operation(cm, commands.selectAll)(cm);
  1303. else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
  1304. else display.input.reset();
  1305. };
  1306. display.detectingSelectAll = setTimeout(poll, 200);
  1307. }
  1308. }
  1309. if (ie && ie_version >= 9) prepareSelectAllHack();
  1310. if (captureRightClick) {
  1311. e_stop(e);
  1312. var mouseup = function() {
  1313. off(window, "mouseup", mouseup);
  1314. setTimeout(rehide, 20);
  1315. };
  1316. on(window, "mouseup", mouseup);
  1317. } else {
  1318. setTimeout(rehide, 50);
  1319. }
  1320. },
  1321. setUneditable: nothing,
  1322. needsContentAttribute: false
  1323. }, TextareaInput.prototype);
  1324. // CONTENTEDITABLE INPUT STYLE
  1325. function ContentEditableInput(cm) {
  1326. this.cm = cm;
  1327. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  1328. this.polling = new Delayed();
  1329. this.gracePeriod = false;
  1330. }
  1331. ContentEditableInput.prototype = copyObj({
  1332. init: function(display) {
  1333. var input = this, cm = input.cm;
  1334. var div = input.div = display.lineDiv;
  1335. div.contentEditable = "true";
  1336. disableBrowserMagic(div);
  1337. on(div, "paste", function(e) {
  1338. var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
  1339. if (pasted) {
  1340. e.preventDefault();
  1341. cm.replaceSelection(pasted, null, "paste");
  1342. }
  1343. });
  1344. on(div, "compositionstart", function(e) {
  1345. var data = e.data;
  1346. input.composing = {sel: cm.doc.sel, data: data, startData: data};
  1347. if (!data) return;
  1348. var prim = cm.doc.sel.primary();
  1349. var line = cm.getLine(prim.head.line);
  1350. var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
  1351. if (found > -1 && found <= prim.head.ch)
  1352. input.composing.sel = simpleSelection(Pos(prim.head.line, found),
  1353. Pos(prim.head.line, found + data.length));
  1354. });
  1355. on(div, "compositionupdate", function(e) {
  1356. input.composing.data = e.data;
  1357. });
  1358. on(div, "compositionend", function(e) {
  1359. var ours = input.composing;
  1360. if (!ours) return;
  1361. if (e.data != ours.startData && !/\u200b/.test(e.data))
  1362. ours.data = e.data;
  1363. // Need a small delay to prevent other code (input event,
  1364. // selection polling) from doing damage when fired right after
  1365. // compositionend.
  1366. setTimeout(function() {
  1367. if (!ours.handled)
  1368. input.applyComposition(ours);
  1369. if (input.composing == ours)
  1370. input.composing = null;
  1371. }, 50);
  1372. });
  1373. on(div, "touchstart", function() {
  1374. input.forceCompositionEnd();
  1375. });
  1376. on(div, "input", function() {
  1377. if (input.composing) return;
  1378. if (!input.pollContent())
  1379. runInOp(input.cm, function() {regChange(cm);});
  1380. });
  1381. function onCopyCut(e) {
  1382. if (cm.somethingSelected()) {
  1383. lastCopied = cm.getSelections();
  1384. if (e.type == "cut") cm.replaceSelection("", null, "cut");
  1385. } else {
  1386. var ranges = copyableRanges(cm);
  1387. lastCopied = ranges.text;
  1388. if (e.type == "cut") {
  1389. cm.operation(function() {
  1390. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  1391. cm.replaceSelection("", null, "cut");
  1392. });
  1393. }
  1394. }
  1395. // iOS exposes the clipboard API, but seems to discard content inserted into it
  1396. if (e.clipboardData && !ios) {
  1397. e.preventDefault();
  1398. e.clipboardData.clearData();
  1399. e.clipboardData.setData("text/plain", lastCopied.join("\n"));
  1400. } else {
  1401. // Old-fashioned briefly-focus-a-textarea hack
  1402. var kludge = hiddenTextarea(), te = kludge.firstChild;
  1403. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  1404. te.value = lastCopied.join("\n");
  1405. var hadFocus = document.activeElement;
  1406. selectInput(te);
  1407. setTimeout(function() {
  1408. cm.display.lineSpace.removeChild(kludge);
  1409. hadFocus.focus();
  1410. }, 50);
  1411. }
  1412. }
  1413. on(div, "copy", onCopyCut);
  1414. on(div, "cut", onCopyCut);
  1415. },
  1416. prepareSelection: function() {
  1417. var result = prepareSelection(this.cm, false);
  1418. result.focus = this.cm.state.focused;
  1419. return result;
  1420. },
  1421. showSelection: function(info) {
  1422. if (!info || !this.cm.display.view.length) return;
  1423. if (info.focus) this.showPrimarySelection();
  1424. this.showMultipleSelections(info);
  1425. },
  1426. showPrimarySelection: function() {
  1427. var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
  1428. var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
  1429. var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
  1430. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  1431. cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
  1432. cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
  1433. return;
  1434. var start = posToDOM(this.cm, prim.from());
  1435. var end = posToDOM(this.cm, prim.to());
  1436. if (!start && !end) return;
  1437. var view = this.cm.display.view;
  1438. var old = sel.rangeCount && sel.getRangeAt(0);
  1439. if (!start) {
  1440. start = {node: view[0].measure.map[2], offset: 0};
  1441. } else if (!end) { // FIXME dangerously hacky
  1442. var measure = view[view.length - 1].measure;
  1443. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  1444. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
  1445. }
  1446. try { var rng = range(start.node, start.offset, end.offset, end.node); }
  1447. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  1448. if (rng) {
  1449. sel.removeAllRanges();
  1450. sel.addRange(rng);
  1451. if (old && sel.anchorNode == null) sel.addRange(old);
  1452. else if (gecko) this.startGracePeriod();
  1453. }
  1454. this.rememberSelection();
  1455. },
  1456. startGracePeriod: function() {
  1457. var input = this;
  1458. clearTimeout(this.gracePeriod);
  1459. this.gracePeriod = setTimeout(function() {
  1460. input.gracePeriod = false;
  1461. if (input.selectionChanged())
  1462. input.cm.operation(function() { input.cm.curOp.selectionChanged = true; });
  1463. }, 20);
  1464. },
  1465. showMultipleSelections: function(info) {
  1466. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  1467. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  1468. },
  1469. rememberSelection: function() {
  1470. var sel = window.getSelection();
  1471. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  1472. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  1473. },
  1474. selectionInEditor: function() {
  1475. var sel = window.getSelection();
  1476. if (!sel.rangeCount) return false;
  1477. var node = sel.getRangeAt(0).commonAncestorContainer;
  1478. return contains(this.div, node);
  1479. },
  1480. focus: function() {
  1481. if (this.cm.options.readOnly != "nocursor") this.div.focus();
  1482. },
  1483. blur: function() { this.div.blur(); },
  1484. getField: function() { return this.div; },
  1485. supportsTouch: function() { return true; },
  1486. receivedFocus: function() {
  1487. var input = this;
  1488. if (this.selectionInEditor())
  1489. this.pollSelection();
  1490. else
  1491. runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
  1492. function poll() {
  1493. if (input.cm.state.focused) {
  1494. input.pollSelection();
  1495. input.polling.set(input.cm.options.pollInterval, poll);
  1496. }
  1497. }
  1498. this.polling.set(this.cm.options.pollInterval, poll);
  1499. },
  1500. selectionChanged: function() {
  1501. var sel = window.getSelection();
  1502. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  1503. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
  1504. },
  1505. pollSelection: function() {
  1506. if (!this.composing && !this.gracePeriod && this.selectionChanged()) {
  1507. var sel = window.getSelection(), cm = this.cm;
  1508. this.rememberSelection();
  1509. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  1510. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  1511. if (anchor && head) runInOp(cm, function() {
  1512. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  1513. if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
  1514. });
  1515. }
  1516. },
  1517. pollContent: function() {
  1518. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  1519. var from = sel.from(), to = sel.to();
  1520. if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false;
  1521. var fromIndex;
  1522. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  1523. var fromLine = lineNo(display.view[0].line);
  1524. var fromNode = display.view[0].node;
  1525. } else {
  1526. var fromLine = lineNo(display.view[fromIndex].line);
  1527. var fromNode = display.view[fromIndex - 1].node.nextSibling;
  1528. }
  1529. var toIndex = findViewIndex(cm, to.line);
  1530. if (toIndex == display.view.length - 1) {
  1531. var toLine = display.viewTo - 1;
  1532. var toNode = display.view[toIndex].node;
  1533. } else {
  1534. var toLine = lineNo(display.view[toIndex + 1].line) - 1;
  1535. var toNode = display.view[toIndex + 1].node.previousSibling;
  1536. }
  1537. var newText = splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  1538. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  1539. while (newText.length > 1 && oldText.length > 1) {
  1540. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  1541. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  1542. else break;
  1543. }
  1544. var cutFront = 0, cutEnd = 0;
  1545. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  1546. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  1547. ++cutFront;
  1548. var newBot = lst(newText), oldBot = lst(oldText);
  1549. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  1550. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  1551. while (cutEnd < maxCutEnd &&
  1552. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  1553. ++cutEnd;
  1554. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
  1555. newText[0] = newText[0].slice(cutFront);
  1556. var chFrom = Pos(fromLine, cutFront);
  1557. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  1558. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  1559. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  1560. return true;
  1561. }
  1562. },
  1563. ensurePolled: function() {
  1564. this.forceCompositionEnd();
  1565. },
  1566. reset: function() {
  1567. this.forceCompositionEnd();
  1568. },
  1569. forceCompositionEnd: function() {
  1570. if (!this.composing || this.composing.handled) return;
  1571. this.applyComposition(this.composing);
  1572. this.composing.handled = true;
  1573. this.div.blur();
  1574. this.div.focus();
  1575. },
  1576. applyComposition: function(composing) {
  1577. if (composing.data && composing.data != composing.startData)
  1578. operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
  1579. },
  1580. setUneditable: function(node) {
  1581. node.setAttribute("contenteditable", "false");
  1582. },
  1583. onKeyPress: function(e) {
  1584. e.preventDefault();
  1585. operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
  1586. },
  1587. onContextMenu: nothing,
  1588. resetPosition: nothing,
  1589. needsContentAttribute: true
  1590. }, ContentEditableInput.prototype);
  1591. function posToDOM(cm, pos) {
  1592. var view = findViewForLine(cm, pos.line);
  1593. if (!view || view.hidden) return null;
  1594. var line = getLine(cm.doc, pos.line);
  1595. var info = mapFromLineView(view, line, pos.line);
  1596. var order = getOrder(line), side = "left";
  1597. if (order) {
  1598. var partPos = getBidiPartAt(order, pos.ch);
  1599. side = partPos % 2 ? "right" : "left";
  1600. }
  1601. var result = nodeAndOffsetInLineMap(info.map, pos.ch, "left");
  1602. result.offset = result.collapse == "right" ? result.end : result.start;
  1603. return result;
  1604. }
  1605. function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
  1606. function domToPos(cm, node, offset) {
  1607. var lineNode;
  1608. if (node == cm.display.lineDiv) {
  1609. lineNode = cm.display.lineDiv.childNodes[offset];
  1610. if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
  1611. node = null; offset = 0;
  1612. } else {
  1613. for (lineNode = node;; lineNode = lineNode.parentNode) {
  1614. if (!lineNode || lineNode == cm.display.lineDiv) return null;
  1615. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break;
  1616. }
  1617. }
  1618. for (var i = 0; i < cm.display.view.length; i++) {
  1619. var lineView = cm.display.view[i];
  1620. if (lineView.node == lineNode)
  1621. return locateNodeInLineView(lineView, node, offset);
  1622. }
  1623. }
  1624. function locateNodeInLineView(lineView, node, offset) {
  1625. var wrapper = lineView.text.firstChild, bad = false;
  1626. if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
  1627. if (node == wrapper) {
  1628. bad = true;
  1629. node = wrapper.childNodes[offset];
  1630. offset = 0;
  1631. if (!node) {
  1632. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  1633. return badPos(Pos(lineNo(line), line.text.length), bad);
  1634. }
  1635. }
  1636. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  1637. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  1638. textNode = node.firstChild;
  1639. if (offset) offset = textNode.nodeValue.length;
  1640. }
  1641. while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
  1642. var measure = lineView.measure, maps = measure.maps;
  1643. function find(textNode, topNode, offset) {
  1644. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  1645. var map = i < 0 ? measure.map : maps[i];
  1646. for (var j = 0; j < map.length; j += 3) {
  1647. var curNode = map[j + 2];
  1648. if (curNode == textNode || curNode == topNode) {
  1649. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  1650. var ch = map[j] + offset;
  1651. if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
  1652. return Pos(line, ch);
  1653. }
  1654. }
  1655. }
  1656. }
  1657. var found = find(textNode, topNode, offset);
  1658. if (found) return badPos(found, bad);
  1659. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  1660. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  1661. found = find(after, after.firstChild, 0);
  1662. if (found)
  1663. return badPos(Pos(found.line, found.ch - dist), bad);
  1664. else
  1665. dist += after.textContent.length;
  1666. }
  1667. for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
  1668. found = find(before, before.firstChild, -1);
  1669. if (found)
  1670. return badPos(Pos(found.line, found.ch + dist), bad);
  1671. else
  1672. dist += after.textContent.length;
  1673. }
  1674. }
  1675. function domTextBetween(cm, from, to, fromLine, toLine) {
  1676. var text = "", closing = false;
  1677. function recognizeMarker(id) { return function(marker) { return marker.id == id; }; }
  1678. function walk(node) {
  1679. if (node.nodeType == 1) {
  1680. var cmText = node.getAttribute("cm-text");
  1681. if (cmText != null) {
  1682. if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
  1683. text += cmText;
  1684. return;
  1685. }
  1686. var markerID = node.getAttribute("cm-marker"), range;
  1687. if (markerID) {
  1688. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  1689. if (found.length && (range = found[0].find()))
  1690. text += getBetween(cm.doc, range.from, range.to).join("\n");
  1691. return;
  1692. }
  1693. if (node.getAttribute("contenteditable") == "false") return;
  1694. for (var i = 0; i < node.childNodes.length; i++)
  1695. walk(node.childNodes[i]);
  1696. if (/^(pre|div|p)$/i.test(node.nodeName))
  1697. closing = true;
  1698. } else if (node.nodeType == 3) {
  1699. var val = node.nodeValue;
  1700. if (!val) return;
  1701. if (closing) {
  1702. text += "\n";
  1703. closing = false;
  1704. }
  1705. text += val;
  1706. }
  1707. }
  1708. for (;;) {
  1709. walk(from);
  1710. if (from == to) break;
  1711. from = from.nextSibling;
  1712. }
  1713. return text;
  1714. }
  1715. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  1716. // SELECTION / CURSOR
  1717. // Selection objects are immutable. A new one is created every time
  1718. // the selection changes. A selection is one or more non-overlapping
  1719. // (and non-touching) ranges, sorted, and an integer that indicates
  1720. // which one is the primary selection (the one that's scrolled into
  1721. // view, that getCursor returns, etc).
  1722. function Selection(ranges, primIndex) {
  1723. this.ranges = ranges;
  1724. this.primIndex = primIndex;
  1725. }
  1726. Selection.prototype = {
  1727. primary: function() { return this.ranges[this.primIndex]; },
  1728. equals: function(other) {
  1729. if (other == this) return true;
  1730. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
  1731. for (var i = 0; i < this.ranges.length; i++) {
  1732. var here = this.ranges[i], there = other.ranges[i];
  1733. if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
  1734. }
  1735. return true;
  1736. },
  1737. deepCopy: function() {
  1738. for (var out = [], i = 0; i < this.ranges.length; i++)
  1739. out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
  1740. return new Selection(out, this.primIndex);
  1741. },
  1742. somethingSelected: function() {
  1743. for (var i = 0; i < this.ranges.length; i++)
  1744. if (!this.ranges[i].empty()) return true;
  1745. return false;
  1746. },
  1747. contains: function(pos, end) {
  1748. if (!end) end = pos;
  1749. for (var i = 0; i < this.ranges.length; i++) {
  1750. var range = this.ranges[i];
  1751. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  1752. return i;
  1753. }
  1754. return -1;
  1755. }
  1756. };
  1757. function Range(anchor, head) {
  1758. this.anchor = anchor; this.head = head;
  1759. }
  1760. Range.prototype = {
  1761. from: function() { return minPos(this.anchor, this.head); },
  1762. to: function() { return maxPos(this.anchor, this.head); },
  1763. empty: function() {
  1764. return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
  1765. }
  1766. };
  1767. // Take an unsorted, potentially overlapping set of ranges, and
  1768. // build a selection out of it. 'Consumes' ranges array (modifying
  1769. // it).
  1770. function normalizeSelection(ranges, primIndex) {
  1771. var prim = ranges[primIndex];
  1772. ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
  1773. primIndex = indexOf(ranges, prim);
  1774. for (var i = 1; i < ranges.length; i++) {
  1775. var cur = ranges[i], prev = ranges[i - 1];
  1776. if (cmp(prev.to(), cur.from()) >= 0) {
  1777. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  1778. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  1779. if (i <= primIndex) --primIndex;
  1780. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  1781. }
  1782. }
  1783. return new Selection(ranges, primIndex);
  1784. }
  1785. function simpleSelection(anchor, head) {
  1786. return new Selection([new Range(anchor, head || anchor)], 0);
  1787. }
  1788. // Most of the external API clips given positions to make sure they
  1789. // actually exist within the document.
  1790. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
  1791. function clipPos(doc, pos) {
  1792. if (pos.line < doc.first) return Pos(doc.first, 0);
  1793. var last = doc.first + doc.size - 1;
  1794. if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
  1795. return clipToLen(pos, getLine(doc, pos.line).text.length);
  1796. }
  1797. function clipToLen(pos, linelen) {
  1798. var ch = pos.ch;
  1799. if (ch == null || ch > linelen) return Pos(pos.line, linelen);
  1800. else if (ch < 0) return Pos(pos.line, 0);
  1801. else return pos;
  1802. }
  1803. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
  1804. function clipPosArray(doc, array) {
  1805. for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
  1806. return out;
  1807. }
  1808. // SELECTION UPDATES
  1809. // The 'scroll' parameter given to many of these indicated whether
  1810. // the new cursor position should be scrolled into view after
  1811. // modifying the selection.
  1812. // If shift is held or the extend flag is set, extends a range to
  1813. // include a given position (and optionally a second position).
  1814. // Otherwise, simply returns the range between the given positions.
  1815. // Used for cursor motion and such.
  1816. function extendRange(doc, range, head, other) {
  1817. if (doc.cm && doc.cm.display.shift || doc.extend) {
  1818. var anchor = range.anchor;
  1819. if (other) {
  1820. var posBefore = cmp(head, anchor) < 0;
  1821. if (posBefore != (cmp(other, anchor) < 0)) {
  1822. anchor = head;
  1823. head = other;
  1824. } else if (posBefore != (cmp(head, other) < 0)) {
  1825. head = other;
  1826. }
  1827. }
  1828. return new Range(anchor, head);
  1829. } else {
  1830. return new Range(other || head, head);
  1831. }
  1832. }
  1833. // Extend the primary selection range, discard the rest.
  1834. function extendSelection(doc, head, other, options) {
  1835. setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
  1836. }
  1837. // Extend all selections (pos is an array of selections with length
  1838. // equal the number of selections)
  1839. function extendSelections(doc, heads, options) {
  1840. for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
  1841. out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
  1842. var newSel = normalizeSelection(out, doc.sel.primIndex);
  1843. setSelection(doc, newSel, options);
  1844. }
  1845. // Updates a single range in the selection.
  1846. function replaceOneSelection(doc, i, range, options) {
  1847. var ranges = doc.sel.ranges.slice(0);
  1848. ranges[i] = range;
  1849. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
  1850. }
  1851. // Reset the selection to a single range.
  1852. function setSimpleSelection(doc, anchor, head, options) {
  1853. setSelection(doc, simpleSelection(anchor, head), options);
  1854. }
  1855. // Give beforeSelectionChange handlers a change to influence a
  1856. // selection update.
  1857. function filterSelectionChange(doc, sel) {
  1858. var obj = {
  1859. ranges: sel.ranges,
  1860. update: function(ranges) {
  1861. this.ranges = [];
  1862. for (var i = 0; i < ranges.length; i++)
  1863. this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  1864. clipPos(doc, ranges[i].head));
  1865. }
  1866. };
  1867. signal(doc, "beforeSelectionChange", doc, obj);
  1868. if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
  1869. if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
  1870. else return sel;
  1871. }
  1872. function setSelectionReplaceHistory(doc, sel, options) {
  1873. var done = doc.history.done, last = lst(done);
  1874. if (last && last.ranges) {
  1875. done[done.length - 1] = sel;
  1876. setSelectionNoUndo(doc, sel, options);
  1877. } else {
  1878. setSelection(doc, sel, options);
  1879. }
  1880. }
  1881. // Set a new selection.
  1882. function setSelection(doc, sel, options) {
  1883. setSelectionNoUndo(doc, sel, options);
  1884. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  1885. }
  1886. function setSelectionNoUndo(doc, sel, options) {
  1887. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  1888. sel = filterSelectionChange(doc, sel);
  1889. var bias = options && options.bias ||
  1890. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  1891. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  1892. if (!(options && options.scroll === false) && doc.cm)
  1893. ensureCursorVisible(doc.cm);
  1894. }
  1895. function setSelectionInner(doc, sel) {
  1896. if (sel.equals(doc.sel)) return;
  1897. doc.sel = sel;
  1898. if (doc.cm) {
  1899. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
  1900. signalCursorActivity(doc.cm);
  1901. }
  1902. signalLater(doc, "cursorActivity", doc);
  1903. }
  1904. // Verify that the selection does not partially select any atomic
  1905. // marked ranges.
  1906. function reCheckSelection(doc) {
  1907. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
  1908. }
  1909. // Return a selection that does not partially select any atomic
  1910. // ranges.
  1911. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  1912. var out;
  1913. for (var i = 0; i < sel.ranges.length; i++) {
  1914. var range = sel.ranges[i];
  1915. var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear);
  1916. var newHead = skipAtomic(doc, range.head, bias, mayClear);
  1917. if (out || newAnchor != range.anchor || newHead != range.head) {
  1918. if (!out) out = sel.ranges.slice(0, i);
  1919. out[i] = new Range(newAnchor, newHead);
  1920. }
  1921. }
  1922. return out ? normalizeSelection(out, sel.primIndex) : sel;
  1923. }
  1924. // Ensure a given position is not inside an atomic range.
  1925. function skipAtomic(doc, pos, bias, mayClear) {
  1926. var flipped = false, curPos = pos;
  1927. var dir = bias || 1;
  1928. doc.cantEdit = false;
  1929. search: for (;;) {
  1930. var line = getLine(doc, curPos.line);
  1931. if (line.markedSpans) {
  1932. for (var i = 0; i < line.markedSpans.length; ++i) {
  1933. var sp = line.markedSpans[i], m = sp.marker;
  1934. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
  1935. (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
  1936. if (mayClear) {
  1937. signal(m, "beforeCursorEnter");
  1938. if (m.explicitlyCleared) {
  1939. if (!line.markedSpans) break;
  1940. else {--i; continue;}
  1941. }
  1942. }
  1943. if (!m.atomic) continue;
  1944. var newPos = m.find(dir < 0 ? -1 : 1);
  1945. if (cmp(newPos, curPos) == 0) {
  1946. newPos.ch += dir;
  1947. if (newPos.ch < 0) {
  1948. if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
  1949. else newPos = null;
  1950. } else if (newPos.ch > line.text.length) {
  1951. if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
  1952. else newPos = null;
  1953. }
  1954. if (!newPos) {
  1955. if (flipped) {
  1956. // Driven in a corner -- no valid cursor position found at all
  1957. // -- try again *with* clearing, if we didn't already
  1958. if (!mayClear) return skipAtomic(doc, pos, bias, true);
  1959. // Otherwise, turn off editing until further notice, and return the start of the doc
  1960. doc.cantEdit = true;
  1961. return Pos(doc.first, 0);
  1962. }
  1963. flipped = true; newPos = pos; dir = -dir;
  1964. }
  1965. }
  1966. curPos = newPos;
  1967. continue search;
  1968. }
  1969. }
  1970. }
  1971. return curPos;
  1972. }
  1973. }
  1974. // SELECTION DRAWING
  1975. function updateSelection(cm) {
  1976. cm.display.input.showSelection(cm.display.input.prepareSelection());
  1977. }
  1978. function prepareSelection(cm, primary) {
  1979. var doc = cm.doc, result = {};
  1980. var curFragment = result.cursors = document.createDocumentFragment();
  1981. var selFragment = result.selection = document.createDocumentFragment();
  1982. for (var i = 0; i < doc.sel.ranges.length; i++) {
  1983. if (primary === false && i == doc.sel.primIndex) continue;
  1984. var range = doc.sel.ranges[i];
  1985. var collapsed = range.empty();
  1986. if (collapsed || cm.options.showCursorWhenSelecting)
  1987. drawSelectionCursor(cm, range, curFragment);
  1988. if (!collapsed)
  1989. drawSelectionRange(cm, range, selFragment);
  1990. }
  1991. return result;
  1992. }
  1993. // Draws a cursor for the given range
  1994. function drawSelectionCursor(cm, range, output) {
  1995. var pos = cursorCoords(cm, range.head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  1996. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  1997. cursor.style.left = pos.left + "px";
  1998. cursor.style.top = pos.top + "px";
  1999. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  2000. if (pos.other) {
  2001. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2002. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  2003. otherCursor.style.display = "";
  2004. otherCursor.style.left = pos.other.left + "px";
  2005. otherCursor.style.top = pos.other.top + "px";
  2006. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  2007. }
  2008. }
  2009. // Draws the given range as a highlighted selection
  2010. function drawSelectionRange(cm, range, output) {
  2011. var display = cm.display, doc = cm.doc;
  2012. var fragment = document.createDocumentFragment();
  2013. var padding = paddingH(cm.display), leftSide = padding.left;
  2014. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  2015. function add(left, top, width, bottom) {
  2016. if (top < 0) top = 0;
  2017. top = Math.round(top);
  2018. bottom = Math.round(bottom);
  2019. fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
  2020. "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
  2021. "px; height: " + (bottom - top) + "px"));
  2022. }
  2023. function drawForLine(line, fromArg, toArg) {
  2024. var lineObj = getLine(doc, line);
  2025. var lineLen = lineObj.text.length;
  2026. var start, end;
  2027. function coords(ch, bias) {
  2028. return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
  2029. }
  2030. iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
  2031. var leftPos = coords(from, "left"), rightPos, left, right;
  2032. if (from == to) {
  2033. rightPos = leftPos;
  2034. left = right = leftPos.left;
  2035. } else {
  2036. rightPos = coords(to - 1, "right");
  2037. if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
  2038. left = leftPos.left;
  2039. right = rightPos.right;
  2040. }
  2041. if (fromArg == null && from == 0) left = leftSide;
  2042. if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
  2043. add(left, leftPos.top, null, leftPos.bottom);
  2044. left = leftSide;
  2045. if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
  2046. }
  2047. if (toArg == null && to == lineLen) right = rightSide;
  2048. if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
  2049. start = leftPos;
  2050. if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
  2051. end = rightPos;
  2052. if (left < leftSide + 1) left = leftSide;
  2053. add(left, rightPos.top, right - left, rightPos.bottom);
  2054. });
  2055. return {start: start, end: end};
  2056. }
  2057. var sFrom = range.from(), sTo = range.to();
  2058. if (sFrom.line == sTo.line) {
  2059. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  2060. } else {
  2061. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  2062. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  2063. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  2064. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  2065. if (singleVLine) {
  2066. if (leftEnd.top < rightStart.top - 2) {
  2067. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  2068. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  2069. } else {
  2070. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  2071. }
  2072. }
  2073. if (leftEnd.bottom < rightStart.top)
  2074. add(leftSide, leftEnd.bottom, null, rightStart.top);
  2075. }
  2076. output.appendChild(fragment);
  2077. }
  2078. // Cursor-blinking
  2079. function restartBlink(cm) {
  2080. if (!cm.state.focused) return;
  2081. var display = cm.display;
  2082. clearInterval(display.blinker);
  2083. var on = true;
  2084. display.cursorDiv.style.visibility = "";
  2085. if (cm.options.cursorBlinkRate > 0)
  2086. display.blinker = setInterval(function() {
  2087. display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  2088. }, cm.options.cursorBlinkRate);
  2089. else if (cm.options.cursorBlinkRate < 0)
  2090. display.cursorDiv.style.visibility = "hidden";
  2091. }
  2092. // HIGHLIGHT WORKER
  2093. function startWorker(cm, time) {
  2094. if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
  2095. cm.state.highlight.set(time, bind(highlightWorker, cm));
  2096. }
  2097. function highlightWorker(cm) {
  2098. var doc = cm.doc;
  2099. if (doc.frontier < doc.first) doc.frontier = doc.first;
  2100. if (doc.frontier >= cm.display.viewTo) return;
  2101. var end = +new Date + cm.options.workTime;
  2102. var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
  2103. var changedLines = [];
  2104. doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
  2105. if (doc.frontier >= cm.display.viewFrom) { // Visible
  2106. var oldStyles = line.styles;
  2107. var highlighted = highlightLine(cm, line, state, true);
  2108. line.styles = highlighted.styles;
  2109. var oldCls = line.styleClasses, newCls = highlighted.classes;
  2110. if (newCls) line.styleClasses = newCls;
  2111. else if (oldCls) line.styleClasses = null;
  2112. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  2113. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  2114. for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
  2115. if (ischange) changedLines.push(doc.frontier);
  2116. line.stateAfter = copyState(doc.mode, state);
  2117. } else {
  2118. processLine(cm, line.text, state);
  2119. line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
  2120. }
  2121. ++doc.frontier;
  2122. if (+new Date > end) {
  2123. startWorker(cm, cm.options.workDelay);
  2124. return true;
  2125. }
  2126. });
  2127. if (changedLines.length) runInOp(cm, function() {
  2128. for (var i = 0; i < changedLines.length; i++)
  2129. regLineChange(cm, changedLines[i], "text");
  2130. });
  2131. }
  2132. // Finds the line to start with when starting a parse. Tries to
  2133. // find a line with a stateAfter, so that it can start with a
  2134. // valid state. If that fails, it returns the line with the
  2135. // smallest indentation, which tends to need the least context to
  2136. // parse correctly.
  2137. function findStartLine(cm, n, precise) {
  2138. var minindent, minline, doc = cm.doc;
  2139. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  2140. for (var search = n; search > lim; --search) {
  2141. if (search <= doc.first) return doc.first;
  2142. var line = getLine(doc, search - 1);
  2143. if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
  2144. var indented = countColumn(line.text, null, cm.options.tabSize);
  2145. if (minline == null || minindent > indented) {
  2146. minline = search - 1;
  2147. minindent = indented;
  2148. }
  2149. }
  2150. return minline;
  2151. }
  2152. function getStateBefore(cm, n, precise) {
  2153. var doc = cm.doc, display = cm.display;
  2154. if (!doc.mode.startState) return true;
  2155. var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
  2156. if (!state) state = startState(doc.mode);
  2157. else state = copyState(doc.mode, state);
  2158. doc.iter(pos, n, function(line) {
  2159. processLine(cm, line.text, state);
  2160. var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
  2161. line.stateAfter = save ? copyState(doc.mode, state) : null;
  2162. ++pos;
  2163. });
  2164. if (precise) doc.frontier = pos;
  2165. return state;
  2166. }
  2167. // POSITION MEASUREMENT
  2168. function paddingTop(display) {return display.lineSpace.offsetTop;}
  2169. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
  2170. function paddingH(display) {
  2171. if (display.cachedPaddingH) return display.cachedPaddingH;
  2172. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
  2173. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  2174. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  2175. if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
  2176. return data;
  2177. }
  2178. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
  2179. function displayWidth(cm) {
  2180. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
  2181. }
  2182. function displayHeight(cm) {
  2183. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
  2184. }
  2185. // Ensure the lineView.wrapping.heights array is populated. This is
  2186. // an array of bottom offsets for the lines that make up a drawn
  2187. // line. When lineWrapping is on, there might be more than one
  2188. // height.
  2189. function ensureLineHeights(cm, lineView, rect) {
  2190. var wrapping = cm.options.lineWrapping;
  2191. var curWidth = wrapping && displayWidth(cm);
  2192. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2193. var heights = lineView.measure.heights = [];
  2194. if (wrapping) {
  2195. lineView.measure.width = curWidth;
  2196. var rects = lineView.text.firstChild.getClientRects();
  2197. for (var i = 0; i < rects.length - 1; i++) {
  2198. var cur = rects[i], next = rects[i + 1];
  2199. if (Math.abs(cur.bottom - next.bottom) > 2)
  2200. heights.push((cur.bottom + next.top) / 2 - rect.top);
  2201. }
  2202. }
  2203. heights.push(rect.bottom - rect.top);
  2204. }
  2205. }
  2206. // Find a line map (mapping character offsets to text nodes) and a
  2207. // measurement cache for the given line number. (A line view might
  2208. // contain multiple lines when collapsed ranges are present.)
  2209. function mapFromLineView(lineView, line, lineN) {
  2210. if (lineView.line == line)
  2211. return {map: lineView.measure.map, cache: lineView.measure.cache};
  2212. for (var i = 0; i < lineView.rest.length; i++)
  2213. if (lineView.rest[i] == line)
  2214. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
  2215. for (var i = 0; i < lineView.rest.length; i++)
  2216. if (lineNo(lineView.rest[i]) > lineN)
  2217. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
  2218. }
  2219. // Render a line into the hidden node display.externalMeasured. Used
  2220. // when measurement is needed for a line that's not in the viewport.
  2221. function updateExternalMeasurement(cm, line) {
  2222. line = visualLine(line);
  2223. var lineN = lineNo(line);
  2224. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  2225. view.lineN = lineN;
  2226. var built = view.built = buildLineContent(cm, view);
  2227. view.text = built.pre;
  2228. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  2229. return view;
  2230. }
  2231. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2232. // for a given character.
  2233. function measureChar(cm, line, ch, bias) {
  2234. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
  2235. }
  2236. // Find a line view that corresponds to the given line number.
  2237. function findViewForLine(cm, lineN) {
  2238. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2239. return cm.display.view[findViewIndex(cm, lineN)];
  2240. var ext = cm.display.externalMeasured;
  2241. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2242. return ext;
  2243. }
  2244. // Measurement can be split in two steps, the set-up work that
  2245. // applies to the whole line, and the measurement of the actual
  2246. // character. Functions like coordsChar, that need to do a lot of
  2247. // measurements in a row, can thus ensure that the set-up work is
  2248. // only done once.
  2249. function prepareMeasureForLine(cm, line) {
  2250. var lineN = lineNo(line);
  2251. var view = findViewForLine(cm, lineN);
  2252. if (view && !view.text)
  2253. view = null;
  2254. else if (view && view.changes)
  2255. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  2256. if (!view)
  2257. view = updateExternalMeasurement(cm, line);
  2258. var info = mapFromLineView(view, line, lineN);
  2259. return {
  2260. line: line, view: view, rect: null,
  2261. map: info.map, cache: info.cache, before: info.before,
  2262. hasHeights: false
  2263. };
  2264. }
  2265. // Given a prepared measurement object, measures the position of an
  2266. // actual character (or fetches it from the cache).
  2267. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2268. if (prepared.before) ch = -1;
  2269. var key = ch + (bias || ""), found;
  2270. if (prepared.cache.hasOwnProperty(key)) {
  2271. found = prepared.cache[key];
  2272. } else {
  2273. if (!prepared.rect)
  2274. prepared.rect = prepared.view.text.getBoundingClientRect();
  2275. if (!prepared.hasHeights) {
  2276. ensureLineHeights(cm, prepared.view, prepared.rect);
  2277. prepared.hasHeights = true;
  2278. }
  2279. found = measureCharInner(cm, prepared, ch, bias);
  2280. if (!found.bogus) prepared.cache[key] = found;
  2281. }
  2282. return {left: found.left, right: found.right,
  2283. top: varHeight ? found.rtop : found.top,
  2284. bottom: varHeight ? found.rbottom : found.bottom};
  2285. }
  2286. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  2287. function nodeAndOffsetInLineMap(map, ch, bias) {
  2288. var node, start, end, collapse;
  2289. // First, search the line map for the text node corresponding to,
  2290. // or closest to, the target character.
  2291. for (var i = 0; i < map.length; i += 3) {
  2292. var mStart = map[i], mEnd = map[i + 1];
  2293. if (ch < mStart) {
  2294. start = 0; end = 1;
  2295. collapse = "left";
  2296. } else if (ch < mEnd) {
  2297. start = ch - mStart;
  2298. end = start + 1;
  2299. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2300. end = mEnd - mStart;
  2301. start = end - 1;
  2302. if (ch >= mEnd) collapse = "right";
  2303. }
  2304. if (start != null) {
  2305. node = map[i + 2];
  2306. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2307. collapse = bias;
  2308. if (bias == "left" && start == 0)
  2309. while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2310. node = map[(i -= 3) + 2];
  2311. collapse = "left";
  2312. }
  2313. if (bias == "right" && start == mEnd - mStart)
  2314. while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2315. node = map[(i += 3) + 2];
  2316. collapse = "right";
  2317. }
  2318. break;
  2319. }
  2320. }
  2321. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
  2322. }
  2323. function measureCharInner(cm, prepared, ch, bias) {
  2324. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  2325. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  2326. var rect;
  2327. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2328. for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2329. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
  2330. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
  2331. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
  2332. rect = node.parentNode.getBoundingClientRect();
  2333. } else if (ie && cm.options.lineWrapping) {
  2334. var rects = range(node, start, end).getClientRects();
  2335. if (rects.length)
  2336. rect = rects[bias == "right" ? rects.length - 1 : 0];
  2337. else
  2338. rect = nullRect;
  2339. } else {
  2340. rect = range(node, start, end).getBoundingClientRect() || nullRect;
  2341. }
  2342. if (rect.left || rect.right || start == 0) break;
  2343. end = start;
  2344. start = start - 1;
  2345. collapse = "right";
  2346. }
  2347. if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
  2348. } else { // If it is a widget, simply get the box for the whole widget.
  2349. if (start > 0) collapse = bias = "right";
  2350. var rects;
  2351. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2352. rect = rects[bias == "right" ? rects.length - 1 : 0];
  2353. else
  2354. rect = node.getBoundingClientRect();
  2355. }
  2356. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2357. var rSpan = node.parentNode.getClientRects()[0];
  2358. if (rSpan)
  2359. rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
  2360. else
  2361. rect = nullRect;
  2362. }
  2363. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  2364. var mid = (rtop + rbot) / 2;
  2365. var heights = prepared.view.measure.heights;
  2366. for (var i = 0; i < heights.length - 1; i++)
  2367. if (mid < heights[i]) break;
  2368. var top = i ? heights[i - 1] : 0, bot = heights[i];
  2369. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2370. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2371. top: top, bottom: bot};
  2372. if (!rect.left && !rect.right) result.bogus = true;
  2373. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  2374. return result;
  2375. }
  2376. // Work around problem with bounding client rects on ranges being
  2377. // returned incorrectly when zoomed on IE10 and below.
  2378. function maybeUpdateRectForZooming(measure, rect) {
  2379. if (!window.screen || screen.logicalXDPI == null ||
  2380. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2381. return rect;
  2382. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  2383. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  2384. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2385. top: rect.top * scaleY, bottom: rect.bottom * scaleY};
  2386. }
  2387. function clearLineMeasurementCacheFor(lineView) {
  2388. if (lineView.measure) {
  2389. lineView.measure.cache = {};
  2390. lineView.measure.heights = null;
  2391. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  2392. lineView.measure.caches[i] = {};
  2393. }
  2394. }
  2395. function clearLineMeasurementCache(cm) {
  2396. cm.display.externalMeasure = null;
  2397. removeChildren(cm.display.lineMeasure);
  2398. for (var i = 0; i < cm.display.view.length; i++)
  2399. clearLineMeasurementCacheFor(cm.display.view[i]);
  2400. }
  2401. function clearCaches(cm) {
  2402. clearLineMeasurementCache(cm);
  2403. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  2404. if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
  2405. cm.display.lineNumChars = null;
  2406. }
  2407. function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
  2408. function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
  2409. // Converts a {top, bottom, left, right} box from line-local
  2410. // coordinates into another coordinate system. Context may be one of
  2411. // "line", "div" (display.lineDiv), "local"/null (editor), "window",
  2412. // or "page".
  2413. function intoCoordSystem(cm, lineObj, rect, context) {
  2414. if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
  2415. var size = widgetHeight(lineObj.widgets[i]);
  2416. rect.top += size; rect.bottom += size;
  2417. }
  2418. if (context == "line") return rect;
  2419. if (!context) context = "local";
  2420. var yOff = heightAtLine(lineObj);
  2421. if (context == "local") yOff += paddingTop(cm.display);
  2422. else yOff -= cm.display.viewOffset;
  2423. if (context == "page" || context == "window") {
  2424. var lOff = cm.display.lineSpace.getBoundingClientRect();
  2425. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  2426. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  2427. rect.left += xOff; rect.right += xOff;
  2428. }
  2429. rect.top += yOff; rect.bottom += yOff;
  2430. return rect;
  2431. }
  2432. // Coverts a box from "div" coords to another coordinate system.
  2433. // Context may be "window", "page", "div", or "local"/null.
  2434. function fromCoordSystem(cm, coords, context) {
  2435. if (context == "div") return coords;
  2436. var left = coords.left, top = coords.top;
  2437. // First move into "page" coordinate system
  2438. if (context == "page") {
  2439. left -= pageScrollX();
  2440. top -= pageScrollY();
  2441. } else if (context == "local" || !context) {
  2442. var localBox = cm.display.sizer.getBoundingClientRect();
  2443. left += localBox.left;
  2444. top += localBox.top;
  2445. }
  2446. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  2447. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
  2448. }
  2449. function charCoords(cm, pos, context, lineObj, bias) {
  2450. if (!lineObj) lineObj = getLine(cm.doc, pos.line);
  2451. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
  2452. }
  2453. // Returns a box for a given cursor position, which may have an
  2454. // 'other' property containing the position of the secondary cursor
  2455. // on a bidi boundary.
  2456. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2457. lineObj = lineObj || getLine(cm.doc, pos.line);
  2458. if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2459. function get(ch, right) {
  2460. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  2461. if (right) m.left = m.right; else m.right = m.left;
  2462. return intoCoordSystem(cm, lineObj, m, context);
  2463. }
  2464. function getBidi(ch, partPos) {
  2465. var part = order[partPos], right = part.level % 2;
  2466. if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
  2467. part = order[--partPos];
  2468. ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
  2469. right = true;
  2470. } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
  2471. part = order[++partPos];
  2472. ch = bidiLeft(part) - part.level % 2;
  2473. right = false;
  2474. }
  2475. if (right && ch == part.to && ch > part.from) return get(ch - 1);
  2476. return get(ch, right);
  2477. }
  2478. var order = getOrder(lineObj), ch = pos.ch;
  2479. if (!order) return get(ch);
  2480. var partPos = getBidiPartAt(order, ch);
  2481. var val = getBidi(ch, partPos);
  2482. if (bidiOther != null) val.other = getBidi(ch, bidiOther);
  2483. return val;
  2484. }
  2485. // Used to cheaply estimate the coordinates for a position. Used for
  2486. // intermediate scroll updates.
  2487. function estimateCoords(cm, pos) {
  2488. var left = 0, pos = clipPos(cm.doc, pos);
  2489. if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
  2490. var lineObj = getLine(cm.doc, pos.line);
  2491. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  2492. return {left: left, right: left, top: top, bottom: top + lineObj.height};
  2493. }
  2494. // Positions returned by coordsChar contain some extra information.
  2495. // xRel is the relative x position of the input coordinates compared
  2496. // to the found position (so xRel > 0 means the coordinates are to
  2497. // the right of the character position, for example). When outside
  2498. // is true, that means the coordinates lie outside the line's
  2499. // vertical range.
  2500. function PosWithInfo(line, ch, outside, xRel) {
  2501. var pos = Pos(line, ch);
  2502. pos.xRel = xRel;
  2503. if (outside) pos.outside = true;
  2504. return pos;
  2505. }
  2506. // Compute the character position closest to the given coordinates.
  2507. // Input must be lineSpace-local ("div" coordinate system).
  2508. function coordsChar(cm, x, y) {
  2509. var doc = cm.doc;
  2510. y += cm.display.viewOffset;
  2511. if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
  2512. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  2513. if (lineN > last)
  2514. return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
  2515. if (x < 0) x = 0;
  2516. var lineObj = getLine(doc, lineN);
  2517. for (;;) {
  2518. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  2519. var merged = collapsedSpanAtEnd(lineObj);
  2520. var mergedPos = merged && merged.find(0, true);
  2521. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  2522. lineN = lineNo(lineObj = mergedPos.to.line);
  2523. else
  2524. return found;
  2525. }
  2526. }
  2527. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2528. var innerOff = y - heightAtLine(lineObj);
  2529. var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
  2530. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2531. function getX(ch) {
  2532. var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
  2533. wrongLine = true;
  2534. if (innerOff > sp.bottom) return sp.left - adjust;
  2535. else if (innerOff < sp.top) return sp.left + adjust;
  2536. else wrongLine = false;
  2537. return sp.left;
  2538. }
  2539. var bidi = getOrder(lineObj), dist = lineObj.text.length;
  2540. var from = lineLeft(lineObj), to = lineRight(lineObj);
  2541. var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
  2542. if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
  2543. // Do a binary search between these bounds.
  2544. for (;;) {
  2545. if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
  2546. var ch = x < fromX || x - fromX <= toX - x ? from : to;
  2547. var xDiff = x - (ch == from ? fromX : toX);
  2548. while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
  2549. var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
  2550. xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
  2551. return pos;
  2552. }
  2553. var step = Math.ceil(dist / 2), middle = from + step;
  2554. if (bidi) {
  2555. middle = from;
  2556. for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
  2557. }
  2558. var middleX = getX(middle);
  2559. if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
  2560. else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
  2561. }
  2562. }
  2563. var measureText;
  2564. // Compute the default text height.
  2565. function textHeight(display) {
  2566. if (display.cachedTextHeight != null) return display.cachedTextHeight;
  2567. if (measureText == null) {
  2568. measureText = elt("pre");
  2569. // Measure a bunch of lines, for browsers that compute
  2570. // fractional heights.
  2571. for (var i = 0; i < 49; ++i) {
  2572. measureText.appendChild(document.createTextNode("x"));
  2573. measureText.appendChild(elt("br"));
  2574. }
  2575. measureText.appendChild(document.createTextNode("x"));
  2576. }
  2577. removeChildrenAndAdd(display.measure, measureText);
  2578. var height = measureText.offsetHeight / 50;
  2579. if (height > 3) display.cachedTextHeight = height;
  2580. removeChildren(display.measure);
  2581. return height || 1;
  2582. }
  2583. // Compute the default character width.
  2584. function charWidth(display) {
  2585. if (display.cachedCharWidth != null) return display.cachedCharWidth;
  2586. var anchor = elt("span", "xxxxxxxxxx");
  2587. var pre = elt("pre", [anchor]);
  2588. removeChildrenAndAdd(display.measure, pre);
  2589. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  2590. if (width > 2) display.cachedCharWidth = width;
  2591. return width || 10;
  2592. }
  2593. // OPERATIONS
  2594. // Operations are used to wrap a series of changes to the editor
  2595. // state in such a way that each change won't have to update the
  2596. // cursor and display (which would be awkward, slow, and
  2597. // error-prone). Instead, display updates are batched and then all
  2598. // combined and executed at once.
  2599. var operationGroup = null;
  2600. var nextOpId = 0;
  2601. // Start a new operation.
  2602. function startOperation(cm) {
  2603. cm.curOp = {
  2604. cm: cm,
  2605. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  2606. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  2607. forceUpdate: false, // Used to force a redraw
  2608. updateInput: null, // Whether to reset the input textarea
  2609. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  2610. changeObjs: null, // Accumulated changes, for firing change events
  2611. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  2612. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  2613. selectionChanged: false, // Whether the selection needs to be redrawn
  2614. updateMaxLine: false, // Set when the widest line needs to be determined anew
  2615. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  2616. scrollToPos: null, // Used to scroll to a specific position
  2617. id: ++nextOpId // Unique ID
  2618. };
  2619. if (operationGroup) {
  2620. operationGroup.ops.push(cm.curOp);
  2621. } else {
  2622. cm.curOp.ownsGroup = operationGroup = {
  2623. ops: [cm.curOp],
  2624. delayedCallbacks: []
  2625. };
  2626. }
  2627. }
  2628. function fireCallbacksForOps(group) {
  2629. // Calls delayed callbacks and cursorActivity handlers until no
  2630. // new ones appear
  2631. var callbacks = group.delayedCallbacks, i = 0;
  2632. do {
  2633. for (; i < callbacks.length; i++)
  2634. callbacks[i]();
  2635. for (var j = 0; j < group.ops.length; j++) {
  2636. var op = group.ops[j];
  2637. if (op.cursorActivityHandlers)
  2638. while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  2639. op.cursorActivityHandlers[op.cursorActivityCalled++](op.cm);
  2640. }
  2641. } while (i < callbacks.length);
  2642. }
  2643. // Finish an operation, updating the display and signalling delayed events
  2644. function endOperation(cm) {
  2645. var op = cm.curOp, group = op.ownsGroup;
  2646. if (!group) return;
  2647. try { fireCallbacksForOps(group); }
  2648. finally {
  2649. operationGroup = null;
  2650. for (var i = 0; i < group.ops.length; i++)
  2651. group.ops[i].cm.curOp = null;
  2652. endOperations(group);
  2653. }
  2654. }
  2655. // The DOM updates done when an operation finishes are batched so
  2656. // that the minimum number of relayouts are required.
  2657. function endOperations(group) {
  2658. var ops = group.ops;
  2659. for (var i = 0; i < ops.length; i++) // Read DOM
  2660. endOperation_R1(ops[i]);
  2661. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  2662. endOperation_W1(ops[i]);
  2663. for (var i = 0; i < ops.length; i++) // Read DOM
  2664. endOperation_R2(ops[i]);
  2665. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  2666. endOperation_W2(ops[i]);
  2667. for (var i = 0; i < ops.length; i++) // Read DOM
  2668. endOperation_finish(ops[i]);
  2669. }
  2670. function endOperation_R1(op) {
  2671. var cm = op.cm, display = cm.display;
  2672. maybeClipScrollbars(cm);
  2673. if (op.updateMaxLine) findMaxLine(cm);
  2674. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  2675. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  2676. op.scrollToPos.to.line >= display.viewTo) ||
  2677. display.maxLineChanged && cm.options.lineWrapping;
  2678. op.update = op.mustUpdate &&
  2679. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  2680. }
  2681. function endOperation_W1(op) {
  2682. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  2683. }
  2684. function endOperation_R2(op) {
  2685. var cm = op.cm, display = cm.display;
  2686. if (op.updatedDisplay) updateHeightsInViewport(cm);
  2687. op.barMeasure = measureForScrollbars(cm);
  2688. // If the max line changed since it was last measured, measure it,
  2689. // and ensure the document's width matches it.
  2690. // updateDisplay_W2 will use these properties to do the actual resizing
  2691. if (display.maxLineChanged && !cm.options.lineWrapping) {
  2692. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  2693. cm.display.sizerWidth = op.adjustWidthTo;
  2694. op.barMeasure.scrollWidth =
  2695. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  2696. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  2697. }
  2698. if (op.updatedDisplay || op.selectionChanged)
  2699. op.preparedSelection = display.input.prepareSelection();
  2700. }
  2701. function endOperation_W2(op) {
  2702. var cm = op.cm;
  2703. if (op.adjustWidthTo != null) {
  2704. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  2705. if (op.maxScrollLeft < cm.doc.scrollLeft)
  2706. setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
  2707. cm.display.maxLineChanged = false;
  2708. }
  2709. if (op.preparedSelection)
  2710. cm.display.input.showSelection(op.preparedSelection);
  2711. if (op.updatedDisplay)
  2712. setDocumentHeight(cm, op.barMeasure);
  2713. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  2714. updateScrollbars(cm, op.barMeasure);
  2715. if (op.selectionChanged) restartBlink(cm);
  2716. if (cm.state.focused && op.updateInput)
  2717. cm.display.input.reset(op.typing);
  2718. }
  2719. function endOperation_finish(op) {
  2720. var cm = op.cm, display = cm.display, doc = cm.doc;
  2721. if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
  2722. // Abort mouse wheel delta measurement, when scrolling explicitly
  2723. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  2724. display.wheelStartX = display.wheelStartY = null;
  2725. // Propagate the scroll position to the actual DOM scroller
  2726. if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
  2727. doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
  2728. display.scrollbars.setScrollTop(doc.scrollTop);
  2729. display.scroller.scrollTop = doc.scrollTop;
  2730. }
  2731. if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
  2732. doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft));
  2733. display.scrollbars.setScrollLeft(doc.scrollLeft);
  2734. display.scroller.scrollLeft = doc.scrollLeft;
  2735. alignHorizontally(cm);
  2736. }
  2737. // If we need to scroll a specific position into view, do so.
  2738. if (op.scrollToPos) {
  2739. var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  2740. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  2741. if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
  2742. }
  2743. // Fire events for markers that are hidden/unidden by editing or
  2744. // undoing
  2745. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  2746. if (hidden) for (var i = 0; i < hidden.length; ++i)
  2747. if (!hidden[i].lines.length) signal(hidden[i], "hide");
  2748. if (unhidden) for (var i = 0; i < unhidden.length; ++i)
  2749. if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
  2750. if (display.wrapper.offsetHeight)
  2751. doc.scrollTop = cm.display.scroller.scrollTop;
  2752. // Fire change events, and delayed event handlers
  2753. if (op.changeObjs)
  2754. signal(cm, "changes", cm, op.changeObjs);
  2755. if (op.update)
  2756. op.update.finish();
  2757. }
  2758. // Run the given function in an operation
  2759. function runInOp(cm, f) {
  2760. if (cm.curOp) return f();
  2761. startOperation(cm);
  2762. try { return f(); }
  2763. finally { endOperation(cm); }
  2764. }
  2765. // Wraps a function in an operation. Returns the wrapped function.
  2766. function operation(cm, f) {
  2767. return function() {
  2768. if (cm.curOp) return f.apply(cm, arguments);
  2769. startOperation(cm);
  2770. try { return f.apply(cm, arguments); }
  2771. finally { endOperation(cm); }
  2772. };
  2773. }
  2774. // Used to add methods to editor and doc instances, wrapping them in
  2775. // operations.
  2776. function methodOp(f) {
  2777. return function() {
  2778. if (this.curOp) return f.apply(this, arguments);
  2779. startOperation(this);
  2780. try { return f.apply(this, arguments); }
  2781. finally { endOperation(this); }
  2782. };
  2783. }
  2784. function docMethodOp(f) {
  2785. return function() {
  2786. var cm = this.cm;
  2787. if (!cm || cm.curOp) return f.apply(this, arguments);
  2788. startOperation(cm);
  2789. try { return f.apply(this, arguments); }
  2790. finally { endOperation(cm); }
  2791. };
  2792. }
  2793. // VIEW TRACKING
  2794. // These objects are used to represent the visible (currently drawn)
  2795. // part of the document. A LineView may correspond to multiple
  2796. // logical lines, if those are connected by collapsed ranges.
  2797. function LineView(doc, line, lineN) {
  2798. // The starting line
  2799. this.line = line;
  2800. // Continuing lines, if any
  2801. this.rest = visualLineContinued(line);
  2802. // Number of logical lines in this visual line
  2803. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  2804. this.node = this.text = null;
  2805. this.hidden = lineIsHidden(doc, line);
  2806. }
  2807. // Create a range of LineView objects for the given lines.
  2808. function buildViewArray(cm, from, to) {
  2809. var array = [], nextPos;
  2810. for (var pos = from; pos < to; pos = nextPos) {
  2811. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  2812. nextPos = pos + view.size;
  2813. array.push(view);
  2814. }
  2815. return array;
  2816. }
  2817. // Updates the display.view data structure for a given change to the
  2818. // document. From and to are in pre-change coordinates. Lendiff is
  2819. // the amount of lines added or subtracted by the change. This is
  2820. // used for changes that span multiple lines, or change the way
  2821. // lines are divided into visual lines. regLineChange (below)
  2822. // registers single-line changes.
  2823. function regChange(cm, from, to, lendiff) {
  2824. if (from == null) from = cm.doc.first;
  2825. if (to == null) to = cm.doc.first + cm.doc.size;
  2826. if (!lendiff) lendiff = 0;
  2827. var display = cm.display;
  2828. if (lendiff && to < display.viewTo &&
  2829. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  2830. display.updateLineNumbers = from;
  2831. cm.curOp.viewChanged = true;
  2832. if (from >= display.viewTo) { // Change after
  2833. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  2834. resetView(cm);
  2835. } else if (to <= display.viewFrom) { // Change before
  2836. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  2837. resetView(cm);
  2838. } else {
  2839. display.viewFrom += lendiff;
  2840. display.viewTo += lendiff;
  2841. }
  2842. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  2843. resetView(cm);
  2844. } else if (from <= display.viewFrom) { // Top overlap
  2845. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  2846. if (cut) {
  2847. display.view = display.view.slice(cut.index);
  2848. display.viewFrom = cut.lineN;
  2849. display.viewTo += lendiff;
  2850. } else {
  2851. resetView(cm);
  2852. }
  2853. } else if (to >= display.viewTo) { // Bottom overlap
  2854. var cut = viewCuttingPoint(cm, from, from, -1);
  2855. if (cut) {
  2856. display.view = display.view.slice(0, cut.index);
  2857. display.viewTo = cut.lineN;
  2858. } else {
  2859. resetView(cm);
  2860. }
  2861. } else { // Gap in the middle
  2862. var cutTop = viewCuttingPoint(cm, from, from, -1);
  2863. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  2864. if (cutTop && cutBot) {
  2865. display.view = display.view.slice(0, cutTop.index)
  2866. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  2867. .concat(display.view.slice(cutBot.index));
  2868. display.viewTo += lendiff;
  2869. } else {
  2870. resetView(cm);
  2871. }
  2872. }
  2873. var ext = display.externalMeasured;
  2874. if (ext) {
  2875. if (to < ext.lineN)
  2876. ext.lineN += lendiff;
  2877. else if (from < ext.lineN + ext.size)
  2878. display.externalMeasured = null;
  2879. }
  2880. }
  2881. // Register a change to a single line. Type must be one of "text",
  2882. // "gutter", "class", "widget"
  2883. function regLineChange(cm, line, type) {
  2884. cm.curOp.viewChanged = true;
  2885. var display = cm.display, ext = cm.display.externalMeasured;
  2886. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  2887. display.externalMeasured = null;
  2888. if (line < display.viewFrom || line >= display.viewTo) return;
  2889. var lineView = display.view[findViewIndex(cm, line)];
  2890. if (lineView.node == null) return;
  2891. var arr = lineView.changes || (lineView.changes = []);
  2892. if (indexOf(arr, type) == -1) arr.push(type);
  2893. }
  2894. // Clear the view.
  2895. function resetView(cm) {
  2896. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  2897. cm.display.view = [];
  2898. cm.display.viewOffset = 0;
  2899. }
  2900. // Find the view element corresponding to a given line. Return null
  2901. // when the line isn't visible.
  2902. function findViewIndex(cm, n) {
  2903. if (n >= cm.display.viewTo) return null;
  2904. n -= cm.display.viewFrom;
  2905. if (n < 0) return null;
  2906. var view = cm.display.view;
  2907. for (var i = 0; i < view.length; i++) {
  2908. n -= view[i].size;
  2909. if (n < 0) return i;
  2910. }
  2911. }
  2912. function viewCuttingPoint(cm, oldN, newN, dir) {
  2913. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  2914. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  2915. return {index: index, lineN: newN};
  2916. for (var i = 0, n = cm.display.viewFrom; i < index; i++)
  2917. n += view[i].size;
  2918. if (n != oldN) {
  2919. if (dir > 0) {
  2920. if (index == view.length - 1) return null;
  2921. diff = (n + view[index].size) - oldN;
  2922. index++;
  2923. } else {
  2924. diff = n - oldN;
  2925. }
  2926. oldN += diff; newN += diff;
  2927. }
  2928. while (visualLineNo(cm.doc, newN) != newN) {
  2929. if (index == (dir < 0 ? 0 : view.length - 1)) return null;
  2930. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  2931. index += dir;
  2932. }
  2933. return {index: index, lineN: newN};
  2934. }
  2935. // Force the view to cover a given range, adding empty view element
  2936. // or clipping off existing ones as needed.
  2937. function adjustView(cm, from, to) {
  2938. var display = cm.display, view = display.view;
  2939. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  2940. display.view = buildViewArray(cm, from, to);
  2941. display.viewFrom = from;
  2942. } else {
  2943. if (display.viewFrom > from)
  2944. display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
  2945. else if (display.viewFrom < from)
  2946. display.view = display.view.slice(findViewIndex(cm, from));
  2947. display.viewFrom = from;
  2948. if (display.viewTo < to)
  2949. display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
  2950. else if (display.viewTo > to)
  2951. display.view = display.view.slice(0, findViewIndex(cm, to));
  2952. }
  2953. display.viewTo = to;
  2954. }
  2955. // Count the number of lines in the view whose DOM representation is
  2956. // out of date (or nonexistent).
  2957. function countDirtyView(cm) {
  2958. var view = cm.display.view, dirty = 0;
  2959. for (var i = 0; i < view.length; i++) {
  2960. var lineView = view[i];
  2961. if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
  2962. }
  2963. return dirty;
  2964. }
  2965. // EVENT HANDLERS
  2966. // Attach the necessary event handlers when initializing the editor
  2967. function registerEventHandlers(cm) {
  2968. var d = cm.display;
  2969. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  2970. // Older IE's will not fire a second mousedown for a double click
  2971. if (ie && ie_version < 11)
  2972. on(d.scroller, "dblclick", operation(cm, function(e) {
  2973. if (signalDOMEvent(cm, e)) return;
  2974. var pos = posFromMouse(cm, e);
  2975. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
  2976. e_preventDefault(e);
  2977. var word = cm.findWordAt(pos);
  2978. extendSelection(cm.doc, word.anchor, word.head);
  2979. }));
  2980. else
  2981. on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
  2982. // Some browsers fire contextmenu *after* opening the menu, at
  2983. // which point we can't mess with it anymore. Context menu is
  2984. // handled in onMouseDown for these browsers.
  2985. if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
  2986. // Used to suppress mouse event handling when a touch happens
  2987. var touchFinished, prevTouch = {end: 0};
  2988. function finishTouch() {
  2989. if (d.activeTouch) {
  2990. touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000);
  2991. prevTouch = d.activeTouch;
  2992. prevTouch.end = +new Date;
  2993. }
  2994. };
  2995. function isMouseLikeTouchEvent(e) {
  2996. if (e.touches.length != 1) return false;
  2997. var touch = e.touches[0];
  2998. return touch.radiusX <= 1 && touch.radiusY <= 1;
  2999. }
  3000. function farAway(touch, other) {
  3001. if (other.left == null) return true;
  3002. var dx = other.left - touch.left, dy = other.top - touch.top;
  3003. return dx * dx + dy * dy > 20 * 20;
  3004. }
  3005. on(d.scroller, "touchstart", function(e) {
  3006. if (!isMouseLikeTouchEvent(e)) {
  3007. clearTimeout(touchFinished);
  3008. var now = +new Date;
  3009. d.activeTouch = {start: now, moved: false,
  3010. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  3011. if (e.touches.length == 1) {
  3012. d.activeTouch.left = e.touches[0].pageX;
  3013. d.activeTouch.top = e.touches[0].pageY;
  3014. }
  3015. }
  3016. });
  3017. on(d.scroller, "touchmove", function() {
  3018. if (d.activeTouch) d.activeTouch.moved = true;
  3019. });
  3020. on(d.scroller, "touchend", function(e) {
  3021. var touch = d.activeTouch;
  3022. if (touch && !eventInWidget(d, e) && touch.left != null &&
  3023. !touch.moved && new Date - touch.start < 300) {
  3024. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  3025. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  3026. range = new Range(pos, pos);
  3027. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  3028. range = cm.findWordAt(pos);
  3029. else // Triple tap
  3030. range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
  3031. cm.setSelection(range.anchor, range.head);
  3032. cm.focus();
  3033. e_preventDefault(e);
  3034. }
  3035. finishTouch();
  3036. });
  3037. on(d.scroller, "touchcancel", finishTouch);
  3038. // Sync scrolling between fake scrollbars and real scrollable
  3039. // area, ensure viewport is updated when scrolling.
  3040. on(d.scroller, "scroll", function() {
  3041. if (d.scroller.clientHeight) {
  3042. setScrollTop(cm, d.scroller.scrollTop);
  3043. setScrollLeft(cm, d.scroller.scrollLeft, true);
  3044. signal(cm, "scroll", cm);
  3045. }
  3046. });
  3047. // Listen to wheel events in order to try and update the viewport on time.
  3048. on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
  3049. on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
  3050. // Prevent wrapper from ever scrolling
  3051. on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  3052. function drag_(e) {
  3053. if (!signalDOMEvent(cm, e)) e_stop(e);
  3054. }
  3055. if (cm.options.dragDrop) {
  3056. on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});
  3057. on(d.scroller, "dragenter", drag_);
  3058. on(d.scroller, "dragover", drag_);
  3059. on(d.scroller, "drop", operation(cm, onDrop));
  3060. }
  3061. var inp = d.input.getField();
  3062. on(inp, "keyup", function(e) { onKeyUp.call(cm, e); });
  3063. on(inp, "keydown", operation(cm, onKeyDown));
  3064. on(inp, "keypress", operation(cm, onKeyPress));
  3065. on(inp, "focus", bind(onFocus, cm));
  3066. on(inp, "blur", bind(onBlur, cm));
  3067. }
  3068. // Called when the window resizes
  3069. function onResize(cm) {
  3070. var d = cm.display;
  3071. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  3072. return;
  3073. // Might be a text scaling operation, clear size caches.
  3074. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  3075. d.scrollbarsClipped = false;
  3076. cm.setSize();
  3077. }
  3078. // MOUSE EVENTS
  3079. // Return true when the given mouse event happened in a widget
  3080. function eventInWidget(display, e) {
  3081. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  3082. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  3083. (n.parentNode == display.sizer && n != display.mover))
  3084. return true;
  3085. }
  3086. }
  3087. // Given a mouse event, find the corresponding position. If liberal
  3088. // is false, it checks whether a gutter or scrollbar was clicked,
  3089. // and returns null if it was. forRect is used by rectangular
  3090. // selections, and tries to estimate a character position even for
  3091. // coordinates beyond the right of the text.
  3092. function posFromMouse(cm, e, liberal, forRect) {
  3093. var display = cm.display;
  3094. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null;
  3095. var x, y, space = display.lineSpace.getBoundingClientRect();
  3096. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  3097. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  3098. catch (e) { return null; }
  3099. var coords = coordsChar(cm, x, y), line;
  3100. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  3101. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  3102. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  3103. }
  3104. return coords;
  3105. }
  3106. // A mouse down can be a single click, double click, triple click,
  3107. // start of selection drag, start of text drag, new cursor
  3108. // (ctrl-click), rectangle drag (alt-drag), or xwin
  3109. // middle-click-paste. Or it might be a click on something we should
  3110. // not interfere with, such as a scrollbar or widget.
  3111. function onMouseDown(e) {
  3112. var cm = this, display = cm.display;
  3113. if (display.activeTouch && display.input.supportsTouch() || signalDOMEvent(cm, e)) return;
  3114. display.shift = e.shiftKey;
  3115. if (eventInWidget(display, e)) {
  3116. if (!webkit) {
  3117. // Briefly turn off draggability, to allow widgets to do
  3118. // normal dragging things.
  3119. display.scroller.draggable = false;
  3120. setTimeout(function(){display.scroller.draggable = true;}, 100);
  3121. }
  3122. return;
  3123. }
  3124. if (clickInGutter(cm, e)) return;
  3125. var start = posFromMouse(cm, e);
  3126. window.focus();
  3127. switch (e_button(e)) {
  3128. case 1:
  3129. if (start)
  3130. leftButtonDown(cm, e, start);
  3131. else if (e_target(e) == display.scroller)
  3132. e_preventDefault(e);
  3133. break;
  3134. case 2:
  3135. if (webkit) cm.state.lastMiddleDown = +new Date;
  3136. if (start) extendSelection(cm.doc, start);
  3137. setTimeout(function() {display.input.focus();}, 20);
  3138. e_preventDefault(e);
  3139. break;
  3140. case 3:
  3141. if (captureRightClick) onContextMenu(cm, e);
  3142. else delayBlurEvent(cm);
  3143. break;
  3144. }
  3145. }
  3146. var lastClick, lastDoubleClick;
  3147. function leftButtonDown(cm, e, start) {
  3148. if (ie) setTimeout(bind(ensureFocus, cm), 0);
  3149. else ensureFocus(cm);
  3150. var now = +new Date, type;
  3151. if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
  3152. type = "triple";
  3153. } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
  3154. type = "double";
  3155. lastDoubleClick = {time: now, pos: start};
  3156. } else {
  3157. type = "single";
  3158. lastClick = {time: now, pos: start};
  3159. }
  3160. var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
  3161. if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) &&
  3162. type == "single" && (contained = sel.contains(start)) > -1 &&
  3163. !sel.ranges[contained].empty())
  3164. leftButtonStartDrag(cm, e, start, modifier);
  3165. else
  3166. leftButtonSelect(cm, e, start, type, modifier);
  3167. }
  3168. // Start a text drag. When it ends, see if any dragging actually
  3169. // happen, and treat as a click if it didn't.
  3170. function leftButtonStartDrag(cm, e, start, modifier) {
  3171. var display = cm.display;
  3172. var dragEnd = operation(cm, function(e2) {
  3173. if (webkit) display.scroller.draggable = false;
  3174. cm.state.draggingText = false;
  3175. off(document, "mouseup", dragEnd);
  3176. off(display.scroller, "drop", dragEnd);
  3177. if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
  3178. e_preventDefault(e2);
  3179. if (!modifier)
  3180. extendSelection(cm.doc, start);
  3181. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  3182. if (webkit || ie && ie_version == 9)
  3183. setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
  3184. else
  3185. display.input.focus();
  3186. }
  3187. });
  3188. // Let the drag handler handle this.
  3189. if (webkit) display.scroller.draggable = true;
  3190. cm.state.draggingText = dragEnd;
  3191. // IE's approach to draggable
  3192. if (display.scroller.dragDrop) display.scroller.dragDrop();
  3193. on(document, "mouseup", dragEnd);
  3194. on(display.scroller, "drop", dragEnd);
  3195. }
  3196. // Normal selection, as opposed to text dragging.
  3197. function leftButtonSelect(cm, e, start, type, addNew) {
  3198. var display = cm.display, doc = cm.doc;
  3199. e_preventDefault(e);
  3200. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  3201. if (addNew && !e.shiftKey) {
  3202. ourIndex = doc.sel.contains(start);
  3203. if (ourIndex > -1)
  3204. ourRange = ranges[ourIndex];
  3205. else
  3206. ourRange = new Range(start, start);
  3207. } else {
  3208. ourRange = doc.sel.primary();
  3209. ourIndex = doc.sel.primIndex;
  3210. }
  3211. if (e.altKey) {
  3212. type = "rect";
  3213. if (!addNew) ourRange = new Range(start, start);
  3214. start = posFromMouse(cm, e, true, true);
  3215. ourIndex = -1;
  3216. } else if (type == "double") {
  3217. var word = cm.findWordAt(start);
  3218. if (cm.display.shift || doc.extend)
  3219. ourRange = extendRange(doc, ourRange, word.anchor, word.head);
  3220. else
  3221. ourRange = word;
  3222. } else if (type == "triple") {
  3223. var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
  3224. if (cm.display.shift || doc.extend)
  3225. ourRange = extendRange(doc, ourRange, line.anchor, line.head);
  3226. else
  3227. ourRange = line;
  3228. } else {
  3229. ourRange = extendRange(doc, ourRange, start);
  3230. }
  3231. if (!addNew) {
  3232. ourIndex = 0;
  3233. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  3234. startSel = doc.sel;
  3235. } else if (ourIndex == -1) {
  3236. ourIndex = ranges.length;
  3237. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  3238. {scroll: false, origin: "*mouse"});
  3239. } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
  3240. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0));
  3241. startSel = doc.sel;
  3242. } else {
  3243. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  3244. }
  3245. var lastPos = start;
  3246. function extendTo(pos) {
  3247. if (cmp(lastPos, pos) == 0) return;
  3248. lastPos = pos;
  3249. if (type == "rect") {
  3250. var ranges = [], tabSize = cm.options.tabSize;
  3251. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  3252. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  3253. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  3254. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  3255. line <= end; line++) {
  3256. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  3257. if (left == right)
  3258. ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
  3259. else if (text.length > leftPos)
  3260. ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
  3261. }
  3262. if (!ranges.length) ranges.push(new Range(start, start));
  3263. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  3264. {origin: "*mouse", scroll: false});
  3265. cm.scrollIntoView(pos);
  3266. } else {
  3267. var oldRange = ourRange;
  3268. var anchor = oldRange.anchor, head = pos;
  3269. if (type != "single") {
  3270. if (type == "double")
  3271. var range = cm.findWordAt(pos);
  3272. else
  3273. var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
  3274. if (cmp(range.anchor, anchor) > 0) {
  3275. head = range.head;
  3276. anchor = minPos(oldRange.from(), range.anchor);
  3277. } else {
  3278. head = range.anchor;
  3279. anchor = maxPos(oldRange.to(), range.head);
  3280. }
  3281. }
  3282. var ranges = startSel.ranges.slice(0);
  3283. ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
  3284. setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
  3285. }
  3286. }
  3287. var editorSize = display.wrapper.getBoundingClientRect();
  3288. // Used to ensure timeout re-tries don't fire when another extend
  3289. // happened in the meantime (clearTimeout isn't reliable -- at
  3290. // least on Chrome, the timeouts still happen even when cleared,
  3291. // if the clear happens after their scheduled firing time).
  3292. var counter = 0;
  3293. function extend(e) {
  3294. var curCount = ++counter;
  3295. var cur = posFromMouse(cm, e, true, type == "rect");
  3296. if (!cur) return;
  3297. if (cmp(cur, lastPos) != 0) {
  3298. ensureFocus(cm);
  3299. extendTo(cur);
  3300. var visible = visibleLines(display, doc);
  3301. if (cur.line >= visible.to || cur.line < visible.from)
  3302. setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
  3303. } else {
  3304. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  3305. if (outside) setTimeout(operation(cm, function() {
  3306. if (counter != curCount) return;
  3307. display.scroller.scrollTop += outside;
  3308. extend(e);
  3309. }), 50);
  3310. }
  3311. }
  3312. function done(e) {
  3313. counter = Infinity;
  3314. e_preventDefault(e);
  3315. display.input.focus();
  3316. off(document, "mousemove", move);
  3317. off(document, "mouseup", up);
  3318. doc.history.lastSelOrigin = null;
  3319. }
  3320. var move = operation(cm, function(e) {
  3321. if (!e_button(e)) done(e);
  3322. else extend(e);
  3323. });
  3324. var up = operation(cm, done);
  3325. on(document, "mousemove", move);
  3326. on(document, "mouseup", up);
  3327. }
  3328. // Determines whether an event happened in the gutter, and fires the
  3329. // handlers for the corresponding event.
  3330. function gutterEvent(cm, e, type, prevent, signalfn) {
  3331. try { var mX = e.clientX, mY = e.clientY; }
  3332. catch(e) { return false; }
  3333. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
  3334. if (prevent) e_preventDefault(e);
  3335. var display = cm.display;
  3336. var lineBox = display.lineDiv.getBoundingClientRect();
  3337. if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
  3338. mY -= lineBox.top - display.viewOffset;
  3339. for (var i = 0; i < cm.options.gutters.length; ++i) {
  3340. var g = display.gutters.childNodes[i];
  3341. if (g && g.getBoundingClientRect().right >= mX) {
  3342. var line = lineAtHeight(cm.doc, mY);
  3343. var gutter = cm.options.gutters[i];
  3344. signalfn(cm, type, cm, line, gutter, e);
  3345. return e_defaultPrevented(e);
  3346. }
  3347. }
  3348. }
  3349. function clickInGutter(cm, e) {
  3350. return gutterEvent(cm, e, "gutterClick", true, signalLater);
  3351. }
  3352. // Kludge to work around strange IE behavior where it'll sometimes
  3353. // re-fire a series of drag-related events right after the drop (#1551)
  3354. var lastDrop = 0;
  3355. function onDrop(e) {
  3356. var cm = this;
  3357. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  3358. return;
  3359. e_preventDefault(e);
  3360. if (ie) lastDrop = +new Date;
  3361. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  3362. if (!pos || isReadOnly(cm)) return;
  3363. // Might be a file drop, in which case we simply extract the text
  3364. // and insert it.
  3365. if (files && files.length && window.FileReader && window.File) {
  3366. var n = files.length, text = Array(n), read = 0;
  3367. var loadFile = function(file, i) {
  3368. var reader = new FileReader;
  3369. reader.onload = operation(cm, function() {
  3370. text[i] = reader.result;
  3371. if (++read == n) {
  3372. pos = clipPos(cm.doc, pos);
  3373. var change = {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"};
  3374. makeChange(cm.doc, change);
  3375. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
  3376. }
  3377. });
  3378. reader.readAsText(file);
  3379. };
  3380. for (var i = 0; i < n; ++i) loadFile(files[i], i);
  3381. } else { // Normal drop
  3382. // Don't do a replace if the drop happened inside of the selected text.
  3383. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  3384. cm.state.draggingText(e);
  3385. // Ensure the editor is re-focused
  3386. setTimeout(function() {cm.display.input.focus();}, 20);
  3387. return;
  3388. }
  3389. try {
  3390. var text = e.dataTransfer.getData("Text");
  3391. if (text) {
  3392. if (cm.state.draggingText && !(mac ? e.metaKey : e.ctrlKey))
  3393. var selected = cm.listSelections();
  3394. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  3395. if (selected) for (var i = 0; i < selected.length; ++i)
  3396. replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
  3397. cm.replaceSelection(text, "around", "paste");
  3398. cm.display.input.focus();
  3399. }
  3400. }
  3401. catch(e){}
  3402. }
  3403. }
  3404. function onDragStart(cm, e) {
  3405. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
  3406. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
  3407. e.dataTransfer.setData("Text", cm.getSelection());
  3408. // Use dummy image instead of default browsers image.
  3409. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  3410. if (e.dataTransfer.setDragImage && !safari) {
  3411. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  3412. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  3413. if (presto) {
  3414. img.width = img.height = 1;
  3415. cm.display.wrapper.appendChild(img);
  3416. // Force a relayout, or Opera won't use our image for some obscure reason
  3417. img._top = img.offsetTop;
  3418. }
  3419. e.dataTransfer.setDragImage(img, 0, 0);
  3420. if (presto) img.parentNode.removeChild(img);
  3421. }
  3422. }
  3423. // SCROLL EVENTS
  3424. // Sync the scrollable area and scrollbars, ensure the viewport
  3425. // covers the visible area.
  3426. function setScrollTop(cm, val) {
  3427. if (Math.abs(cm.doc.scrollTop - val) < 2) return;
  3428. cm.doc.scrollTop = val;
  3429. if (!gecko) updateDisplaySimple(cm, {top: val});
  3430. if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
  3431. cm.display.scrollbars.setScrollTop(val);
  3432. if (gecko) updateDisplaySimple(cm);
  3433. startWorker(cm, 100);
  3434. }
  3435. // Sync scroller and scrollbar, ensure the gutter elements are
  3436. // aligned.
  3437. function setScrollLeft(cm, val, isScroller) {
  3438. if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
  3439. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  3440. cm.doc.scrollLeft = val;
  3441. alignHorizontally(cm);
  3442. if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
  3443. cm.display.scrollbars.setScrollLeft(val);
  3444. }
  3445. // Since the delta values reported on mouse wheel events are
  3446. // unstandardized between browsers and even browser versions, and
  3447. // generally horribly unpredictable, this code starts by measuring
  3448. // the scroll effect that the first few mouse wheel events have,
  3449. // and, from that, detects the way it can convert deltas to pixel
  3450. // offsets afterwards.
  3451. //
  3452. // The reason we want to know the amount a wheel event will scroll
  3453. // is that it gives us a chance to update the display before the
  3454. // actual scrolling happens, reducing flickering.
  3455. var wheelSamples = 0, wheelPixelsPerUnit = null;
  3456. // Fill in a browser-detected starting value on browsers where we
  3457. // know one. These don't have to be accurate -- the result of them
  3458. // being wrong would just be a slight flicker on the first wheel
  3459. // scroll (if it is large enough).
  3460. if (ie) wheelPixelsPerUnit = -.53;
  3461. else if (gecko) wheelPixelsPerUnit = 15;
  3462. else if (chrome) wheelPixelsPerUnit = -.7;
  3463. else if (safari) wheelPixelsPerUnit = -1/3;
  3464. var wheelEventDelta = function(e) {
  3465. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  3466. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
  3467. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
  3468. else if (dy == null) dy = e.wheelDelta;
  3469. return {x: dx, y: dy};
  3470. };
  3471. CodeMirror.wheelEventPixels = function(e) {
  3472. var delta = wheelEventDelta(e);
  3473. delta.x *= wheelPixelsPerUnit;
  3474. delta.y *= wheelPixelsPerUnit;
  3475. return delta;
  3476. };
  3477. function onScrollWheel(cm, e) {
  3478. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  3479. var display = cm.display, scroll = display.scroller;
  3480. // Quit if there's nothing to scroll here
  3481. if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
  3482. dy && scroll.scrollHeight > scroll.clientHeight)) return;
  3483. // Webkit browsers on OS X abort momentum scrolls when the target
  3484. // of the scroll event is removed from the scrollable element.
  3485. // This hack (see related code in patchDisplay) makes sure the
  3486. // element is kept around.
  3487. if (dy && mac && webkit) {
  3488. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  3489. for (var i = 0; i < view.length; i++) {
  3490. if (view[i].node == cur) {
  3491. cm.display.currentWheelTarget = cur;
  3492. break outer;
  3493. }
  3494. }
  3495. }
  3496. }
  3497. // On some browsers, horizontal scrolling will cause redraws to
  3498. // happen before the gutter has been realigned, causing it to
  3499. // wriggle around in a most unseemly way. When we have an
  3500. // estimated pixels/delta value, we just handle horizontal
  3501. // scrolling entirely here. It'll be slightly off from native, but
  3502. // better than glitching out.
  3503. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  3504. if (dy)
  3505. setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
  3506. setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
  3507. e_preventDefault(e);
  3508. display.wheelStartX = null; // Abort measurement, if in progress
  3509. return;
  3510. }
  3511. // 'Project' the visible viewport to cover the area that is being
  3512. // scrolled into view (if we know enough to estimate it).
  3513. if (dy && wheelPixelsPerUnit != null) {
  3514. var pixels = dy * wheelPixelsPerUnit;
  3515. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  3516. if (pixels < 0) top = Math.max(0, top + pixels - 50);
  3517. else bot = Math.min(cm.doc.height, bot + pixels + 50);
  3518. updateDisplaySimple(cm, {top: top, bottom: bot});
  3519. }
  3520. if (wheelSamples < 20) {
  3521. if (display.wheelStartX == null) {
  3522. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  3523. display.wheelDX = dx; display.wheelDY = dy;
  3524. setTimeout(function() {
  3525. if (display.wheelStartX == null) return;
  3526. var movedX = scroll.scrollLeft - display.wheelStartX;
  3527. var movedY = scroll.scrollTop - display.wheelStartY;
  3528. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  3529. (movedX && display.wheelDX && movedX / display.wheelDX);
  3530. display.wheelStartX = display.wheelStartY = null;
  3531. if (!sample) return;
  3532. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  3533. ++wheelSamples;
  3534. }, 200);
  3535. } else {
  3536. display.wheelDX += dx; display.wheelDY += dy;
  3537. }
  3538. }
  3539. }
  3540. // KEY EVENTS
  3541. // Run a handler that was bound to a key.
  3542. function doHandleBinding(cm, bound, dropShift) {
  3543. if (typeof bound == "string") {
  3544. bound = commands[bound];
  3545. if (!bound) return false;
  3546. }
  3547. // Ensure previous input has been read, so that the handler sees a
  3548. // consistent view of the document
  3549. cm.display.input.ensurePolled();
  3550. var prevShift = cm.display.shift, done = false;
  3551. try {
  3552. if (isReadOnly(cm)) cm.state.suppressEdits = true;
  3553. if (dropShift) cm.display.shift = false;
  3554. done = bound(cm) != Pass;
  3555. } finally {
  3556. cm.display.shift = prevShift;
  3557. cm.state.suppressEdits = false;
  3558. }
  3559. return done;
  3560. }
  3561. function lookupKeyForEditor(cm, name, handle) {
  3562. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  3563. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  3564. if (result) return result;
  3565. }
  3566. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  3567. || lookupKey(name, cm.options.keyMap, handle, cm);
  3568. }
  3569. var stopSeq = new Delayed;
  3570. function dispatchKey(cm, name, e, handle) {
  3571. var seq = cm.state.keySeq;
  3572. if (seq) {
  3573. if (isModifierKey(name)) return "handled";
  3574. stopSeq.set(50, function() {
  3575. if (cm.state.keySeq == seq) {
  3576. cm.state.keySeq = null;
  3577. cm.display.input.reset();
  3578. }
  3579. });
  3580. name = seq + " " + name;
  3581. }
  3582. var result = lookupKeyForEditor(cm, name, handle);
  3583. if (result == "multi")
  3584. cm.state.keySeq = name;
  3585. if (result == "handled")
  3586. signalLater(cm, "keyHandled", cm, name, e);
  3587. if (result == "handled" || result == "multi") {
  3588. e_preventDefault(e);
  3589. restartBlink(cm);
  3590. }
  3591. if (seq && !result && /\'$/.test(name)) {
  3592. e_preventDefault(e);
  3593. return true;
  3594. }
  3595. return !!result;
  3596. }
  3597. // Handle a key from the keydown event.
  3598. function handleKeyBinding(cm, e) {
  3599. var name = keyName(e, true);
  3600. if (!name) return false;
  3601. if (e.shiftKey && !cm.state.keySeq) {
  3602. // First try to resolve full name (including 'Shift-'). Failing
  3603. // that, see if there is a cursor-motion command (starting with
  3604. // 'go') bound to the keyname without 'Shift-'.
  3605. return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})
  3606. || dispatchKey(cm, name, e, function(b) {
  3607. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  3608. return doHandleBinding(cm, b);
  3609. });
  3610. } else {
  3611. return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
  3612. }
  3613. }
  3614. // Handle a key from the keypress event
  3615. function handleCharBinding(cm, e, ch) {
  3616. return dispatchKey(cm, "'" + ch + "'", e,
  3617. function(b) { return doHandleBinding(cm, b, true); });
  3618. }
  3619. var lastStoppedKey = null;
  3620. function onKeyDown(e) {
  3621. var cm = this;
  3622. ensureFocus(cm);
  3623. if (signalDOMEvent(cm, e)) return;
  3624. // IE does strange things with escape.
  3625. if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
  3626. var code = e.keyCode;
  3627. cm.display.shift = code == 16 || e.shiftKey;
  3628. var handled = handleKeyBinding(cm, e);
  3629. if (presto) {
  3630. lastStoppedKey = handled ? code : null;
  3631. // Opera has no cut event... we try to at least catch the key combo
  3632. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  3633. cm.replaceSelection("", null, "cut");
  3634. }
  3635. // Turn mouse into crosshair when Alt is held on Mac.
  3636. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  3637. showCrossHair(cm);
  3638. }
  3639. function showCrossHair(cm) {
  3640. var lineDiv = cm.display.lineDiv;
  3641. addClass(lineDiv, "CodeMirror-crosshair");
  3642. function up(e) {
  3643. if (e.keyCode == 18 || !e.altKey) {
  3644. rmClass(lineDiv, "CodeMirror-crosshair");
  3645. off(document, "keyup", up);
  3646. off(document, "mouseover", up);
  3647. }
  3648. }
  3649. on(document, "keyup", up);
  3650. on(document, "mouseover", up);
  3651. }
  3652. function onKeyUp(e) {
  3653. if (e.keyCode == 16) this.doc.sel.shift = false;
  3654. signalDOMEvent(this, e);
  3655. }
  3656. function onKeyPress(e) {
  3657. var cm = this;
  3658. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
  3659. var keyCode = e.keyCode, charCode = e.charCode;
  3660. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
  3661. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return;
  3662. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  3663. if (handleCharBinding(cm, e, ch)) return;
  3664. cm.display.input.onKeyPress(e);
  3665. }
  3666. // FOCUS/BLUR EVENTS
  3667. function delayBlurEvent(cm) {
  3668. cm.state.delayingBlurEvent = true;
  3669. setTimeout(function() {
  3670. if (cm.state.delayingBlurEvent) {
  3671. cm.state.delayingBlurEvent = false;
  3672. onBlur(cm);
  3673. }
  3674. }, 100);
  3675. }
  3676. function onFocus(cm) {
  3677. if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
  3678. if (cm.options.readOnly == "nocursor") return;
  3679. if (!cm.state.focused) {
  3680. signal(cm, "focus", cm);
  3681. cm.state.focused = true;
  3682. addClass(cm.display.wrapper, "CodeMirror-focused");
  3683. // This test prevents this from firing when a context
  3684. // menu is closed (since the input reset would kill the
  3685. // select-all detection hack)
  3686. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  3687. cm.display.input.reset();
  3688. if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
  3689. }
  3690. cm.display.input.receivedFocus();
  3691. }
  3692. restartBlink(cm);
  3693. }
  3694. function onBlur(cm) {
  3695. if (cm.state.delayingBlurEvent) return;
  3696. if (cm.state.focused) {
  3697. signal(cm, "blur", cm);
  3698. cm.state.focused = false;
  3699. rmClass(cm.display.wrapper, "CodeMirror-focused");
  3700. }
  3701. clearInterval(cm.display.blinker);
  3702. setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
  3703. }
  3704. // CONTEXT MENU HANDLING
  3705. // To make the context menu work, we need to briefly unhide the
  3706. // textarea (making it as unobtrusive as possible) to let the
  3707. // right-click take effect on it.
  3708. function onContextMenu(cm, e) {
  3709. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
  3710. cm.display.input.onContextMenu(e);
  3711. }
  3712. function contextMenuInGutter(cm, e) {
  3713. if (!hasHandler(cm, "gutterContextMenu")) return false;
  3714. return gutterEvent(cm, e, "gutterContextMenu", false, signal);
  3715. }
  3716. // UPDATING
  3717. // Compute the position of the end of a change (its 'to' property
  3718. // refers to the pre-change end).
  3719. var changeEnd = CodeMirror.changeEnd = function(change) {
  3720. if (!change.text) return change.to;
  3721. return Pos(change.from.line + change.text.length - 1,
  3722. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
  3723. };
  3724. // Adjust a position to refer to the post-change position of the
  3725. // same text, or the end of the change if the change covers it.
  3726. function adjustForChange(pos, change) {
  3727. if (cmp(pos, change.from) < 0) return pos;
  3728. if (cmp(pos, change.to) <= 0) return changeEnd(change);
  3729. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  3730. if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
  3731. return Pos(line, ch);
  3732. }
  3733. function computeSelAfterChange(doc, change) {
  3734. var out = [];
  3735. for (var i = 0; i < doc.sel.ranges.length; i++) {
  3736. var range = doc.sel.ranges[i];
  3737. out.push(new Range(adjustForChange(range.anchor, change),
  3738. adjustForChange(range.head, change)));
  3739. }
  3740. return normalizeSelection(out, doc.sel.primIndex);
  3741. }
  3742. function offsetPos(pos, old, nw) {
  3743. if (pos.line == old.line)
  3744. return Pos(nw.line, pos.ch - old.ch + nw.ch);
  3745. else
  3746. return Pos(nw.line + (pos.line - old.line), pos.ch);
  3747. }
  3748. // Used by replaceSelections to allow moving the selection to the
  3749. // start or around the replaced test. Hint may be "start" or "around".
  3750. function computeReplacedSel(doc, changes, hint) {
  3751. var out = [];
  3752. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  3753. for (var i = 0; i < changes.length; i++) {
  3754. var change = changes[i];
  3755. var from = offsetPos(change.from, oldPrev, newPrev);
  3756. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  3757. oldPrev = change.to;
  3758. newPrev = to;
  3759. if (hint == "around") {
  3760. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  3761. out[i] = new Range(inv ? to : from, inv ? from : to);
  3762. } else {
  3763. out[i] = new Range(from, from);
  3764. }
  3765. }
  3766. return new Selection(out, doc.sel.primIndex);
  3767. }
  3768. // Allow "beforeChange" event handlers to influence a change
  3769. function filterChange(doc, change, update) {
  3770. var obj = {
  3771. canceled: false,
  3772. from: change.from,
  3773. to: change.to,
  3774. text: change.text,
  3775. origin: change.origin,
  3776. cancel: function() { this.canceled = true; }
  3777. };
  3778. if (update) obj.update = function(from, to, text, origin) {
  3779. if (from) this.from = clipPos(doc, from);
  3780. if (to) this.to = clipPos(doc, to);
  3781. if (text) this.text = text;
  3782. if (origin !== undefined) this.origin = origin;
  3783. };
  3784. signal(doc, "beforeChange", doc, obj);
  3785. if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
  3786. if (obj.canceled) return null;
  3787. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
  3788. }
  3789. // Apply a change to a document, and add it to the document's
  3790. // history, and propagating it to all linked documents.
  3791. function makeChange(doc, change, ignoreReadOnly) {
  3792. if (doc.cm) {
  3793. if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
  3794. if (doc.cm.state.suppressEdits) return;
  3795. }
  3796. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  3797. change = filterChange(doc, change, true);
  3798. if (!change) return;
  3799. }
  3800. // Possibly split or suppress the update based on the presence
  3801. // of read-only spans in its range.
  3802. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  3803. if (split) {
  3804. for (var i = split.length - 1; i >= 0; --i)
  3805. makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
  3806. } else {
  3807. makeChangeInner(doc, change);
  3808. }
  3809. }
  3810. function makeChangeInner(doc, change) {
  3811. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
  3812. var selAfter = computeSelAfterChange(doc, change);
  3813. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  3814. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  3815. var rebased = [];
  3816. linkedDocs(doc, function(doc, sharedHist) {
  3817. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  3818. rebaseHist(doc.history, change);
  3819. rebased.push(doc.history);
  3820. }
  3821. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  3822. });
  3823. }
  3824. // Revert a change stored in a document's history.
  3825. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  3826. if (doc.cm && doc.cm.state.suppressEdits) return;
  3827. var hist = doc.history, event, selAfter = doc.sel;
  3828. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  3829. // Verify that there is a useable event (so that ctrl-z won't
  3830. // needlessly clear selection events)
  3831. for (var i = 0; i < source.length; i++) {
  3832. event = source[i];
  3833. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  3834. break;
  3835. }
  3836. if (i == source.length) return;
  3837. hist.lastOrigin = hist.lastSelOrigin = null;
  3838. for (;;) {
  3839. event = source.pop();
  3840. if (event.ranges) {
  3841. pushSelectionToHistory(event, dest);
  3842. if (allowSelectionOnly && !event.equals(doc.sel)) {
  3843. setSelection(doc, event, {clearRedo: false});
  3844. return;
  3845. }
  3846. selAfter = event;
  3847. }
  3848. else break;
  3849. }
  3850. // Build up a reverse change object to add to the opposite history
  3851. // stack (redo when undoing, and vice versa).
  3852. var antiChanges = [];
  3853. pushSelectionToHistory(selAfter, dest);
  3854. dest.push({changes: antiChanges, generation: hist.generation});
  3855. hist.generation = event.generation || ++hist.maxGeneration;
  3856. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  3857. for (var i = event.changes.length - 1; i >= 0; --i) {
  3858. var change = event.changes[i];
  3859. change.origin = type;
  3860. if (filter && !filterChange(doc, change, false)) {
  3861. source.length = 0;
  3862. return;
  3863. }
  3864. antiChanges.push(historyChangeFromChange(doc, change));
  3865. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  3866. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  3867. if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
  3868. var rebased = [];
  3869. // Propagate to the linked documents
  3870. linkedDocs(doc, function(doc, sharedHist) {
  3871. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  3872. rebaseHist(doc.history, change);
  3873. rebased.push(doc.history);
  3874. }
  3875. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  3876. });
  3877. }
  3878. }
  3879. // Sub-views need their line numbers shifted when text is added
  3880. // above or below them in the parent document.
  3881. function shiftDoc(doc, distance) {
  3882. if (distance == 0) return;
  3883. doc.first += distance;
  3884. doc.sel = new Selection(map(doc.sel.ranges, function(range) {
  3885. return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
  3886. Pos(range.head.line + distance, range.head.ch));
  3887. }), doc.sel.primIndex);
  3888. if (doc.cm) {
  3889. regChange(doc.cm, doc.first, doc.first - distance, distance);
  3890. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  3891. regLineChange(doc.cm, l, "gutter");
  3892. }
  3893. }
  3894. // More lower-level change function, handling only a single document
  3895. // (not linked ones).
  3896. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  3897. if (doc.cm && !doc.cm.curOp)
  3898. return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
  3899. if (change.to.line < doc.first) {
  3900. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  3901. return;
  3902. }
  3903. if (change.from.line > doc.lastLine()) return;
  3904. // Clip the change to the size of this doc
  3905. if (change.from.line < doc.first) {
  3906. var shift = change.text.length - 1 - (doc.first - change.from.line);
  3907. shiftDoc(doc, shift);
  3908. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  3909. text: [lst(change.text)], origin: change.origin};
  3910. }
  3911. var last = doc.lastLine();
  3912. if (change.to.line > last) {
  3913. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  3914. text: [change.text[0]], origin: change.origin};
  3915. }
  3916. change.removed = getBetween(doc, change.from, change.to);
  3917. if (!selAfter) selAfter = computeSelAfterChange(doc, change);
  3918. if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
  3919. else updateDoc(doc, change, spans);
  3920. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  3921. }
  3922. // Handle the interaction of a change to a document with the editor
  3923. // that this document is part of.
  3924. function makeChangeSingleDocInEditor(cm, change, spans) {
  3925. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  3926. var recomputeMaxLength = false, checkWidthStart = from.line;
  3927. if (!cm.options.lineWrapping) {
  3928. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  3929. doc.iter(checkWidthStart, to.line + 1, function(line) {
  3930. if (line == display.maxLine) {
  3931. recomputeMaxLength = true;
  3932. return true;
  3933. }
  3934. });
  3935. }
  3936. if (doc.sel.contains(change.from, change.to) > -1)
  3937. signalCursorActivity(cm);
  3938. updateDoc(doc, change, spans, estimateHeight(cm));
  3939. if (!cm.options.lineWrapping) {
  3940. doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
  3941. var len = lineLength(line);
  3942. if (len > display.maxLineLength) {
  3943. display.maxLine = line;
  3944. display.maxLineLength = len;
  3945. display.maxLineChanged = true;
  3946. recomputeMaxLength = false;
  3947. }
  3948. });
  3949. if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
  3950. }
  3951. // Adjust frontier, schedule worker
  3952. doc.frontier = Math.min(doc.frontier, from.line);
  3953. startWorker(cm, 400);
  3954. var lendiff = change.text.length - (to.line - from.line) - 1;
  3955. // Remember that these lines changed, for updating the display
  3956. if (change.full)
  3957. regChange(cm);
  3958. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  3959. regLineChange(cm, from.line, "text");
  3960. else
  3961. regChange(cm, from.line, to.line + 1, lendiff);
  3962. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  3963. if (changeHandler || changesHandler) {
  3964. var obj = {
  3965. from: from, to: to,
  3966. text: change.text,
  3967. removed: change.removed,
  3968. origin: change.origin
  3969. };
  3970. if (changeHandler) signalLater(cm, "change", cm, obj);
  3971. if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
  3972. }
  3973. cm.display.selForContextMenu = null;
  3974. }
  3975. function replaceRange(doc, code, from, to, origin) {
  3976. if (!to) to = from;
  3977. if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
  3978. if (typeof code == "string") code = splitLines(code);
  3979. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  3980. }
  3981. // SCROLLING THINGS INTO VIEW
  3982. // If an editor sits on the top or bottom of the window, partially
  3983. // scrolled out of view, this ensures that the cursor is visible.
  3984. function maybeScrollWindow(cm, coords) {
  3985. if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
  3986. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  3987. if (coords.top + box.top < 0) doScroll = true;
  3988. else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
  3989. if (doScroll != null && !phantom) {
  3990. var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
  3991. (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
  3992. (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
  3993. coords.left + "px; width: 2px;");
  3994. cm.display.lineSpace.appendChild(scrollNode);
  3995. scrollNode.scrollIntoView(doScroll);
  3996. cm.display.lineSpace.removeChild(scrollNode);
  3997. }
  3998. }
  3999. // Scroll a given position into view (immediately), verifying that
  4000. // it actually became visible (as line heights are accurately
  4001. // measured, the position of something may 'drift' during drawing).
  4002. function scrollPosIntoView(cm, pos, end, margin) {
  4003. if (margin == null) margin = 0;
  4004. for (var limit = 0; limit < 5; limit++) {
  4005. var changed = false, coords = cursorCoords(cm, pos);
  4006. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  4007. var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
  4008. Math.min(coords.top, endCoords.top) - margin,
  4009. Math.max(coords.left, endCoords.left),
  4010. Math.max(coords.bottom, endCoords.bottom) + margin);
  4011. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  4012. if (scrollPos.scrollTop != null) {
  4013. setScrollTop(cm, scrollPos.scrollTop);
  4014. if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
  4015. }
  4016. if (scrollPos.scrollLeft != null) {
  4017. setScrollLeft(cm, scrollPos.scrollLeft);
  4018. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
  4019. }
  4020. if (!changed) break;
  4021. }
  4022. return coords;
  4023. }
  4024. // Scroll a given set of coordinates into view (immediately).
  4025. function scrollIntoView(cm, x1, y1, x2, y2) {
  4026. var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
  4027. if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
  4028. if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
  4029. }
  4030. // Calculate a new scroll position needed to scroll the given
  4031. // rectangle into view. Returns an object with scrollTop and
  4032. // scrollLeft properties. When these are undefined, the
  4033. // vertical/horizontal position does not need to be adjusted.
  4034. function calculateScrollPos(cm, x1, y1, x2, y2) {
  4035. var display = cm.display, snapMargin = textHeight(cm.display);
  4036. if (y1 < 0) y1 = 0;
  4037. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  4038. var screen = displayHeight(cm), result = {};
  4039. if (y2 - y1 > screen) y2 = y1 + screen;
  4040. var docBottom = cm.doc.height + paddingVert(display);
  4041. var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
  4042. if (y1 < screentop) {
  4043. result.scrollTop = atTop ? 0 : y1;
  4044. } else if (y2 > screentop + screen) {
  4045. var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
  4046. if (newTop != screentop) result.scrollTop = newTop;
  4047. }
  4048. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  4049. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  4050. var tooWide = x2 - x1 > screenw;
  4051. if (tooWide) x2 = x1 + screenw;
  4052. if (x1 < 10)
  4053. result.scrollLeft = 0;
  4054. else if (x1 < screenleft)
  4055. result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
  4056. else if (x2 > screenw + screenleft - 3)
  4057. result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
  4058. return result;
  4059. }
  4060. // Store a relative adjustment to the scroll position in the current
  4061. // operation (to be applied when the operation finishes).
  4062. function addToScrollPos(cm, left, top) {
  4063. if (left != null || top != null) resolveScrollToPos(cm);
  4064. if (left != null)
  4065. cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
  4066. if (top != null)
  4067. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  4068. }
  4069. // Make sure that at the end of the operation the current cursor is
  4070. // shown.
  4071. function ensureCursorVisible(cm) {
  4072. resolveScrollToPos(cm);
  4073. var cur = cm.getCursor(), from = cur, to = cur;
  4074. if (!cm.options.lineWrapping) {
  4075. from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
  4076. to = Pos(cur.line, cur.ch + 1);
  4077. }
  4078. cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
  4079. }
  4080. // When an operation has its scrollToPos property set, and another
  4081. // scroll action is applied before the end of the operation, this
  4082. // 'simulates' scrolling that position into view in a cheap way, so
  4083. // that the effect of intermediate scroll commands is not ignored.
  4084. function resolveScrollToPos(cm) {
  4085. var range = cm.curOp.scrollToPos;
  4086. if (range) {
  4087. cm.curOp.scrollToPos = null;
  4088. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  4089. var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
  4090. Math.min(from.top, to.top) - range.margin,
  4091. Math.max(from.right, to.right),
  4092. Math.max(from.bottom, to.bottom) + range.margin);
  4093. cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  4094. }
  4095. }
  4096. // API UTILITIES
  4097. // Indent the given line. The how parameter can be "smart",
  4098. // "add"/null, "subtract", or "prev". When aggressive is false
  4099. // (typically set to true for forced single-line indents), empty
  4100. // lines are not indented, and places where the mode returns Pass
  4101. // are left alone.
  4102. function indentLine(cm, n, how, aggressive) {
  4103. var doc = cm.doc, state;
  4104. if (how == null) how = "add";
  4105. if (how == "smart") {
  4106. // Fall back to "prev" when the mode doesn't have an indentation
  4107. // method.
  4108. if (!doc.mode.indent) how = "prev";
  4109. else state = getStateBefore(cm, n);
  4110. }
  4111. var tabSize = cm.options.tabSize;
  4112. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  4113. if (line.stateAfter) line.stateAfter = null;
  4114. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  4115. if (!aggressive && !/\S/.test(line.text)) {
  4116. indentation = 0;
  4117. how = "not";
  4118. } else if (how == "smart") {
  4119. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  4120. if (indentation == Pass || indentation > 150) {
  4121. if (!aggressive) return;
  4122. how = "prev";
  4123. }
  4124. }
  4125. if (how == "prev") {
  4126. if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
  4127. else indentation = 0;
  4128. } else if (how == "add") {
  4129. indentation = curSpace + cm.options.indentUnit;
  4130. } else if (how == "subtract") {
  4131. indentation = curSpace - cm.options.indentUnit;
  4132. } else if (typeof how == "number") {
  4133. indentation = curSpace + how;
  4134. }
  4135. indentation = Math.max(0, indentation);
  4136. var indentString = "", pos = 0;
  4137. if (cm.options.indentWithTabs)
  4138. for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
  4139. if (pos < indentation) indentString += spaceStr(indentation - pos);
  4140. if (indentString != curSpaceString) {
  4141. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  4142. } else {
  4143. // Ensure that, if the cursor was in the whitespace at the start
  4144. // of the line, it is moved to the end of that space.
  4145. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4146. var range = doc.sel.ranges[i];
  4147. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  4148. var pos = Pos(n, curSpaceString.length);
  4149. replaceOneSelection(doc, i, new Range(pos, pos));
  4150. break;
  4151. }
  4152. }
  4153. }
  4154. line.stateAfter = null;
  4155. }
  4156. // Utility for applying a change to a line by handle or number,
  4157. // returning the number and optionally registering the line as
  4158. // changed.
  4159. function changeLine(doc, handle, changeType, op) {
  4160. var no = handle, line = handle;
  4161. if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
  4162. else no = lineNo(handle);
  4163. if (no == null) return null;
  4164. if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
  4165. return line;
  4166. }
  4167. // Helper for deleting text near the selection(s), used to implement
  4168. // backspace, delete, and similar functionality.
  4169. function deleteNearSelection(cm, compute) {
  4170. var ranges = cm.doc.sel.ranges, kill = [];
  4171. // Build up a set of ranges to kill first, merging overlapping
  4172. // ranges.
  4173. for (var i = 0; i < ranges.length; i++) {
  4174. var toKill = compute(ranges[i]);
  4175. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  4176. var replaced = kill.pop();
  4177. if (cmp(replaced.from, toKill.from) < 0) {
  4178. toKill.from = replaced.from;
  4179. break;
  4180. }
  4181. }
  4182. kill.push(toKill);
  4183. }
  4184. // Next, remove those actual ranges.
  4185. runInOp(cm, function() {
  4186. for (var i = kill.length - 1; i >= 0; i--)
  4187. replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
  4188. ensureCursorVisible(cm);
  4189. });
  4190. }
  4191. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  4192. // right), unit can be "char", "column" (like char, but doesn't
  4193. // cross line boundaries), "word" (across next word), or "group" (to
  4194. // the start of next group of word or non-word-non-whitespace
  4195. // chars). The visually param controls whether, in right-to-left
  4196. // text, direction 1 means to move towards the next index in the
  4197. // string, or towards the character to the right of the current
  4198. // position. The resulting position will have a hitSide=true
  4199. // property if it reached the end of the document.
  4200. function findPosH(doc, pos, dir, unit, visually) {
  4201. var line = pos.line, ch = pos.ch, origDir = dir;
  4202. var lineObj = getLine(doc, line);
  4203. var possible = true;
  4204. function findNextLine() {
  4205. var l = line + dir;
  4206. if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
  4207. line = l;
  4208. return lineObj = getLine(doc, l);
  4209. }
  4210. function moveOnce(boundToLine) {
  4211. var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
  4212. if (next == null) {
  4213. if (!boundToLine && findNextLine()) {
  4214. if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
  4215. else ch = dir < 0 ? lineObj.text.length : 0;
  4216. } else return (possible = false);
  4217. } else ch = next;
  4218. return true;
  4219. }
  4220. if (unit == "char") moveOnce();
  4221. else if (unit == "column") moveOnce(true);
  4222. else if (unit == "word" || unit == "group") {
  4223. var sawType = null, group = unit == "group";
  4224. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  4225. for (var first = true;; first = false) {
  4226. if (dir < 0 && !moveOnce(!first)) break;
  4227. var cur = lineObj.text.charAt(ch) || "\n";
  4228. var type = isWordChar(cur, helper) ? "w"
  4229. : group && cur == "\n" ? "n"
  4230. : !group || /\s/.test(cur) ? null
  4231. : "p";
  4232. if (group && !first && !type) type = "s";
  4233. if (sawType && sawType != type) {
  4234. if (dir < 0) {dir = 1; moveOnce();}
  4235. break;
  4236. }
  4237. if (type) sawType = type;
  4238. if (dir > 0 && !moveOnce(!first)) break;
  4239. }
  4240. }
  4241. var result = skipAtomic(doc, Pos(line, ch), origDir, true);
  4242. if (!possible) result.hitSide = true;
  4243. return result;
  4244. }
  4245. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  4246. // "page" or "line". The resulting position will have a hitSide=true
  4247. // property if it reached the end of the document.
  4248. function findPosV(cm, pos, dir, unit) {
  4249. var doc = cm.doc, x = pos.left, y;
  4250. if (unit == "page") {
  4251. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  4252. y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
  4253. } else if (unit == "line") {
  4254. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  4255. }
  4256. for (;;) {
  4257. var target = coordsChar(cm, x, y);
  4258. if (!target.outside) break;
  4259. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
  4260. y += dir * 5;
  4261. }
  4262. return target;
  4263. }
  4264. // EDITOR METHODS
  4265. // The publicly visible API. Note that methodOp(f) means
  4266. // 'wrap f in an operation, performed on its `this` parameter'.
  4267. // This is not the complete set of editor methods. Most of the
  4268. // methods defined on the Doc type are also injected into
  4269. // CodeMirror.prototype, for backwards compatibility and
  4270. // convenience.
  4271. CodeMirror.prototype = {
  4272. constructor: CodeMirror,
  4273. focus: function(){window.focus(); this.display.input.focus();},
  4274. setOption: function(option, value) {
  4275. var options = this.options, old = options[option];
  4276. if (options[option] == value && option != "mode") return;
  4277. options[option] = value;
  4278. if (optionHandlers.hasOwnProperty(option))
  4279. operation(this, optionHandlers[option])(this, value, old);
  4280. },
  4281. getOption: function(option) {return this.options[option];},
  4282. getDoc: function() {return this.doc;},
  4283. addKeyMap: function(map, bottom) {
  4284. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  4285. },
  4286. removeKeyMap: function(map) {
  4287. var maps = this.state.keyMaps;
  4288. for (var i = 0; i < maps.length; ++i)
  4289. if (maps[i] == map || maps[i].name == map) {
  4290. maps.splice(i, 1);
  4291. return true;
  4292. }
  4293. },
  4294. addOverlay: methodOp(function(spec, options) {
  4295. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  4296. if (mode.startState) throw new Error("Overlays may not be stateful.");
  4297. this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
  4298. this.state.modeGen++;
  4299. regChange(this);
  4300. }),
  4301. removeOverlay: methodOp(function(spec) {
  4302. var overlays = this.state.overlays;
  4303. for (var i = 0; i < overlays.length; ++i) {
  4304. var cur = overlays[i].modeSpec;
  4305. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  4306. overlays.splice(i, 1);
  4307. this.state.modeGen++;
  4308. regChange(this);
  4309. return;
  4310. }
  4311. }
  4312. }),
  4313. indentLine: methodOp(function(n, dir, aggressive) {
  4314. if (typeof dir != "string" && typeof dir != "number") {
  4315. if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
  4316. else dir = dir ? "add" : "subtract";
  4317. }
  4318. if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
  4319. }),
  4320. indentSelection: methodOp(function(how) {
  4321. var ranges = this.doc.sel.ranges, end = -1;
  4322. for (var i = 0; i < ranges.length; i++) {
  4323. var range = ranges[i];
  4324. if (!range.empty()) {
  4325. var from = range.from(), to = range.to();
  4326. var start = Math.max(end, from.line);
  4327. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  4328. for (var j = start; j < end; ++j)
  4329. indentLine(this, j, how);
  4330. var newRanges = this.doc.sel.ranges;
  4331. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  4332. replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
  4333. } else if (range.head.line > end) {
  4334. indentLine(this, range.head.line, how, true);
  4335. end = range.head.line;
  4336. if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
  4337. }
  4338. }
  4339. }),
  4340. // Fetch the parser token for a given character. Useful for hacks
  4341. // that want to inspect the mode state (say, for completion).
  4342. getTokenAt: function(pos, precise) {
  4343. return takeToken(this, pos, precise);
  4344. },
  4345. getLineTokens: function(line, precise) {
  4346. return takeToken(this, Pos(line), precise, true);
  4347. },
  4348. getTokenTypeAt: function(pos) {
  4349. pos = clipPos(this.doc, pos);
  4350. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  4351. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  4352. var type;
  4353. if (ch == 0) type = styles[2];
  4354. else for (;;) {
  4355. var mid = (before + after) >> 1;
  4356. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
  4357. else if (styles[mid * 2 + 1] < ch) before = mid + 1;
  4358. else { type = styles[mid * 2 + 2]; break; }
  4359. }
  4360. var cut = type ? type.indexOf("cm-overlay ") : -1;
  4361. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
  4362. },
  4363. getModeAt: function(pos) {
  4364. var mode = this.doc.mode;
  4365. if (!mode.innerMode) return mode;
  4366. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
  4367. },
  4368. getHelper: function(pos, type) {
  4369. return this.getHelpers(pos, type)[0];
  4370. },
  4371. getHelpers: function(pos, type) {
  4372. var found = [];
  4373. if (!helpers.hasOwnProperty(type)) return found;
  4374. var help = helpers[type], mode = this.getModeAt(pos);
  4375. if (typeof mode[type] == "string") {
  4376. if (help[mode[type]]) found.push(help[mode[type]]);
  4377. } else if (mode[type]) {
  4378. for (var i = 0; i < mode[type].length; i++) {
  4379. var val = help[mode[type][i]];
  4380. if (val) found.push(val);
  4381. }
  4382. } else if (mode.helperType && help[mode.helperType]) {
  4383. found.push(help[mode.helperType]);
  4384. } else if (help[mode.name]) {
  4385. found.push(help[mode.name]);
  4386. }
  4387. for (var i = 0; i < help._global.length; i++) {
  4388. var cur = help._global[i];
  4389. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  4390. found.push(cur.val);
  4391. }
  4392. return found;
  4393. },
  4394. getStateAfter: function(line, precise) {
  4395. var doc = this.doc;
  4396. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  4397. return getStateBefore(this, line + 1, precise);
  4398. },
  4399. cursorCoords: function(start, mode) {
  4400. var pos, range = this.doc.sel.primary();
  4401. if (start == null) pos = range.head;
  4402. else if (typeof start == "object") pos = clipPos(this.doc, start);
  4403. else pos = start ? range.from() : range.to();
  4404. return cursorCoords(this, pos, mode || "page");
  4405. },
  4406. charCoords: function(pos, mode) {
  4407. return charCoords(this, clipPos(this.doc, pos), mode || "page");
  4408. },
  4409. coordsChar: function(coords, mode) {
  4410. coords = fromCoordSystem(this, coords, mode || "page");
  4411. return coordsChar(this, coords.left, coords.top);
  4412. },
  4413. lineAtHeight: function(height, mode) {
  4414. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  4415. return lineAtHeight(this.doc, height + this.display.viewOffset);
  4416. },
  4417. heightAtLine: function(line, mode) {
  4418. var end = false, last = this.doc.first + this.doc.size - 1;
  4419. if (line < this.doc.first) line = this.doc.first;
  4420. else if (line > last) { line = last; end = true; }
  4421. var lineObj = getLine(this.doc, line);
  4422. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
  4423. (end ? this.doc.height - heightAtLine(lineObj) : 0);
  4424. },
  4425. defaultTextHeight: function() { return textHeight(this.display); },
  4426. defaultCharWidth: function() { return charWidth(this.display); },
  4427. setGutterMarker: methodOp(function(line, gutterID, value) {
  4428. return changeLine(this.doc, line, "gutter", function(line) {
  4429. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  4430. markers[gutterID] = value;
  4431. if (!value && isEmpty(markers)) line.gutterMarkers = null;
  4432. return true;
  4433. });
  4434. }),
  4435. clearGutter: methodOp(function(gutterID) {
  4436. var cm = this, doc = cm.doc, i = doc.first;
  4437. doc.iter(function(line) {
  4438. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  4439. line.gutterMarkers[gutterID] = null;
  4440. regLineChange(cm, i, "gutter");
  4441. if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
  4442. }
  4443. ++i;
  4444. });
  4445. }),
  4446. lineInfo: function(line) {
  4447. if (typeof line == "number") {
  4448. if (!isLine(this.doc, line)) return null;
  4449. var n = line;
  4450. line = getLine(this.doc, line);
  4451. if (!line) return null;
  4452. } else {
  4453. var n = lineNo(line);
  4454. if (n == null) return null;
  4455. }
  4456. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  4457. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  4458. widgets: line.widgets};
  4459. },
  4460. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
  4461. addWidget: function(pos, node, scroll, vert, horiz) {
  4462. var display = this.display;
  4463. pos = cursorCoords(this, clipPos(this.doc, pos));
  4464. var top = pos.bottom, left = pos.left;
  4465. node.style.position = "absolute";
  4466. node.setAttribute("cm-ignore-events", "true");
  4467. this.display.input.setUneditable(node);
  4468. display.sizer.appendChild(node);
  4469. if (vert == "over") {
  4470. top = pos.top;
  4471. } else if (vert == "above" || vert == "near") {
  4472. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  4473. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  4474. // Default to positioning above (if specified and possible); otherwise default to positioning below
  4475. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  4476. top = pos.top - node.offsetHeight;
  4477. else if (pos.bottom + node.offsetHeight <= vspace)
  4478. top = pos.bottom;
  4479. if (left + node.offsetWidth > hspace)
  4480. left = hspace - node.offsetWidth;
  4481. }
  4482. node.style.top = top + "px";
  4483. node.style.left = node.style.right = "";
  4484. if (horiz == "right") {
  4485. left = display.sizer.clientWidth - node.offsetWidth;
  4486. node.style.right = "0px";
  4487. } else {
  4488. if (horiz == "left") left = 0;
  4489. else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
  4490. node.style.left = left + "px";
  4491. }
  4492. if (scroll)
  4493. scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
  4494. },
  4495. triggerOnKeyDown: methodOp(onKeyDown),
  4496. triggerOnKeyPress: methodOp(onKeyPress),
  4497. triggerOnKeyUp: onKeyUp,
  4498. execCommand: function(cmd) {
  4499. if (commands.hasOwnProperty(cmd))
  4500. return commands[cmd](this);
  4501. },
  4502. findPosH: function(from, amount, unit, visually) {
  4503. var dir = 1;
  4504. if (amount < 0) { dir = -1; amount = -amount; }
  4505. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  4506. cur = findPosH(this.doc, cur, dir, unit, visually);
  4507. if (cur.hitSide) break;
  4508. }
  4509. return cur;
  4510. },
  4511. moveH: methodOp(function(dir, unit) {
  4512. var cm = this;
  4513. cm.extendSelectionsBy(function(range) {
  4514. if (cm.display.shift || cm.doc.extend || range.empty())
  4515. return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
  4516. else
  4517. return dir < 0 ? range.from() : range.to();
  4518. }, sel_move);
  4519. }),
  4520. deleteH: methodOp(function(dir, unit) {
  4521. var sel = this.doc.sel, doc = this.doc;
  4522. if (sel.somethingSelected())
  4523. doc.replaceSelection("", null, "+delete");
  4524. else
  4525. deleteNearSelection(this, function(range) {
  4526. var other = findPosH(doc, range.head, dir, unit, false);
  4527. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
  4528. });
  4529. }),
  4530. findPosV: function(from, amount, unit, goalColumn) {
  4531. var dir = 1, x = goalColumn;
  4532. if (amount < 0) { dir = -1; amount = -amount; }
  4533. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  4534. var coords = cursorCoords(this, cur, "div");
  4535. if (x == null) x = coords.left;
  4536. else coords.left = x;
  4537. cur = findPosV(this, coords, dir, unit);
  4538. if (cur.hitSide) break;
  4539. }
  4540. return cur;
  4541. },
  4542. moveV: methodOp(function(dir, unit) {
  4543. var cm = this, doc = this.doc, goals = [];
  4544. var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
  4545. doc.extendSelectionsBy(function(range) {
  4546. if (collapse)
  4547. return dir < 0 ? range.from() : range.to();
  4548. var headPos = cursorCoords(cm, range.head, "div");
  4549. if (range.goalColumn != null) headPos.left = range.goalColumn;
  4550. goals.push(headPos.left);
  4551. var pos = findPosV(cm, headPos, dir, unit);
  4552. if (unit == "page" && range == doc.sel.primary())
  4553. addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
  4554. return pos;
  4555. }, sel_move);
  4556. if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
  4557. doc.sel.ranges[i].goalColumn = goals[i];
  4558. }),
  4559. // Find the word at the given position (as returned by coordsChar).
  4560. findWordAt: function(pos) {
  4561. var doc = this.doc, line = getLine(doc, pos.line).text;
  4562. var start = pos.ch, end = pos.ch;
  4563. if (line) {
  4564. var helper = this.getHelper(pos, "wordChars");
  4565. if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
  4566. var startChar = line.charAt(start);
  4567. var check = isWordChar(startChar, helper)
  4568. ? function(ch) { return isWordChar(ch, helper); }
  4569. : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
  4570. : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
  4571. while (start > 0 && check(line.charAt(start - 1))) --start;
  4572. while (end < line.length && check(line.charAt(end))) ++end;
  4573. }
  4574. return new Range(Pos(pos.line, start), Pos(pos.line, end));
  4575. },
  4576. toggleOverwrite: function(value) {
  4577. if (value != null && value == this.state.overwrite) return;
  4578. if (this.state.overwrite = !this.state.overwrite)
  4579. addClass(this.display.cursorDiv, "CodeMirror-overwrite");
  4580. else
  4581. rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
  4582. signal(this, "overwriteToggle", this, this.state.overwrite);
  4583. },
  4584. hasFocus: function() { return this.display.input.getField() == activeElt(); },
  4585. scrollTo: methodOp(function(x, y) {
  4586. if (x != null || y != null) resolveScrollToPos(this);
  4587. if (x != null) this.curOp.scrollLeft = x;
  4588. if (y != null) this.curOp.scrollTop = y;
  4589. }),
  4590. getScrollInfo: function() {
  4591. var scroller = this.display.scroller;
  4592. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  4593. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  4594. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  4595. clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
  4596. },
  4597. scrollIntoView: methodOp(function(range, margin) {
  4598. if (range == null) {
  4599. range = {from: this.doc.sel.primary().head, to: null};
  4600. if (margin == null) margin = this.options.cursorScrollMargin;
  4601. } else if (typeof range == "number") {
  4602. range = {from: Pos(range, 0), to: null};
  4603. } else if (range.from == null) {
  4604. range = {from: range, to: null};
  4605. }
  4606. if (!range.to) range.to = range.from;
  4607. range.margin = margin || 0;
  4608. if (range.from.line != null) {
  4609. resolveScrollToPos(this);
  4610. this.curOp.scrollToPos = range;
  4611. } else {
  4612. var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
  4613. Math.min(range.from.top, range.to.top) - range.margin,
  4614. Math.max(range.from.right, range.to.right),
  4615. Math.max(range.from.bottom, range.to.bottom) + range.margin);
  4616. this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  4617. }
  4618. }),
  4619. setSize: methodOp(function(width, height) {
  4620. var cm = this;
  4621. function interpret(val) {
  4622. return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
  4623. }
  4624. if (width != null) cm.display.wrapper.style.width = interpret(width);
  4625. if (height != null) cm.display.wrapper.style.height = interpret(height);
  4626. if (cm.options.lineWrapping) clearLineMeasurementCache(this);
  4627. var lineNo = cm.display.viewFrom;
  4628. cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
  4629. if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
  4630. if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
  4631. ++lineNo;
  4632. });
  4633. cm.curOp.forceUpdate = true;
  4634. signal(cm, "refresh", this);
  4635. }),
  4636. operation: function(f){return runInOp(this, f);},
  4637. refresh: methodOp(function() {
  4638. var oldHeight = this.display.cachedTextHeight;
  4639. regChange(this);
  4640. this.curOp.forceUpdate = true;
  4641. clearCaches(this);
  4642. this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
  4643. updateGutterSpace(this);
  4644. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  4645. estimateLineHeights(this);
  4646. signal(this, "refresh", this);
  4647. }),
  4648. swapDoc: methodOp(function(doc) {
  4649. var old = this.doc;
  4650. old.cm = null;
  4651. attachDoc(this, doc);
  4652. clearCaches(this);
  4653. this.display.input.reset();
  4654. this.scrollTo(doc.scrollLeft, doc.scrollTop);
  4655. this.curOp.forceScroll = true;
  4656. signalLater(this, "swapDoc", this, old);
  4657. return old;
  4658. }),
  4659. getInputField: function(){return this.display.input.getField();},
  4660. getWrapperElement: function(){return this.display.wrapper;},
  4661. getScrollerElement: function(){return this.display.scroller;},
  4662. getGutterElement: function(){return this.display.gutters;}
  4663. };
  4664. eventMixin(CodeMirror);
  4665. // OPTION DEFAULTS
  4666. // The default configuration options.
  4667. var defaults = CodeMirror.defaults = {};
  4668. // Functions to run when options are changed.
  4669. var optionHandlers = CodeMirror.optionHandlers = {};
  4670. function option(name, deflt, handle, notOnInit) {
  4671. CodeMirror.defaults[name] = deflt;
  4672. if (handle) optionHandlers[name] =
  4673. notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
  4674. }
  4675. // Passed to option handlers when there is no old value.
  4676. var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
  4677. // These two are, on init, called from the constructor because they
  4678. // have to be initialized before the editor can start at all.
  4679. option("value", "", function(cm, val) {
  4680. cm.setValue(val);
  4681. }, true);
  4682. option("mode", null, function(cm, val) {
  4683. cm.doc.modeOption = val;
  4684. loadMode(cm);
  4685. }, true);
  4686. option("indentUnit", 2, loadMode, true);
  4687. option("indentWithTabs", false);
  4688. option("smartIndent", true);
  4689. option("tabSize", 4, function(cm) {
  4690. resetModeState(cm);
  4691. clearCaches(cm);
  4692. regChange(cm);
  4693. }, true);
  4694. option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
  4695. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  4696. if (old != CodeMirror.Init) cm.refresh();
  4697. });
  4698. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
  4699. option("electricChars", true);
  4700. option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
  4701. throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
  4702. }, true);
  4703. option("rtlMoveVisually", !windows);
  4704. option("wholeLineUpdateBefore", true);
  4705. option("theme", "default", function(cm) {
  4706. themeChanged(cm);
  4707. guttersChanged(cm);
  4708. }, true);
  4709. option("keyMap", "default", function(cm, val, old) {
  4710. var next = getKeyMap(val);
  4711. var prev = old != CodeMirror.Init && getKeyMap(old);
  4712. if (prev && prev.detach) prev.detach(cm, next);
  4713. if (next.attach) next.attach(cm, prev || null);
  4714. });
  4715. option("extraKeys", null);
  4716. option("lineWrapping", false, wrappingChanged, true);
  4717. option("gutters", [], function(cm) {
  4718. setGuttersForLineNumbers(cm.options);
  4719. guttersChanged(cm);
  4720. }, true);
  4721. option("fixedGutter", true, function(cm, val) {
  4722. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  4723. cm.refresh();
  4724. }, true);
  4725. option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
  4726. option("scrollbarStyle", "native", function(cm) {
  4727. initScrollbars(cm);
  4728. updateScrollbars(cm);
  4729. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  4730. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  4731. }, true);
  4732. option("lineNumbers", false, function(cm) {
  4733. setGuttersForLineNumbers(cm.options);
  4734. guttersChanged(cm);
  4735. }, true);
  4736. option("firstLineNumber", 1, guttersChanged, true);
  4737. option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
  4738. option("showCursorWhenSelecting", false, updateSelection, true);
  4739. option("resetSelectionOnContextMenu", true);
  4740. option("readOnly", false, function(cm, val) {
  4741. if (val == "nocursor") {
  4742. onBlur(cm);
  4743. cm.display.input.blur();
  4744. cm.display.disabled = true;
  4745. } else {
  4746. cm.display.disabled = false;
  4747. if (!val) cm.display.input.reset();
  4748. }
  4749. });
  4750. option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
  4751. option("dragDrop", true);
  4752. option("cursorBlinkRate", 530);
  4753. option("cursorScrollMargin", 0);
  4754. option("cursorHeight", 1, updateSelection, true);
  4755. option("singleCursorHeightPerLine", true, updateSelection, true);
  4756. option("workTime", 100);
  4757. option("workDelay", 100);
  4758. option("flattenSpans", true, resetModeState, true);
  4759. option("addModeClass", false, resetModeState, true);
  4760. option("pollInterval", 100);
  4761. option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
  4762. option("historyEventDelay", 1250);
  4763. option("viewportMargin", 10, function(cm){cm.refresh();}, true);
  4764. option("maxHighlightLength", 10000, resetModeState, true);
  4765. option("moveInputWithCursor", true, function(cm, val) {
  4766. if (!val) cm.display.input.resetPosition();
  4767. });
  4768. option("tabindex", null, function(cm, val) {
  4769. cm.display.input.getField().tabIndex = val || "";
  4770. });
  4771. option("autofocus", null);
  4772. // MODE DEFINITION AND QUERYING
  4773. // Known modes, by name and by MIME
  4774. var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
  4775. // Extra arguments are stored as the mode's dependencies, which is
  4776. // used by (legacy) mechanisms like loadmode.js to automatically
  4777. // load a mode. (Preferred mechanism is the require/define calls.)
  4778. CodeMirror.defineMode = function(name, mode) {
  4779. if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
  4780. if (arguments.length > 2)
  4781. mode.dependencies = Array.prototype.slice.call(arguments, 2);
  4782. modes[name] = mode;
  4783. };
  4784. CodeMirror.defineMIME = function(mime, spec) {
  4785. mimeModes[mime] = spec;
  4786. };
  4787. // Given a MIME type, a {name, ...options} config object, or a name
  4788. // string, return a mode config object.
  4789. CodeMirror.resolveMode = function(spec) {
  4790. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  4791. spec = mimeModes[spec];
  4792. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  4793. var found = mimeModes[spec.name];
  4794. if (typeof found == "string") found = {name: found};
  4795. spec = createObj(found, spec);
  4796. spec.name = found.name;
  4797. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  4798. return CodeMirror.resolveMode("application/xml");
  4799. }
  4800. if (typeof spec == "string") return {name: spec};
  4801. else return spec || {name: "null"};
  4802. };
  4803. // Given a mode spec (anything that resolveMode accepts), find and
  4804. // initialize an actual mode object.
  4805. CodeMirror.getMode = function(options, spec) {
  4806. var spec = CodeMirror.resolveMode(spec);
  4807. var mfactory = modes[spec.name];
  4808. if (!mfactory) return CodeMirror.getMode(options, "text/plain");
  4809. var modeObj = mfactory(options, spec);
  4810. if (modeExtensions.hasOwnProperty(spec.name)) {
  4811. var exts = modeExtensions[spec.name];
  4812. for (var prop in exts) {
  4813. if (!exts.hasOwnProperty(prop)) continue;
  4814. if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
  4815. modeObj[prop] = exts[prop];
  4816. }
  4817. }
  4818. modeObj.name = spec.name;
  4819. if (spec.helperType) modeObj.helperType = spec.helperType;
  4820. if (spec.modeProps) for (var prop in spec.modeProps)
  4821. modeObj[prop] = spec.modeProps[prop];
  4822. return modeObj;
  4823. };
  4824. // Minimal default mode.
  4825. CodeMirror.defineMode("null", function() {
  4826. return {token: function(stream) {stream.skipToEnd();}};
  4827. });
  4828. CodeMirror.defineMIME("text/plain", "null");
  4829. // This can be used to attach properties to mode objects from
  4830. // outside the actual mode definition.
  4831. var modeExtensions = CodeMirror.modeExtensions = {};
  4832. CodeMirror.extendMode = function(mode, properties) {
  4833. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  4834. copyObj(properties, exts);
  4835. };
  4836. // EXTENSIONS
  4837. CodeMirror.defineExtension = function(name, func) {
  4838. CodeMirror.prototype[name] = func;
  4839. };
  4840. CodeMirror.defineDocExtension = function(name, func) {
  4841. Doc.prototype[name] = func;
  4842. };
  4843. CodeMirror.defineOption = option;
  4844. var initHooks = [];
  4845. CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
  4846. var helpers = CodeMirror.helpers = {};
  4847. CodeMirror.registerHelper = function(type, name, value) {
  4848. if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
  4849. helpers[type][name] = value;
  4850. };
  4851. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  4852. CodeMirror.registerHelper(type, name, value);
  4853. helpers[type]._global.push({pred: predicate, val: value});
  4854. };
  4855. // MODE STATE HANDLING
  4856. // Utility functions for working with state. Exported because nested
  4857. // modes need to do this for their inner modes.
  4858. var copyState = CodeMirror.copyState = function(mode, state) {
  4859. if (state === true) return state;
  4860. if (mode.copyState) return mode.copyState(state);
  4861. var nstate = {};
  4862. for (var n in state) {
  4863. var val = state[n];
  4864. if (val instanceof Array) val = val.concat([]);
  4865. nstate[n] = val;
  4866. }
  4867. return nstate;
  4868. };
  4869. var startState = CodeMirror.startState = function(mode, a1, a2) {
  4870. return mode.startState ? mode.startState(a1, a2) : true;
  4871. };
  4872. // Given a mode and a state (for that mode), find the inner mode and
  4873. // state at the position that the state refers to.
  4874. CodeMirror.innerMode = function(mode, state) {
  4875. while (mode.innerMode) {
  4876. var info = mode.innerMode(state);
  4877. if (!info || info.mode == mode) break;
  4878. state = info.state;
  4879. mode = info.mode;
  4880. }
  4881. return info || {mode: mode, state: state};
  4882. };
  4883. // STANDARD COMMANDS
  4884. // Commands are parameter-less actions that can be performed on an
  4885. // editor, mostly used for keybindings.
  4886. var commands = CodeMirror.commands = {
  4887. selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
  4888. singleSelection: function(cm) {
  4889. cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
  4890. },
  4891. killLine: function(cm) {
  4892. deleteNearSelection(cm, function(range) {
  4893. if (range.empty()) {
  4894. var len = getLine(cm.doc, range.head.line).text.length;
  4895. if (range.head.ch == len && range.head.line < cm.lastLine())
  4896. return {from: range.head, to: Pos(range.head.line + 1, 0)};
  4897. else
  4898. return {from: range.head, to: Pos(range.head.line, len)};
  4899. } else {
  4900. return {from: range.from(), to: range.to()};
  4901. }
  4902. });
  4903. },
  4904. deleteLine: function(cm) {
  4905. deleteNearSelection(cm, function(range) {
  4906. return {from: Pos(range.from().line, 0),
  4907. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
  4908. });
  4909. },
  4910. delLineLeft: function(cm) {
  4911. deleteNearSelection(cm, function(range) {
  4912. return {from: Pos(range.from().line, 0), to: range.from()};
  4913. });
  4914. },
  4915. delWrappedLineLeft: function(cm) {
  4916. deleteNearSelection(cm, function(range) {
  4917. var top = cm.charCoords(range.head, "div").top + 5;
  4918. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  4919. return {from: leftPos, to: range.from()};
  4920. });
  4921. },
  4922. delWrappedLineRight: function(cm) {
  4923. deleteNearSelection(cm, function(range) {
  4924. var top = cm.charCoords(range.head, "div").top + 5;
  4925. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  4926. return {from: range.from(), to: rightPos };
  4927. });
  4928. },
  4929. undo: function(cm) {cm.undo();},
  4930. redo: function(cm) {cm.redo();},
  4931. undoSelection: function(cm) {cm.undoSelection();},
  4932. redoSelection: function(cm) {cm.redoSelection();},
  4933. goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
  4934. goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
  4935. goLineStart: function(cm) {
  4936. cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
  4937. {origin: "+move", bias: 1});
  4938. },
  4939. goLineStartSmart: function(cm) {
  4940. cm.extendSelectionsBy(function(range) {
  4941. return lineStartSmart(cm, range.head);
  4942. }, {origin: "+move", bias: 1});
  4943. },
  4944. goLineEnd: function(cm) {
  4945. cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
  4946. {origin: "+move", bias: -1});
  4947. },
  4948. goLineRight: function(cm) {
  4949. cm.extendSelectionsBy(function(range) {
  4950. var top = cm.charCoords(range.head, "div").top + 5;
  4951. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  4952. }, sel_move);
  4953. },
  4954. goLineLeft: function(cm) {
  4955. cm.extendSelectionsBy(function(range) {
  4956. var top = cm.charCoords(range.head, "div").top + 5;
  4957. return cm.coordsChar({left: 0, top: top}, "div");
  4958. }, sel_move);
  4959. },
  4960. goLineLeftSmart: function(cm) {
  4961. cm.extendSelectionsBy(function(range) {
  4962. var top = cm.charCoords(range.head, "div").top + 5;
  4963. var pos = cm.coordsChar({left: 0, top: top}, "div");
  4964. if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
  4965. return pos;
  4966. }, sel_move);
  4967. },
  4968. goLineUp: function(cm) {cm.moveV(-1, "line");},
  4969. goLineDown: function(cm) {cm.moveV(1, "line");},
  4970. goPageUp: function(cm) {cm.moveV(-1, "page");},
  4971. goPageDown: function(cm) {cm.moveV(1, "page");},
  4972. goCharLeft: function(cm) {cm.moveH(-1, "char");},
  4973. goCharRight: function(cm) {cm.moveH(1, "char");},
  4974. goColumnLeft: function(cm) {cm.moveH(-1, "column");},
  4975. goColumnRight: function(cm) {cm.moveH(1, "column");},
  4976. goWordLeft: function(cm) {cm.moveH(-1, "word");},
  4977. goGroupRight: function(cm) {cm.moveH(1, "group");},
  4978. goGroupLeft: function(cm) {cm.moveH(-1, "group");},
  4979. goWordRight: function(cm) {cm.moveH(1, "word");},
  4980. delCharBefore: function(cm) {cm.deleteH(-1, "char");},
  4981. delCharAfter: function(cm) {cm.deleteH(1, "char");},
  4982. delWordBefore: function(cm) {cm.deleteH(-1, "word");},
  4983. delWordAfter: function(cm) {cm.deleteH(1, "word");},
  4984. delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
  4985. delGroupAfter: function(cm) {cm.deleteH(1, "group");},
  4986. indentAuto: function(cm) {cm.indentSelection("smart");},
  4987. indentMore: function(cm) {cm.indentSelection("add");},
  4988. indentLess: function(cm) {cm.indentSelection("subtract");},
  4989. insertTab: function(cm) {cm.replaceSelection("\t");},
  4990. insertSoftTab: function(cm) {
  4991. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  4992. for (var i = 0; i < ranges.length; i++) {
  4993. var pos = ranges[i].from();
  4994. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  4995. spaces.push(new Array(tabSize - col % tabSize + 1).join(" "));
  4996. }
  4997. cm.replaceSelections(spaces);
  4998. },
  4999. defaultTab: function(cm) {
  5000. if (cm.somethingSelected()) cm.indentSelection("add");
  5001. else cm.execCommand("insertTab");
  5002. },
  5003. transposeChars: function(cm) {
  5004. runInOp(cm, function() {
  5005. var ranges = cm.listSelections(), newSel = [];
  5006. for (var i = 0; i < ranges.length; i++) {
  5007. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  5008. if (line) {
  5009. if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
  5010. if (cur.ch > 0) {
  5011. cur = new Pos(cur.line, cur.ch + 1);
  5012. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  5013. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  5014. } else if (cur.line > cm.doc.first) {
  5015. var prev = getLine(cm.doc, cur.line - 1).text;
  5016. if (prev)
  5017. cm.replaceRange(line.charAt(0) + "\n" + prev.charAt(prev.length - 1),
  5018. Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
  5019. }
  5020. }
  5021. newSel.push(new Range(cur, cur));
  5022. }
  5023. cm.setSelections(newSel);
  5024. });
  5025. },
  5026. newlineAndIndent: function(cm) {
  5027. runInOp(cm, function() {
  5028. var len = cm.listSelections().length;
  5029. for (var i = 0; i < len; i++) {
  5030. var range = cm.listSelections()[i];
  5031. cm.replaceRange("\n", range.anchor, range.head, "+input");
  5032. cm.indentLine(range.from().line + 1, null, true);
  5033. ensureCursorVisible(cm);
  5034. }
  5035. });
  5036. },
  5037. toggleOverwrite: function(cm) {cm.toggleOverwrite();}
  5038. };
  5039. // STANDARD KEYMAPS
  5040. var keyMap = CodeMirror.keyMap = {};
  5041. keyMap.basic = {
  5042. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  5043. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  5044. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  5045. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  5046. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  5047. "Esc": "singleSelection"
  5048. };
  5049. // Note that the save and find-related commands aren't defined by
  5050. // default. User code or addons can define them. Unknown commands
  5051. // are simply ignored.
  5052. keyMap.pcDefault = {
  5053. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  5054. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  5055. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  5056. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  5057. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  5058. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  5059. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  5060. fallthrough: "basic"
  5061. };
  5062. // Very basic readline/emacs-style bindings, which are standard on Mac.
  5063. keyMap.emacsy = {
  5064. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  5065. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  5066. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  5067. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
  5068. };
  5069. keyMap.macDefault = {
  5070. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  5071. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  5072. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  5073. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  5074. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  5075. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  5076. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  5077. fallthrough: ["basic", "emacsy"]
  5078. };
  5079. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  5080. // KEYMAP DISPATCH
  5081. function normalizeKeyName(name) {
  5082. var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
  5083. var alt, ctrl, shift, cmd;
  5084. for (var i = 0; i < parts.length - 1; i++) {
  5085. var mod = parts[i];
  5086. if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
  5087. else if (/^a(lt)?$/i.test(mod)) alt = true;
  5088. else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
  5089. else if (/^s(hift)$/i.test(mod)) shift = true;
  5090. else throw new Error("Unrecognized modifier name: " + mod);
  5091. }
  5092. if (alt) name = "Alt-" + name;
  5093. if (ctrl) name = "Ctrl-" + name;
  5094. if (cmd) name = "Cmd-" + name;
  5095. if (shift) name = "Shift-" + name;
  5096. return name;
  5097. }
  5098. // This is a kludge to keep keymaps mostly working as raw objects
  5099. // (backwards compatibility) while at the same time support features
  5100. // like normalization and multi-stroke key bindings. It compiles a
  5101. // new normalized keymap, and then updates the old object to reflect
  5102. // this.
  5103. CodeMirror.normalizeKeyMap = function(keymap) {
  5104. var copy = {};
  5105. for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
  5106. var value = keymap[keyname];
  5107. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
  5108. if (value == "...") { delete keymap[keyname]; continue; }
  5109. var keys = map(keyname.split(" "), normalizeKeyName);
  5110. for (var i = 0; i < keys.length; i++) {
  5111. var val, name;
  5112. if (i == keys.length - 1) {
  5113. name = keyname;
  5114. val = value;
  5115. } else {
  5116. name = keys.slice(0, i + 1).join(" ");
  5117. val = "...";
  5118. }
  5119. var prev = copy[name];
  5120. if (!prev) copy[name] = val;
  5121. else if (prev != val) throw new Error("Inconsistent bindings for " + name);
  5122. }
  5123. delete keymap[keyname];
  5124. }
  5125. for (var prop in copy) keymap[prop] = copy[prop];
  5126. return keymap;
  5127. };
  5128. var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
  5129. map = getKeyMap(map);
  5130. var found = map.call ? map.call(key, context) : map[key];
  5131. if (found === false) return "nothing";
  5132. if (found === "...") return "multi";
  5133. if (found != null && handle(found)) return "handled";
  5134. if (map.fallthrough) {
  5135. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  5136. return lookupKey(key, map.fallthrough, handle, context);
  5137. for (var i = 0; i < map.fallthrough.length; i++) {
  5138. var result = lookupKey(key, map.fallthrough[i], handle, context);
  5139. if (result) return result;
  5140. }
  5141. }
  5142. };
  5143. // Modifier key presses don't count as 'real' key presses for the
  5144. // purpose of keymap fallthrough.
  5145. var isModifierKey = CodeMirror.isModifierKey = function(value) {
  5146. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  5147. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
  5148. };
  5149. // Look up the name of a key as indicated by an event object.
  5150. var keyName = CodeMirror.keyName = function(event, noShift) {
  5151. if (presto && event.keyCode == 34 && event["char"]) return false;
  5152. var base = keyNames[event.keyCode], name = base;
  5153. if (name == null || event.altGraphKey) return false;
  5154. if (event.altKey && base != "Alt") name = "Alt-" + name;
  5155. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
  5156. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
  5157. if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
  5158. return name;
  5159. };
  5160. function getKeyMap(val) {
  5161. return typeof val == "string" ? keyMap[val] : val;
  5162. }
  5163. // FROMTEXTAREA
  5164. CodeMirror.fromTextArea = function(textarea, options) {
  5165. options = options ? copyObj(options) : {};
  5166. options.value = textarea.value;
  5167. if (!options.tabindex && textarea.tabIndex)
  5168. options.tabindex = textarea.tabIndex;
  5169. if (!options.placeholder && textarea.placeholder)
  5170. options.placeholder = textarea.placeholder;
  5171. // Set autofocus to true if this textarea is focused, or if it has
  5172. // autofocus and no other element is focused.
  5173. if (options.autofocus == null) {
  5174. var hasFocus = activeElt();
  5175. options.autofocus = hasFocus == textarea ||
  5176. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  5177. }
  5178. function save() {textarea.value = cm.getValue();}
  5179. if (textarea.form) {
  5180. on(textarea.form, "submit", save);
  5181. // Deplorable hack to make the submit method do the right thing.
  5182. if (!options.leaveSubmitMethodAlone) {
  5183. var form = textarea.form, realSubmit = form.submit;
  5184. try {
  5185. var wrappedSubmit = form.submit = function() {
  5186. save();
  5187. form.submit = realSubmit;
  5188. form.submit();
  5189. form.submit = wrappedSubmit;
  5190. };
  5191. } catch(e) {}
  5192. }
  5193. }
  5194. options.finishInit = function(cm) {
  5195. cm.save = save;
  5196. cm.getTextArea = function() { return textarea; };
  5197. cm.toTextArea = function() {
  5198. cm.toTextArea = isNaN; // Prevent this from being ran twice
  5199. save();
  5200. textarea.parentNode.removeChild(cm.getWrapperElement());
  5201. textarea.style.display = "";
  5202. if (textarea.form) {
  5203. off(textarea.form, "submit", save);
  5204. if (typeof textarea.form.submit == "function")
  5205. textarea.form.submit = realSubmit;
  5206. }
  5207. };
  5208. };
  5209. textarea.style.display = "none";
  5210. var cm = CodeMirror(function(node) {
  5211. textarea.parentNode.insertBefore(node, textarea.nextSibling);
  5212. }, options);
  5213. return cm;
  5214. };
  5215. // STRING STREAM
  5216. // Fed to the mode parsers, provides helper functions to make
  5217. // parsers more succinct.
  5218. var StringStream = CodeMirror.StringStream = function(string, tabSize) {
  5219. this.pos = this.start = 0;
  5220. this.string = string;
  5221. this.tabSize = tabSize || 8;
  5222. this.lastColumnPos = this.lastColumnValue = 0;
  5223. this.lineStart = 0;
  5224. };
  5225. StringStream.prototype = {
  5226. eol: function() {return this.pos >= this.string.length;},
  5227. sol: function() {return this.pos == this.lineStart;},
  5228. peek: function() {return this.string.charAt(this.pos) || undefined;},
  5229. next: function() {
  5230. if (this.pos < this.string.length)
  5231. return this.string.charAt(this.pos++);
  5232. },
  5233. eat: function(match) {
  5234. var ch = this.string.charAt(this.pos);
  5235. if (typeof match == "string") var ok = ch == match;
  5236. else var ok = ch && (match.test ? match.test(ch) : match(ch));
  5237. if (ok) {++this.pos; return ch;}
  5238. },
  5239. eatWhile: function(match) {
  5240. var start = this.pos;
  5241. while (this.eat(match)){}
  5242. return this.pos > start;
  5243. },
  5244. eatSpace: function() {
  5245. var start = this.pos;
  5246. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
  5247. return this.pos > start;
  5248. },
  5249. skipToEnd: function() {this.pos = this.string.length;},
  5250. skipTo: function(ch) {
  5251. var found = this.string.indexOf(ch, this.pos);
  5252. if (found > -1) {this.pos = found; return true;}
  5253. },
  5254. backUp: function(n) {this.pos -= n;},
  5255. column: function() {
  5256. if (this.lastColumnPos < this.start) {
  5257. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  5258. this.lastColumnPos = this.start;
  5259. }
  5260. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  5261. },
  5262. indentation: function() {
  5263. return countColumn(this.string, null, this.tabSize) -
  5264. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  5265. },
  5266. match: function(pattern, consume, caseInsensitive) {
  5267. if (typeof pattern == "string") {
  5268. var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
  5269. var substr = this.string.substr(this.pos, pattern.length);
  5270. if (cased(substr) == cased(pattern)) {
  5271. if (consume !== false) this.pos += pattern.length;
  5272. return true;
  5273. }
  5274. } else {
  5275. var match = this.string.slice(this.pos).match(pattern);
  5276. if (match && match.index > 0) return null;
  5277. if (match && consume !== false) this.pos += match[0].length;
  5278. return match;
  5279. }
  5280. },
  5281. current: function(){return this.string.slice(this.start, this.pos);},
  5282. hideFirstChars: function(n, inner) {
  5283. this.lineStart += n;
  5284. try { return inner(); }
  5285. finally { this.lineStart -= n; }
  5286. }
  5287. };
  5288. // TEXTMARKERS
  5289. // Created with markText and setBookmark methods. A TextMarker is a
  5290. // handle that can be used to clear or find a marked position in the
  5291. // document. Line objects hold arrays (markedSpans) containing
  5292. // {from, to, marker} object pointing to such marker objects, and
  5293. // indicating that such a marker is present on that line. Multiple
  5294. // lines may point to the same marker when it spans across lines.
  5295. // The spans will have null for their from/to properties when the
  5296. // marker continues beyond the start/end of the line. Markers have
  5297. // links back to the lines they currently touch.
  5298. var nextMarkerId = 0;
  5299. var TextMarker = CodeMirror.TextMarker = function(doc, type) {
  5300. this.lines = [];
  5301. this.type = type;
  5302. this.doc = doc;
  5303. this.id = ++nextMarkerId;
  5304. };
  5305. eventMixin(TextMarker);
  5306. // Clear the marker.
  5307. TextMarker.prototype.clear = function() {
  5308. if (this.explicitlyCleared) return;
  5309. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  5310. if (withOp) startOperation(cm);
  5311. if (hasHandler(this, "clear")) {
  5312. var found = this.find();
  5313. if (found) signalLater(this, "clear", found.from, found.to);
  5314. }
  5315. var min = null, max = null;
  5316. for (var i = 0; i < this.lines.length; ++i) {
  5317. var line = this.lines[i];
  5318. var span = getMarkedSpanFor(line.markedSpans, this);
  5319. if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
  5320. else if (cm) {
  5321. if (span.to != null) max = lineNo(line);
  5322. if (span.from != null) min = lineNo(line);
  5323. }
  5324. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  5325. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  5326. updateLineHeight(line, textHeight(cm.display));
  5327. }
  5328. if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
  5329. var visual = visualLine(this.lines[i]), len = lineLength(visual);
  5330. if (len > cm.display.maxLineLength) {
  5331. cm.display.maxLine = visual;
  5332. cm.display.maxLineLength = len;
  5333. cm.display.maxLineChanged = true;
  5334. }
  5335. }
  5336. if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
  5337. this.lines.length = 0;
  5338. this.explicitlyCleared = true;
  5339. if (this.atomic && this.doc.cantEdit) {
  5340. this.doc.cantEdit = false;
  5341. if (cm) reCheckSelection(cm.doc);
  5342. }
  5343. if (cm) signalLater(cm, "markerCleared", cm, this);
  5344. if (withOp) endOperation(cm);
  5345. if (this.parent) this.parent.clear();
  5346. };
  5347. // Find the position of the marker in the document. Returns a {from,
  5348. // to} object by default. Side can be passed to get a specific side
  5349. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5350. // Pos objects returned contain a line object, rather than a line
  5351. // number (used to prevent looking up the same line twice).
  5352. TextMarker.prototype.find = function(side, lineObj) {
  5353. if (side == null && this.type == "bookmark") side = 1;
  5354. var from, to;
  5355. for (var i = 0; i < this.lines.length; ++i) {
  5356. var line = this.lines[i];
  5357. var span = getMarkedSpanFor(line.markedSpans, this);
  5358. if (span.from != null) {
  5359. from = Pos(lineObj ? line : lineNo(line), span.from);
  5360. if (side == -1) return from;
  5361. }
  5362. if (span.to != null) {
  5363. to = Pos(lineObj ? line : lineNo(line), span.to);
  5364. if (side == 1) return to;
  5365. }
  5366. }
  5367. return from && {from: from, to: to};
  5368. };
  5369. // Signals that the marker's widget changed, and surrounding layout
  5370. // should be recomputed.
  5371. TextMarker.prototype.changed = function() {
  5372. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  5373. if (!pos || !cm) return;
  5374. runInOp(cm, function() {
  5375. var line = pos.line, lineN = lineNo(pos.line);
  5376. var view = findViewForLine(cm, lineN);
  5377. if (view) {
  5378. clearLineMeasurementCacheFor(view);
  5379. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  5380. }
  5381. cm.curOp.updateMaxLine = true;
  5382. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5383. var oldHeight = widget.height;
  5384. widget.height = null;
  5385. var dHeight = widgetHeight(widget) - oldHeight;
  5386. if (dHeight)
  5387. updateLineHeight(line, line.height + dHeight);
  5388. }
  5389. });
  5390. };
  5391. TextMarker.prototype.attachLine = function(line) {
  5392. if (!this.lines.length && this.doc.cm) {
  5393. var op = this.doc.cm.curOp;
  5394. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5395. (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
  5396. }
  5397. this.lines.push(line);
  5398. };
  5399. TextMarker.prototype.detachLine = function(line) {
  5400. this.lines.splice(indexOf(this.lines, line), 1);
  5401. if (!this.lines.length && this.doc.cm) {
  5402. var op = this.doc.cm.curOp;
  5403. (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  5404. }
  5405. };
  5406. // Collapsed markers have unique ids, in order to be able to order
  5407. // them, which is needed for uniquely determining an outer marker
  5408. // when they overlap (they may nest, but not partially overlap).
  5409. var nextMarkerId = 0;
  5410. // Create a marker, wire it up to the right lines, and
  5411. function markText(doc, from, to, options, type) {
  5412. // Shared markers (across linked documents) are handled separately
  5413. // (markTextShared will call out to this again, once per
  5414. // document).
  5415. if (options && options.shared) return markTextShared(doc, from, to, options, type);
  5416. // Ensure we are in an operation.
  5417. if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
  5418. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  5419. if (options) copyObj(options, marker, false);
  5420. // Don't connect empty markers unless clearWhenEmpty is false
  5421. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5422. return marker;
  5423. if (marker.replacedWith) {
  5424. // Showing up as a widget implies collapsed (widget replaces text)
  5425. marker.collapsed = true;
  5426. marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
  5427. if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
  5428. if (options.insertLeft) marker.widgetNode.insertLeft = true;
  5429. }
  5430. if (marker.collapsed) {
  5431. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5432. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5433. throw new Error("Inserting collapsed marker partially overlapping an existing one");
  5434. sawCollapsedSpans = true;
  5435. }
  5436. if (marker.addToHistory)
  5437. addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
  5438. var curLine = from.line, cm = doc.cm, updateMaxLine;
  5439. doc.iter(curLine, to.line + 1, function(line) {
  5440. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5441. updateMaxLine = true;
  5442. if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
  5443. addMarkedSpan(line, new MarkedSpan(marker,
  5444. curLine == from.line ? from.ch : null,
  5445. curLine == to.line ? to.ch : null));
  5446. ++curLine;
  5447. });
  5448. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5449. if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
  5450. if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
  5451. });
  5452. if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
  5453. if (marker.readOnly) {
  5454. sawReadOnlySpans = true;
  5455. if (doc.history.done.length || doc.history.undone.length)
  5456. doc.clearHistory();
  5457. }
  5458. if (marker.collapsed) {
  5459. marker.id = ++nextMarkerId;
  5460. marker.atomic = true;
  5461. }
  5462. if (cm) {
  5463. // Sync editor state
  5464. if (updateMaxLine) cm.curOp.updateMaxLine = true;
  5465. if (marker.collapsed)
  5466. regChange(cm, from.line, to.line + 1);
  5467. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  5468. for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
  5469. if (marker.atomic) reCheckSelection(cm.doc);
  5470. signalLater(cm, "markerAdded", cm, marker);
  5471. }
  5472. return marker;
  5473. }
  5474. // SHARED TEXTMARKERS
  5475. // A shared marker spans multiple linked documents. It is
  5476. // implemented as a meta-marker-object controlling multiple normal
  5477. // markers.
  5478. var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
  5479. this.markers = markers;
  5480. this.primary = primary;
  5481. for (var i = 0; i < markers.length; ++i)
  5482. markers[i].parent = this;
  5483. };
  5484. eventMixin(SharedTextMarker);
  5485. SharedTextMarker.prototype.clear = function() {
  5486. if (this.explicitlyCleared) return;
  5487. this.explicitlyCleared = true;
  5488. for (var i = 0; i < this.markers.length; ++i)
  5489. this.markers[i].clear();
  5490. signalLater(this, "clear");
  5491. };
  5492. SharedTextMarker.prototype.find = function(side, lineObj) {
  5493. return this.primary.find(side, lineObj);
  5494. };
  5495. function markTextShared(doc, from, to, options, type) {
  5496. options = copyObj(options);
  5497. options.shared = false;
  5498. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  5499. var widget = options.widgetNode;
  5500. linkedDocs(doc, function(doc) {
  5501. if (widget) options.widgetNode = widget.cloneNode(true);
  5502. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  5503. for (var i = 0; i < doc.linked.length; ++i)
  5504. if (doc.linked[i].isParent) return;
  5505. primary = lst(markers);
  5506. });
  5507. return new SharedTextMarker(markers, primary);
  5508. }
  5509. function findSharedMarkers(doc) {
  5510. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
  5511. function(m) { return m.parent; });
  5512. }
  5513. function copySharedMarkers(doc, markers) {
  5514. for (var i = 0; i < markers.length; i++) {
  5515. var marker = markers[i], pos = marker.find();
  5516. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  5517. if (cmp(mFrom, mTo)) {
  5518. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  5519. marker.markers.push(subMark);
  5520. subMark.parent = marker;
  5521. }
  5522. }
  5523. }
  5524. function detachSharedMarkers(markers) {
  5525. for (var i = 0; i < markers.length; i++) {
  5526. var marker = markers[i], linked = [marker.primary.doc];;
  5527. linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
  5528. for (var j = 0; j < marker.markers.length; j++) {
  5529. var subMarker = marker.markers[j];
  5530. if (indexOf(linked, subMarker.doc) == -1) {
  5531. subMarker.parent = null;
  5532. marker.markers.splice(j--, 1);
  5533. }
  5534. }
  5535. }
  5536. }
  5537. // TEXTMARKER SPANS
  5538. function MarkedSpan(marker, from, to) {
  5539. this.marker = marker;
  5540. this.from = from; this.to = to;
  5541. }
  5542. // Search an array of spans for a span matching the given marker.
  5543. function getMarkedSpanFor(spans, marker) {
  5544. if (spans) for (var i = 0; i < spans.length; ++i) {
  5545. var span = spans[i];
  5546. if (span.marker == marker) return span;
  5547. }
  5548. }
  5549. // Remove a span from an array, returning undefined if no spans are
  5550. // left (we don't store arrays for lines without spans).
  5551. function removeMarkedSpan(spans, span) {
  5552. for (var r, i = 0; i < spans.length; ++i)
  5553. if (spans[i] != span) (r || (r = [])).push(spans[i]);
  5554. return r;
  5555. }
  5556. // Add a span to a line.
  5557. function addMarkedSpan(line, span) {
  5558. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  5559. span.marker.attachLine(line);
  5560. }
  5561. // Used for the algorithm that adjusts markers for a change in the
  5562. // document. These functions cut an array of spans at a given
  5563. // character position, returning an array of remaining chunks (or
  5564. // undefined if nothing remains).
  5565. function markedSpansBefore(old, startCh, isInsert) {
  5566. if (old) for (var i = 0, nw; i < old.length; ++i) {
  5567. var span = old[i], marker = span.marker;
  5568. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  5569. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  5570. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
  5571. (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  5572. }
  5573. }
  5574. return nw;
  5575. }
  5576. function markedSpansAfter(old, endCh, isInsert) {
  5577. if (old) for (var i = 0, nw; i < old.length; ++i) {
  5578. var span = old[i], marker = span.marker;
  5579. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  5580. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  5581. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
  5582. (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  5583. span.to == null ? null : span.to - endCh));
  5584. }
  5585. }
  5586. return nw;
  5587. }
  5588. // Given a change object, compute the new set of marker spans that
  5589. // cover the line in which the change took place. Removes spans
  5590. // entirely within the change, reconnects spans belonging to the
  5591. // same marker that appear on both sides of the change, and cuts off
  5592. // spans partially within the change. Returns an array of span
  5593. // arrays with one element for each line in (after) the change.
  5594. function stretchSpansOverChange(doc, change) {
  5595. if (change.full) return null;
  5596. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  5597. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  5598. if (!oldFirst && !oldLast) return null;
  5599. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  5600. // Get the spans that 'stick out' on both sides
  5601. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  5602. var last = markedSpansAfter(oldLast, endCh, isInsert);
  5603. // Next, merge those two ends
  5604. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  5605. if (first) {
  5606. // Fix up .to properties of first
  5607. for (var i = 0; i < first.length; ++i) {
  5608. var span = first[i];
  5609. if (span.to == null) {
  5610. var found = getMarkedSpanFor(last, span.marker);
  5611. if (!found) span.to = startCh;
  5612. else if (sameLine) span.to = found.to == null ? null : found.to + offset;
  5613. }
  5614. }
  5615. }
  5616. if (last) {
  5617. // Fix up .from in last (or move them into first in case of sameLine)
  5618. for (var i = 0; i < last.length; ++i) {
  5619. var span = last[i];
  5620. if (span.to != null) span.to += offset;
  5621. if (span.from == null) {
  5622. var found = getMarkedSpanFor(first, span.marker);
  5623. if (!found) {
  5624. span.from = offset;
  5625. if (sameLine) (first || (first = [])).push(span);
  5626. }
  5627. } else {
  5628. span.from += offset;
  5629. if (sameLine) (first || (first = [])).push(span);
  5630. }
  5631. }
  5632. }
  5633. // Make sure we didn't create any zero-length spans
  5634. if (first) first = clearEmptySpans(first);
  5635. if (last && last != first) last = clearEmptySpans(last);
  5636. var newMarkers = [first];
  5637. if (!sameLine) {
  5638. // Fill gap with whole-line-spans
  5639. var gap = change.text.length - 2, gapMarkers;
  5640. if (gap > 0 && first)
  5641. for (var i = 0; i < first.length; ++i)
  5642. if (first[i].to == null)
  5643. (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
  5644. for (var i = 0; i < gap; ++i)
  5645. newMarkers.push(gapMarkers);
  5646. newMarkers.push(last);
  5647. }
  5648. return newMarkers;
  5649. }
  5650. // Remove spans that are empty and don't have a clearWhenEmpty
  5651. // option of false.
  5652. function clearEmptySpans(spans) {
  5653. for (var i = 0; i < spans.length; ++i) {
  5654. var span = spans[i];
  5655. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  5656. spans.splice(i--, 1);
  5657. }
  5658. if (!spans.length) return null;
  5659. return spans;
  5660. }
  5661. // Used for un/re-doing changes from the history. Combines the
  5662. // result of computing the existing spans with the set of spans that
  5663. // existed in the history (so that deleting around a span and then
  5664. // undoing brings back the span).
  5665. function mergeOldSpans(doc, change) {
  5666. var old = getOldSpans(doc, change);
  5667. var stretched = stretchSpansOverChange(doc, change);
  5668. if (!old) return stretched;
  5669. if (!stretched) return old;
  5670. for (var i = 0; i < old.length; ++i) {
  5671. var oldCur = old[i], stretchCur = stretched[i];
  5672. if (oldCur && stretchCur) {
  5673. spans: for (var j = 0; j < stretchCur.length; ++j) {
  5674. var span = stretchCur[j];
  5675. for (var k = 0; k < oldCur.length; ++k)
  5676. if (oldCur[k].marker == span.marker) continue spans;
  5677. oldCur.push(span);
  5678. }
  5679. } else if (stretchCur) {
  5680. old[i] = stretchCur;
  5681. }
  5682. }
  5683. return old;
  5684. }
  5685. // Used to 'clip' out readOnly ranges when making a change.
  5686. function removeReadOnlyRanges(doc, from, to) {
  5687. var markers = null;
  5688. doc.iter(from.line, to.line + 1, function(line) {
  5689. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  5690. var mark = line.markedSpans[i].marker;
  5691. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  5692. (markers || (markers = [])).push(mark);
  5693. }
  5694. });
  5695. if (!markers) return null;
  5696. var parts = [{from: from, to: to}];
  5697. for (var i = 0; i < markers.length; ++i) {
  5698. var mk = markers[i], m = mk.find(0);
  5699. for (var j = 0; j < parts.length; ++j) {
  5700. var p = parts[j];
  5701. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
  5702. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  5703. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  5704. newParts.push({from: p.from, to: m.from});
  5705. if (dto > 0 || !mk.inclusiveRight && !dto)
  5706. newParts.push({from: m.to, to: p.to});
  5707. parts.splice.apply(parts, newParts);
  5708. j += newParts.length - 1;
  5709. }
  5710. }
  5711. return parts;
  5712. }
  5713. // Connect or disconnect spans from a line.
  5714. function detachMarkedSpans(line) {
  5715. var spans = line.markedSpans;
  5716. if (!spans) return;
  5717. for (var i = 0; i < spans.length; ++i)
  5718. spans[i].marker.detachLine(line);
  5719. line.markedSpans = null;
  5720. }
  5721. function attachMarkedSpans(line, spans) {
  5722. if (!spans) return;
  5723. for (var i = 0; i < spans.length; ++i)
  5724. spans[i].marker.attachLine(line);
  5725. line.markedSpans = spans;
  5726. }
  5727. // Helpers used when computing which overlapping collapsed span
  5728. // counts as the larger one.
  5729. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
  5730. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
  5731. // Returns a number indicating which of two overlapping collapsed
  5732. // spans is larger (and thus includes the other). Falls back to
  5733. // comparing ids when the spans cover exactly the same range.
  5734. function compareCollapsedMarkers(a, b) {
  5735. var lenDiff = a.lines.length - b.lines.length;
  5736. if (lenDiff != 0) return lenDiff;
  5737. var aPos = a.find(), bPos = b.find();
  5738. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  5739. if (fromCmp) return -fromCmp;
  5740. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  5741. if (toCmp) return toCmp;
  5742. return b.id - a.id;
  5743. }
  5744. // Find out whether a line ends or starts in a collapsed span. If
  5745. // so, return the marker for that span.
  5746. function collapsedSpanAtSide(line, start) {
  5747. var sps = sawCollapsedSpans && line.markedSpans, found;
  5748. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  5749. sp = sps[i];
  5750. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  5751. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  5752. found = sp.marker;
  5753. }
  5754. return found;
  5755. }
  5756. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
  5757. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
  5758. // Test whether there exists a collapsed span that partially
  5759. // overlaps (covers the start or end, but not both) of a new span.
  5760. // Such overlap is not allowed.
  5761. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  5762. var line = getLine(doc, lineNo);
  5763. var sps = sawCollapsedSpans && line.markedSpans;
  5764. if (sps) for (var i = 0; i < sps.length; ++i) {
  5765. var sp = sps[i];
  5766. if (!sp.marker.collapsed) continue;
  5767. var found = sp.marker.find(0);
  5768. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  5769. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  5770. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
  5771. if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) ||
  5772. fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight)))
  5773. return true;
  5774. }
  5775. }
  5776. // A visual line is a line as drawn on the screen. Folding, for
  5777. // example, can cause multiple logical lines to appear on the same
  5778. // visual line. This finds the start of the visual line that the
  5779. // given line is part of (usually that is the line itself).
  5780. function visualLine(line) {
  5781. var merged;
  5782. while (merged = collapsedSpanAtStart(line))
  5783. line = merged.find(-1, true).line;
  5784. return line;
  5785. }
  5786. // Returns an array of logical lines that continue the visual line
  5787. // started by the argument, or undefined if there are no such lines.
  5788. function visualLineContinued(line) {
  5789. var merged, lines;
  5790. while (merged = collapsedSpanAtEnd(line)) {
  5791. line = merged.find(1, true).line;
  5792. (lines || (lines = [])).push(line);
  5793. }
  5794. return lines;
  5795. }
  5796. // Get the line number of the start of the visual line that the
  5797. // given line number is part of.
  5798. function visualLineNo(doc, lineN) {
  5799. var line = getLine(doc, lineN), vis = visualLine(line);
  5800. if (line == vis) return lineN;
  5801. return lineNo(vis);
  5802. }
  5803. // Get the line number of the start of the next visual line after
  5804. // the given line.
  5805. function visualLineEndNo(doc, lineN) {
  5806. if (lineN > doc.lastLine()) return lineN;
  5807. var line = getLine(doc, lineN), merged;
  5808. if (!lineIsHidden(doc, line)) return lineN;
  5809. while (merged = collapsedSpanAtEnd(line))
  5810. line = merged.find(1, true).line;
  5811. return lineNo(line) + 1;
  5812. }
  5813. // Compute whether a line is hidden. Lines count as hidden when they
  5814. // are part of a visual line that starts with another line, or when
  5815. // they are entirely covered by collapsed, non-widget span.
  5816. function lineIsHidden(doc, line) {
  5817. var sps = sawCollapsedSpans && line.markedSpans;
  5818. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  5819. sp = sps[i];
  5820. if (!sp.marker.collapsed) continue;
  5821. if (sp.from == null) return true;
  5822. if (sp.marker.widgetNode) continue;
  5823. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  5824. return true;
  5825. }
  5826. }
  5827. function lineIsHiddenInner(doc, line, span) {
  5828. if (span.to == null) {
  5829. var end = span.marker.find(1, true);
  5830. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
  5831. }
  5832. if (span.marker.inclusiveRight && span.to == line.text.length)
  5833. return true;
  5834. for (var sp, i = 0; i < line.markedSpans.length; ++i) {
  5835. sp = line.markedSpans[i];
  5836. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  5837. (sp.to == null || sp.to != span.from) &&
  5838. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  5839. lineIsHiddenInner(doc, line, sp)) return true;
  5840. }
  5841. }
  5842. // LINE WIDGETS
  5843. // Line widgets are block elements displayed above or below a line.
  5844. var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
  5845. if (options) for (var opt in options) if (options.hasOwnProperty(opt))
  5846. this[opt] = options[opt];
  5847. this.doc = doc;
  5848. this.node = node;
  5849. };
  5850. eventMixin(LineWidget);
  5851. function adjustScrollWhenAboveVisible(cm, line, diff) {
  5852. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  5853. addToScrollPos(cm, null, diff);
  5854. }
  5855. LineWidget.prototype.clear = function() {
  5856. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  5857. if (no == null || !ws) return;
  5858. for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
  5859. if (!ws.length) line.widgets = null;
  5860. var height = widgetHeight(this);
  5861. updateLineHeight(line, Math.max(0, line.height - height));
  5862. if (cm) runInOp(cm, function() {
  5863. adjustScrollWhenAboveVisible(cm, line, -height);
  5864. regLineChange(cm, no, "widget");
  5865. });
  5866. };
  5867. LineWidget.prototype.changed = function() {
  5868. var oldH = this.height, cm = this.doc.cm, line = this.line;
  5869. this.height = null;
  5870. var diff = widgetHeight(this) - oldH;
  5871. if (!diff) return;
  5872. updateLineHeight(line, line.height + diff);
  5873. if (cm) runInOp(cm, function() {
  5874. cm.curOp.forceUpdate = true;
  5875. adjustScrollWhenAboveVisible(cm, line, diff);
  5876. });
  5877. };
  5878. function widgetHeight(widget) {
  5879. if (widget.height != null) return widget.height;
  5880. var cm = widget.doc.cm;
  5881. if (!cm) return 0;
  5882. if (!contains(document.body, widget.node)) {
  5883. var parentStyle = "position: relative;";
  5884. if (widget.coverGutter)
  5885. parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
  5886. if (widget.noHScroll)
  5887. parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
  5888. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  5889. }
  5890. return widget.height = widget.node.offsetHeight;
  5891. }
  5892. function addLineWidget(doc, handle, node, options) {
  5893. var widget = new LineWidget(doc, node, options);
  5894. var cm = doc.cm;
  5895. if (cm && widget.noHScroll) cm.display.alignWidgets = true;
  5896. changeLine(doc, handle, "widget", function(line) {
  5897. var widgets = line.widgets || (line.widgets = []);
  5898. if (widget.insertAt == null) widgets.push(widget);
  5899. else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
  5900. widget.line = line;
  5901. if (cm && !lineIsHidden(doc, line)) {
  5902. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  5903. updateLineHeight(line, line.height + widgetHeight(widget));
  5904. if (aboveVisible) addToScrollPos(cm, null, widget.height);
  5905. cm.curOp.forceUpdate = true;
  5906. }
  5907. return true;
  5908. });
  5909. return widget;
  5910. }
  5911. // LINE DATA STRUCTURE
  5912. // Line objects. These hold state related to a line, including
  5913. // highlighting info (the styles array).
  5914. var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
  5915. this.text = text;
  5916. attachMarkedSpans(this, markedSpans);
  5917. this.height = estimateHeight ? estimateHeight(this) : 1;
  5918. };
  5919. eventMixin(Line);
  5920. Line.prototype.lineNo = function() { return lineNo(this); };
  5921. // Change the content (text, markers) of a line. Automatically
  5922. // invalidates cached information and tries to re-estimate the
  5923. // line's height.
  5924. function updateLine(line, text, markedSpans, estimateHeight) {
  5925. line.text = text;
  5926. if (line.stateAfter) line.stateAfter = null;
  5927. if (line.styles) line.styles = null;
  5928. if (line.order != null) line.order = null;
  5929. detachMarkedSpans(line);
  5930. attachMarkedSpans(line, markedSpans);
  5931. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  5932. if (estHeight != line.height) updateLineHeight(line, estHeight);
  5933. }
  5934. // Detach a line from the document tree and its markers.
  5935. function cleanUpLine(line) {
  5936. line.parent = null;
  5937. detachMarkedSpans(line);
  5938. }
  5939. function extractLineClasses(type, output) {
  5940. if (type) for (;;) {
  5941. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  5942. if (!lineClass) break;
  5943. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  5944. var prop = lineClass[1] ? "bgClass" : "textClass";
  5945. if (output[prop] == null)
  5946. output[prop] = lineClass[2];
  5947. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  5948. output[prop] += " " + lineClass[2];
  5949. }
  5950. return type;
  5951. }
  5952. function callBlankLine(mode, state) {
  5953. if (mode.blankLine) return mode.blankLine(state);
  5954. if (!mode.innerMode) return;
  5955. var inner = CodeMirror.innerMode(mode, state);
  5956. if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
  5957. }
  5958. function readToken(mode, stream, state, inner) {
  5959. for (var i = 0; i < 10; i++) {
  5960. if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
  5961. var style = mode.token(stream, state);
  5962. if (stream.pos > stream.start) return style;
  5963. }
  5964. throw new Error("Mode " + mode.name + " failed to advance stream.");
  5965. }
  5966. // Utility for getTokenAt and getLineTokens
  5967. function takeToken(cm, pos, precise, asArray) {
  5968. function getObj(copy) {
  5969. return {start: stream.start, end: stream.pos,
  5970. string: stream.current(),
  5971. type: style || null,
  5972. state: copy ? copyState(doc.mode, state) : state};
  5973. }
  5974. var doc = cm.doc, mode = doc.mode, style;
  5975. pos = clipPos(doc, pos);
  5976. var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
  5977. var stream = new StringStream(line.text, cm.options.tabSize), tokens;
  5978. if (asArray) tokens = [];
  5979. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  5980. stream.start = stream.pos;
  5981. style = readToken(mode, stream, state);
  5982. if (asArray) tokens.push(getObj(true));
  5983. }
  5984. return asArray ? tokens : getObj();
  5985. }
  5986. // Run the given mode's parser over a line, calling f for each token.
  5987. function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
  5988. var flattenSpans = mode.flattenSpans;
  5989. if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
  5990. var curStart = 0, curStyle = null;
  5991. var stream = new StringStream(text, cm.options.tabSize), style;
  5992. var inner = cm.options.addModeClass && [null];
  5993. if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
  5994. while (!stream.eol()) {
  5995. if (stream.pos > cm.options.maxHighlightLength) {
  5996. flattenSpans = false;
  5997. if (forceToEnd) processLine(cm, text, state, stream.pos);
  5998. stream.pos = text.length;
  5999. style = null;
  6000. } else {
  6001. style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
  6002. }
  6003. if (inner) {
  6004. var mName = inner[0].name;
  6005. if (mName) style = "m-" + (style ? mName + " " + style : mName);
  6006. }
  6007. if (!flattenSpans || curStyle != style) {
  6008. while (curStart < stream.start) {
  6009. curStart = Math.min(stream.start, curStart + 50000);
  6010. f(curStart, curStyle);
  6011. }
  6012. curStyle = style;
  6013. }
  6014. stream.start = stream.pos;
  6015. }
  6016. while (curStart < stream.pos) {
  6017. // Webkit seems to refuse to render text nodes longer than 57444 characters
  6018. var pos = Math.min(stream.pos, curStart + 50000);
  6019. f(pos, curStyle);
  6020. curStart = pos;
  6021. }
  6022. }
  6023. // Compute a style array (an array starting with a mode generation
  6024. // -- for invalidation -- followed by pairs of end positions and
  6025. // style strings), which is used to highlight the tokens on the
  6026. // line.
  6027. function highlightLine(cm, line, state, forceToEnd) {
  6028. // A styles array always starts with a number identifying the
  6029. // mode/overlays that it is based on (for easy invalidation).
  6030. var st = [cm.state.modeGen], lineClasses = {};
  6031. // Compute the base array of styles
  6032. runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
  6033. st.push(end, style);
  6034. }, lineClasses, forceToEnd);
  6035. // Run overlays, adjust style array.
  6036. for (var o = 0; o < cm.state.overlays.length; ++o) {
  6037. var overlay = cm.state.overlays[o], i = 1, at = 0;
  6038. runMode(cm, line.text, overlay.mode, true, function(end, style) {
  6039. var start = i;
  6040. // Ensure there's a token end at the current position, and that i points at it
  6041. while (at < end) {
  6042. var i_end = st[i];
  6043. if (i_end > end)
  6044. st.splice(i, 1, end, st[i+1], i_end);
  6045. i += 2;
  6046. at = Math.min(end, i_end);
  6047. }
  6048. if (!style) return;
  6049. if (overlay.opaque) {
  6050. st.splice(start, i - start, end, "cm-overlay " + style);
  6051. i = start + 2;
  6052. } else {
  6053. for (; start < i; start += 2) {
  6054. var cur = st[start+1];
  6055. st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
  6056. }
  6057. }
  6058. }, lineClasses);
  6059. }
  6060. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
  6061. }
  6062. function getLineStyles(cm, line, updateFrontier) {
  6063. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  6064. var result = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
  6065. line.styles = result.styles;
  6066. if (result.classes) line.styleClasses = result.classes;
  6067. else if (line.styleClasses) line.styleClasses = null;
  6068. if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
  6069. }
  6070. return line.styles;
  6071. }
  6072. // Lightweight form of highlight -- proceed over this line and
  6073. // update state, but don't save a style array. Used for lines that
  6074. // aren't currently visible.
  6075. function processLine(cm, text, state, startAt) {
  6076. var mode = cm.doc.mode;
  6077. var stream = new StringStream(text, cm.options.tabSize);
  6078. stream.start = stream.pos = startAt || 0;
  6079. if (text == "") callBlankLine(mode, state);
  6080. while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) {
  6081. readToken(mode, stream, state);
  6082. stream.start = stream.pos;
  6083. }
  6084. }
  6085. // Convert a style as returned by a mode (either null, or a string
  6086. // containing one or more styles) to a CSS style. This is cached,
  6087. // and also looks for line-wide styles.
  6088. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  6089. function interpretTokenStyle(style, options) {
  6090. if (!style || /^\s*$/.test(style)) return null;
  6091. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  6092. return cache[style] ||
  6093. (cache[style] = style.replace(/\S+/g, "cm-$&"));
  6094. }
  6095. // Render the DOM representation of the text of a line. Also builds
  6096. // up a 'line map', which points at the DOM nodes that represent
  6097. // specific stretches of text, and is used by the measuring code.
  6098. // The returned object contains the DOM node, this map, and
  6099. // information about line-wide styles that were set by the mode.
  6100. function buildLineContent(cm, lineView) {
  6101. // The padding-right forces the element to have a 'border', which
  6102. // is needed on Webkit to be able to get line-level bounding
  6103. // rectangles for it (in measureChar).
  6104. var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
  6105. var builder = {pre: elt("pre", [content]), content: content,
  6106. col: 0, pos: 0, cm: cm,
  6107. splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
  6108. lineView.measure = {};
  6109. // Iterate over the logical lines that make up this visual line.
  6110. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  6111. var line = i ? lineView.rest[i - 1] : lineView.line, order;
  6112. builder.pos = 0;
  6113. builder.addToken = buildToken;
  6114. // Optionally wire in some hacks into the token-rendering
  6115. // algorithm, to deal with browser quirks.
  6116. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
  6117. builder.addToken = buildTokenBadBidi(builder.addToken, order);
  6118. builder.map = [];
  6119. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  6120. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  6121. if (line.styleClasses) {
  6122. if (line.styleClasses.bgClass)
  6123. builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
  6124. if (line.styleClasses.textClass)
  6125. builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
  6126. }
  6127. // Ensure at least a single node is present, for measuring.
  6128. if (builder.map.length == 0)
  6129. builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
  6130. // Store the map and a cache object for the current logical line
  6131. if (i == 0) {
  6132. lineView.measure.map = builder.map;
  6133. lineView.measure.cache = {};
  6134. } else {
  6135. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
  6136. (lineView.measure.caches || (lineView.measure.caches = [])).push({});
  6137. }
  6138. }
  6139. // See issue #2901
  6140. if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className))
  6141. builder.content.className = "cm-tab-wrap-hack";
  6142. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  6143. if (builder.pre.className)
  6144. builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
  6145. return builder;
  6146. }
  6147. function defaultSpecialCharPlaceholder(ch) {
  6148. var token = elt("span", "\u2022", "cm-invalidchar");
  6149. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  6150. token.setAttribute("aria-label", token.title);
  6151. return token;
  6152. }
  6153. // Build up the DOM representation for a single token, and add it to
  6154. // the line map. Takes care to render special characters separately.
  6155. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  6156. if (!text) return;
  6157. var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text;
  6158. var special = builder.cm.state.specialChars, mustWrap = false;
  6159. if (!special.test(text)) {
  6160. builder.col += text.length;
  6161. var content = document.createTextNode(displayText);
  6162. builder.map.push(builder.pos, builder.pos + text.length, content);
  6163. if (ie && ie_version < 9) mustWrap = true;
  6164. builder.pos += text.length;
  6165. } else {
  6166. var content = document.createDocumentFragment(), pos = 0;
  6167. while (true) {
  6168. special.lastIndex = pos;
  6169. var m = special.exec(text);
  6170. var skipped = m ? m.index - pos : text.length - pos;
  6171. if (skipped) {
  6172. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  6173. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  6174. else content.appendChild(txt);
  6175. builder.map.push(builder.pos, builder.pos + skipped, txt);
  6176. builder.col += skipped;
  6177. builder.pos += skipped;
  6178. }
  6179. if (!m) break;
  6180. pos += skipped + 1;
  6181. if (m[0] == "\t") {
  6182. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  6183. var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  6184. txt.setAttribute("role", "presentation");
  6185. txt.setAttribute("cm-text", "\t");
  6186. builder.col += tabWidth;
  6187. } else {
  6188. var txt = builder.cm.options.specialCharPlaceholder(m[0]);
  6189. txt.setAttribute("cm-text", m[0]);
  6190. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  6191. else content.appendChild(txt);
  6192. builder.col += 1;
  6193. }
  6194. builder.map.push(builder.pos, builder.pos + 1, txt);
  6195. builder.pos++;
  6196. }
  6197. }
  6198. if (style || startStyle || endStyle || mustWrap || css) {
  6199. var fullStyle = style || "";
  6200. if (startStyle) fullStyle += startStyle;
  6201. if (endStyle) fullStyle += endStyle;
  6202. var token = elt("span", [content], fullStyle, css);
  6203. if (title) token.title = title;
  6204. return builder.content.appendChild(token);
  6205. }
  6206. builder.content.appendChild(content);
  6207. }
  6208. function splitSpaces(old) {
  6209. var out = " ";
  6210. for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
  6211. out += " ";
  6212. return out;
  6213. }
  6214. // Work around nonsense dimensions being reported for stretches of
  6215. // right-to-left text.
  6216. function buildTokenBadBidi(inner, order) {
  6217. return function(builder, text, style, startStyle, endStyle, title, css) {
  6218. style = style ? style + " cm-force-border" : "cm-force-border";
  6219. var start = builder.pos, end = start + text.length;
  6220. for (;;) {
  6221. // Find the part that overlaps with the start of this text
  6222. for (var i = 0; i < order.length; i++) {
  6223. var part = order[i];
  6224. if (part.to > start && part.from <= start) break;
  6225. }
  6226. if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css);
  6227. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
  6228. startStyle = null;
  6229. text = text.slice(part.to - start);
  6230. start = part.to;
  6231. }
  6232. };
  6233. }
  6234. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  6235. var widget = !ignoreWidget && marker.widgetNode;
  6236. if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
  6237. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  6238. if (!widget)
  6239. widget = builder.content.appendChild(document.createElement("span"));
  6240. widget.setAttribute("cm-marker", marker.id);
  6241. }
  6242. if (widget) {
  6243. builder.cm.display.input.setUneditable(widget);
  6244. builder.content.appendChild(widget);
  6245. }
  6246. builder.pos += size;
  6247. }
  6248. // Outputs a number of spans to make up a line, taking highlighting
  6249. // and marked text into account.
  6250. function insertLineContent(line, builder, styles) {
  6251. var spans = line.markedSpans, allText = line.text, at = 0;
  6252. if (!spans) {
  6253. for (var i = 1; i < styles.length; i+=2)
  6254. builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
  6255. return;
  6256. }
  6257. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  6258. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
  6259. for (;;) {
  6260. if (nextChange == pos) { // Update current marker set
  6261. spanStyle = spanEndStyle = spanStartStyle = title = css = "";
  6262. collapsed = null; nextChange = Infinity;
  6263. var foundBookmarks = [];
  6264. for (var j = 0; j < spans.length; ++j) {
  6265. var sp = spans[j], m = sp.marker;
  6266. if (sp.from <= pos && (sp.to == null || sp.to > pos)) {
  6267. if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }
  6268. if (m.className) spanStyle += " " + m.className;
  6269. if (m.css) css = m.css;
  6270. if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
  6271. if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
  6272. if (m.title && !title) title = m.title;
  6273. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  6274. collapsed = sp;
  6275. } else if (sp.from > pos && nextChange > sp.from) {
  6276. nextChange = sp.from;
  6277. }
  6278. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) foundBookmarks.push(m);
  6279. }
  6280. if (collapsed && (collapsed.from || 0) == pos) {
  6281. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  6282. collapsed.marker, collapsed.from == null);
  6283. if (collapsed.to == null) return;
  6284. }
  6285. if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)
  6286. buildCollapsedSpan(builder, 0, foundBookmarks[j]);
  6287. }
  6288. if (pos >= len) break;
  6289. var upto = Math.min(len, nextChange);
  6290. while (true) {
  6291. if (text) {
  6292. var end = pos + text.length;
  6293. if (!collapsed) {
  6294. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  6295. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  6296. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
  6297. }
  6298. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
  6299. pos = end;
  6300. spanStartStyle = "";
  6301. }
  6302. text = allText.slice(at, at = styles[i++]);
  6303. style = interpretTokenStyle(styles[i++], builder.cm.options);
  6304. }
  6305. }
  6306. }
  6307. // DOCUMENT DATA STRUCTURE
  6308. // By default, updates that start and end at the beginning of a line
  6309. // are treated specially, in order to make the association of line
  6310. // widgets and marker elements with the text behave more intuitive.
  6311. function isWholeLineUpdate(doc, change) {
  6312. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  6313. (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
  6314. }
  6315. // Perform a change on the document data structure.
  6316. function updateDoc(doc, change, markedSpans, estimateHeight) {
  6317. function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
  6318. function update(line, text, spans) {
  6319. updateLine(line, text, spans, estimateHeight);
  6320. signalLater(line, "change", line, change);
  6321. }
  6322. function linesFor(start, end) {
  6323. for (var i = start, result = []; i < end; ++i)
  6324. result.push(new Line(text[i], spansFor(i), estimateHeight));
  6325. return result;
  6326. }
  6327. var from = change.from, to = change.to, text = change.text;
  6328. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  6329. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  6330. // Adjust the line structure
  6331. if (change.full) {
  6332. doc.insert(0, linesFor(0, text.length));
  6333. doc.remove(text.length, doc.size - text.length);
  6334. } else if (isWholeLineUpdate(doc, change)) {
  6335. // This is a whole-line replace. Treated specially to make
  6336. // sure line objects move the way they are supposed to.
  6337. var added = linesFor(0, text.length - 1);
  6338. update(lastLine, lastLine.text, lastSpans);
  6339. if (nlines) doc.remove(from.line, nlines);
  6340. if (added.length) doc.insert(from.line, added);
  6341. } else if (firstLine == lastLine) {
  6342. if (text.length == 1) {
  6343. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  6344. } else {
  6345. var added = linesFor(1, text.length - 1);
  6346. added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  6347. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  6348. doc.insert(from.line + 1, added);
  6349. }
  6350. } else if (text.length == 1) {
  6351. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  6352. doc.remove(from.line + 1, nlines);
  6353. } else {
  6354. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  6355. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  6356. var added = linesFor(1, text.length - 1);
  6357. if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
  6358. doc.insert(from.line + 1, added);
  6359. }
  6360. signalLater(doc, "change", doc, change);
  6361. }
  6362. // The document is represented as a BTree consisting of leaves, with
  6363. // chunk of lines in them, and branches, with up to ten leaves or
  6364. // other branch nodes below them. The top node is always a branch
  6365. // node, and is the document object itself (meaning it has
  6366. // additional methods and properties).
  6367. //
  6368. // All nodes have parent links. The tree is used both to go from
  6369. // line numbers to line objects, and to go from objects to numbers.
  6370. // It also indexes by height, and is used to convert between height
  6371. // and line object, and to find the total height of the document.
  6372. //
  6373. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  6374. function LeafChunk(lines) {
  6375. this.lines = lines;
  6376. this.parent = null;
  6377. for (var i = 0, height = 0; i < lines.length; ++i) {
  6378. lines[i].parent = this;
  6379. height += lines[i].height;
  6380. }
  6381. this.height = height;
  6382. }
  6383. LeafChunk.prototype = {
  6384. chunkSize: function() { return this.lines.length; },
  6385. // Remove the n lines at offset 'at'.
  6386. removeInner: function(at, n) {
  6387. for (var i = at, e = at + n; i < e; ++i) {
  6388. var line = this.lines[i];
  6389. this.height -= line.height;
  6390. cleanUpLine(line);
  6391. signalLater(line, "delete");
  6392. }
  6393. this.lines.splice(at, n);
  6394. },
  6395. // Helper used to collapse a small branch into a single leaf.
  6396. collapse: function(lines) {
  6397. lines.push.apply(lines, this.lines);
  6398. },
  6399. // Insert the given array of lines at offset 'at', count them as
  6400. // having the given height.
  6401. insertInner: function(at, lines, height) {
  6402. this.height += height;
  6403. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  6404. for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
  6405. },
  6406. // Used to iterate over a part of the tree.
  6407. iterN: function(at, n, op) {
  6408. for (var e = at + n; at < e; ++at)
  6409. if (op(this.lines[at])) return true;
  6410. }
  6411. };
  6412. function BranchChunk(children) {
  6413. this.children = children;
  6414. var size = 0, height = 0;
  6415. for (var i = 0; i < children.length; ++i) {
  6416. var ch = children[i];
  6417. size += ch.chunkSize(); height += ch.height;
  6418. ch.parent = this;
  6419. }
  6420. this.size = size;
  6421. this.height = height;
  6422. this.parent = null;
  6423. }
  6424. BranchChunk.prototype = {
  6425. chunkSize: function() { return this.size; },
  6426. removeInner: function(at, n) {
  6427. this.size -= n;
  6428. for (var i = 0; i < this.children.length; ++i) {
  6429. var child = this.children[i], sz = child.chunkSize();
  6430. if (at < sz) {
  6431. var rm = Math.min(n, sz - at), oldHeight = child.height;
  6432. child.removeInner(at, rm);
  6433. this.height -= oldHeight - child.height;
  6434. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  6435. if ((n -= rm) == 0) break;
  6436. at = 0;
  6437. } else at -= sz;
  6438. }
  6439. // If the result is smaller than 25 lines, ensure that it is a
  6440. // single leaf node.
  6441. if (this.size - n < 25 &&
  6442. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  6443. var lines = [];
  6444. this.collapse(lines);
  6445. this.children = [new LeafChunk(lines)];
  6446. this.children[0].parent = this;
  6447. }
  6448. },
  6449. collapse: function(lines) {
  6450. for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
  6451. },
  6452. insertInner: function(at, lines, height) {
  6453. this.size += lines.length;
  6454. this.height += height;
  6455. for (var i = 0; i < this.children.length; ++i) {
  6456. var child = this.children[i], sz = child.chunkSize();
  6457. if (at <= sz) {
  6458. child.insertInner(at, lines, height);
  6459. if (child.lines && child.lines.length > 50) {
  6460. while (child.lines.length > 50) {
  6461. var spilled = child.lines.splice(child.lines.length - 25, 25);
  6462. var newleaf = new LeafChunk(spilled);
  6463. child.height -= newleaf.height;
  6464. this.children.splice(i + 1, 0, newleaf);
  6465. newleaf.parent = this;
  6466. }
  6467. this.maybeSpill();
  6468. }
  6469. break;
  6470. }
  6471. at -= sz;
  6472. }
  6473. },
  6474. // When a node has grown, check whether it should be split.
  6475. maybeSpill: function() {
  6476. if (this.children.length <= 10) return;
  6477. var me = this;
  6478. do {
  6479. var spilled = me.children.splice(me.children.length - 5, 5);
  6480. var sibling = new BranchChunk(spilled);
  6481. if (!me.parent) { // Become the parent node
  6482. var copy = new BranchChunk(me.children);
  6483. copy.parent = me;
  6484. me.children = [copy, sibling];
  6485. me = copy;
  6486. } else {
  6487. me.size -= sibling.size;
  6488. me.height -= sibling.height;
  6489. var myIndex = indexOf(me.parent.children, me);
  6490. me.parent.children.splice(myIndex + 1, 0, sibling);
  6491. }
  6492. sibling.parent = me.parent;
  6493. } while (me.children.length > 10);
  6494. me.parent.maybeSpill();
  6495. },
  6496. iterN: function(at, n, op) {
  6497. for (var i = 0; i < this.children.length; ++i) {
  6498. var child = this.children[i], sz = child.chunkSize();
  6499. if (at < sz) {
  6500. var used = Math.min(n, sz - at);
  6501. if (child.iterN(at, used, op)) return true;
  6502. if ((n -= used) == 0) break;
  6503. at = 0;
  6504. } else at -= sz;
  6505. }
  6506. }
  6507. };
  6508. var nextDocId = 0;
  6509. var Doc = CodeMirror.Doc = function(text, mode, firstLine) {
  6510. if (!(this instanceof Doc)) return new Doc(text, mode, firstLine);
  6511. if (firstLine == null) firstLine = 0;
  6512. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  6513. this.first = firstLine;
  6514. this.scrollTop = this.scrollLeft = 0;
  6515. this.cantEdit = false;
  6516. this.cleanGeneration = 1;
  6517. this.frontier = firstLine;
  6518. var start = Pos(firstLine, 0);
  6519. this.sel = simpleSelection(start);
  6520. this.history = new History(null);
  6521. this.id = ++nextDocId;
  6522. this.modeOption = mode;
  6523. if (typeof text == "string") text = splitLines(text);
  6524. updateDoc(this, {from: start, to: start, text: text});
  6525. setSelection(this, simpleSelection(start), sel_dontScroll);
  6526. };
  6527. Doc.prototype = createObj(BranchChunk.prototype, {
  6528. constructor: Doc,
  6529. // Iterate over the document. Supports two forms -- with only one
  6530. // argument, it calls that for each line in the document. With
  6531. // three, it iterates over the range given by the first two (with
  6532. // the second being non-inclusive).
  6533. iter: function(from, to, op) {
  6534. if (op) this.iterN(from - this.first, to - from, op);
  6535. else this.iterN(this.first, this.first + this.size, from);
  6536. },
  6537. // Non-public interface for adding and removing lines.
  6538. insert: function(at, lines) {
  6539. var height = 0;
  6540. for (var i = 0; i < lines.length; ++i) height += lines[i].height;
  6541. this.insertInner(at - this.first, lines, height);
  6542. },
  6543. remove: function(at, n) { this.removeInner(at - this.first, n); },
  6544. // From here, the methods are part of the public interface. Most
  6545. // are also available from CodeMirror (editor) instances.
  6546. getValue: function(lineSep) {
  6547. var lines = getLines(this, this.first, this.first + this.size);
  6548. if (lineSep === false) return lines;
  6549. return lines.join(lineSep || "\n");
  6550. },
  6551. setValue: docMethodOp(function(code) {
  6552. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  6553. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  6554. text: splitLines(code), origin: "setValue", full: true}, true);
  6555. setSelection(this, simpleSelection(top));
  6556. }),
  6557. replaceRange: function(code, from, to, origin) {
  6558. from = clipPos(this, from);
  6559. to = to ? clipPos(this, to) : from;
  6560. replaceRange(this, code, from, to, origin);
  6561. },
  6562. getRange: function(from, to, lineSep) {
  6563. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  6564. if (lineSep === false) return lines;
  6565. return lines.join(lineSep || "\n");
  6566. },
  6567. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
  6568. getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
  6569. getLineNumber: function(line) {return lineNo(line);},
  6570. getLineHandleVisualStart: function(line) {
  6571. if (typeof line == "number") line = getLine(this, line);
  6572. return visualLine(line);
  6573. },
  6574. lineCount: function() {return this.size;},
  6575. firstLine: function() {return this.first;},
  6576. lastLine: function() {return this.first + this.size - 1;},
  6577. clipPos: function(pos) {return clipPos(this, pos);},
  6578. getCursor: function(start) {
  6579. var range = this.sel.primary(), pos;
  6580. if (start == null || start == "head") pos = range.head;
  6581. else if (start == "anchor") pos = range.anchor;
  6582. else if (start == "end" || start == "to" || start === false) pos = range.to();
  6583. else pos = range.from();
  6584. return pos;
  6585. },
  6586. listSelections: function() { return this.sel.ranges; },
  6587. somethingSelected: function() {return this.sel.somethingSelected();},
  6588. setCursor: docMethodOp(function(line, ch, options) {
  6589. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  6590. }),
  6591. setSelection: docMethodOp(function(anchor, head, options) {
  6592. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  6593. }),
  6594. extendSelection: docMethodOp(function(head, other, options) {
  6595. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  6596. }),
  6597. extendSelections: docMethodOp(function(heads, options) {
  6598. extendSelections(this, clipPosArray(this, heads, options));
  6599. }),
  6600. extendSelectionsBy: docMethodOp(function(f, options) {
  6601. extendSelections(this, map(this.sel.ranges, f), options);
  6602. }),
  6603. setSelections: docMethodOp(function(ranges, primary, options) {
  6604. if (!ranges.length) return;
  6605. for (var i = 0, out = []; i < ranges.length; i++)
  6606. out[i] = new Range(clipPos(this, ranges[i].anchor),
  6607. clipPos(this, ranges[i].head));
  6608. if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
  6609. setSelection(this, normalizeSelection(out, primary), options);
  6610. }),
  6611. addSelection: docMethodOp(function(anchor, head, options) {
  6612. var ranges = this.sel.ranges.slice(0);
  6613. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  6614. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
  6615. }),
  6616. getSelection: function(lineSep) {
  6617. var ranges = this.sel.ranges, lines;
  6618. for (var i = 0; i < ranges.length; i++) {
  6619. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6620. lines = lines ? lines.concat(sel) : sel;
  6621. }
  6622. if (lineSep === false) return lines;
  6623. else return lines.join(lineSep || "\n");
  6624. },
  6625. getSelections: function(lineSep) {
  6626. var parts = [], ranges = this.sel.ranges;
  6627. for (var i = 0; i < ranges.length; i++) {
  6628. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6629. if (lineSep !== false) sel = sel.join(lineSep || "\n");
  6630. parts[i] = sel;
  6631. }
  6632. return parts;
  6633. },
  6634. replaceSelection: function(code, collapse, origin) {
  6635. var dup = [];
  6636. for (var i = 0; i < this.sel.ranges.length; i++)
  6637. dup[i] = code;
  6638. this.replaceSelections(dup, collapse, origin || "+input");
  6639. },
  6640. replaceSelections: docMethodOp(function(code, collapse, origin) {
  6641. var changes = [], sel = this.sel;
  6642. for (var i = 0; i < sel.ranges.length; i++) {
  6643. var range = sel.ranges[i];
  6644. changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin};
  6645. }
  6646. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  6647. for (var i = changes.length - 1; i >= 0; i--)
  6648. makeChange(this, changes[i]);
  6649. if (newSel) setSelectionReplaceHistory(this, newSel);
  6650. else if (this.cm) ensureCursorVisible(this.cm);
  6651. }),
  6652. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  6653. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  6654. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  6655. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  6656. setExtending: function(val) {this.extend = val;},
  6657. getExtending: function() {return this.extend;},
  6658. historySize: function() {
  6659. var hist = this.history, done = 0, undone = 0;
  6660. for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
  6661. for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
  6662. return {undo: done, redo: undone};
  6663. },
  6664. clearHistory: function() {this.history = new History(this.history.maxGeneration);},
  6665. markClean: function() {
  6666. this.cleanGeneration = this.changeGeneration(true);
  6667. },
  6668. changeGeneration: function(forceSplit) {
  6669. if (forceSplit)
  6670. this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
  6671. return this.history.generation;
  6672. },
  6673. isClean: function (gen) {
  6674. return this.history.generation == (gen || this.cleanGeneration);
  6675. },
  6676. getHistory: function() {
  6677. return {done: copyHistoryArray(this.history.done),
  6678. undone: copyHistoryArray(this.history.undone)};
  6679. },
  6680. setHistory: function(histData) {
  6681. var hist = this.history = new History(this.history.maxGeneration);
  6682. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  6683. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  6684. },
  6685. addLineClass: docMethodOp(function(handle, where, cls) {
  6686. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  6687. var prop = where == "text" ? "textClass"
  6688. : where == "background" ? "bgClass"
  6689. : where == "gutter" ? "gutterClass" : "wrapClass";
  6690. if (!line[prop]) line[prop] = cls;
  6691. else if (classTest(cls).test(line[prop])) return false;
  6692. else line[prop] += " " + cls;
  6693. return true;
  6694. });
  6695. }),
  6696. removeLineClass: docMethodOp(function(handle, where, cls) {
  6697. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  6698. var prop = where == "text" ? "textClass"
  6699. : where == "background" ? "bgClass"
  6700. : where == "gutter" ? "gutterClass" : "wrapClass";
  6701. var cur = line[prop];
  6702. if (!cur) return false;
  6703. else if (cls == null) line[prop] = null;
  6704. else {
  6705. var found = cur.match(classTest(cls));
  6706. if (!found) return false;
  6707. var end = found.index + found[0].length;
  6708. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  6709. }
  6710. return true;
  6711. });
  6712. }),
  6713. addLineWidget: docMethodOp(function(handle, node, options) {
  6714. return addLineWidget(this, handle, node, options);
  6715. }),
  6716. removeLineWidget: function(widget) { widget.clear(); },
  6717. markText: function(from, to, options) {
  6718. return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
  6719. },
  6720. setBookmark: function(pos, options) {
  6721. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  6722. insertLeft: options && options.insertLeft,
  6723. clearWhenEmpty: false, shared: options && options.shared,
  6724. handleMouseEvents: options && options.handleMouseEvents};
  6725. pos = clipPos(this, pos);
  6726. return markText(this, pos, pos, realOpts, "bookmark");
  6727. },
  6728. findMarksAt: function(pos) {
  6729. pos = clipPos(this, pos);
  6730. var markers = [], spans = getLine(this, pos.line).markedSpans;
  6731. if (spans) for (var i = 0; i < spans.length; ++i) {
  6732. var span = spans[i];
  6733. if ((span.from == null || span.from <= pos.ch) &&
  6734. (span.to == null || span.to >= pos.ch))
  6735. markers.push(span.marker.parent || span.marker);
  6736. }
  6737. return markers;
  6738. },
  6739. findMarks: function(from, to, filter) {
  6740. from = clipPos(this, from); to = clipPos(this, to);
  6741. var found = [], lineNo = from.line;
  6742. this.iter(from.line, to.line + 1, function(line) {
  6743. var spans = line.markedSpans;
  6744. if (spans) for (var i = 0; i < spans.length; i++) {
  6745. var span = spans[i];
  6746. if (!(lineNo == from.line && from.ch > span.to ||
  6747. span.from == null && lineNo != from.line||
  6748. lineNo == to.line && span.from > to.ch) &&
  6749. (!filter || filter(span.marker)))
  6750. found.push(span.marker.parent || span.marker);
  6751. }
  6752. ++lineNo;
  6753. });
  6754. return found;
  6755. },
  6756. getAllMarks: function() {
  6757. var markers = [];
  6758. this.iter(function(line) {
  6759. var sps = line.markedSpans;
  6760. if (sps) for (var i = 0; i < sps.length; ++i)
  6761. if (sps[i].from != null) markers.push(sps[i].marker);
  6762. });
  6763. return markers;
  6764. },
  6765. posFromIndex: function(off) {
  6766. var ch, lineNo = this.first;
  6767. this.iter(function(line) {
  6768. var sz = line.text.length + 1;
  6769. if (sz > off) { ch = off; return true; }
  6770. off -= sz;
  6771. ++lineNo;
  6772. });
  6773. return clipPos(this, Pos(lineNo, ch));
  6774. },
  6775. indexFromPos: function (coords) {
  6776. coords = clipPos(this, coords);
  6777. var index = coords.ch;
  6778. if (coords.line < this.first || coords.ch < 0) return 0;
  6779. this.iter(this.first, coords.line, function (line) {
  6780. index += line.text.length + 1;
  6781. });
  6782. return index;
  6783. },
  6784. copy: function(copyHistory) {
  6785. var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first);
  6786. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  6787. doc.sel = this.sel;
  6788. doc.extend = false;
  6789. if (copyHistory) {
  6790. doc.history.undoDepth = this.history.undoDepth;
  6791. doc.setHistory(this.getHistory());
  6792. }
  6793. return doc;
  6794. },
  6795. linkedDoc: function(options) {
  6796. if (!options) options = {};
  6797. var from = this.first, to = this.first + this.size;
  6798. if (options.from != null && options.from > from) from = options.from;
  6799. if (options.to != null && options.to < to) to = options.to;
  6800. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from);
  6801. if (options.sharedHist) copy.history = this.history;
  6802. (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  6803. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  6804. copySharedMarkers(copy, findSharedMarkers(this));
  6805. return copy;
  6806. },
  6807. unlinkDoc: function(other) {
  6808. if (other instanceof CodeMirror) other = other.doc;
  6809. if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
  6810. var link = this.linked[i];
  6811. if (link.doc != other) continue;
  6812. this.linked.splice(i, 1);
  6813. other.unlinkDoc(this);
  6814. detachSharedMarkers(findSharedMarkers(this));
  6815. break;
  6816. }
  6817. // If the histories were shared, split them again
  6818. if (other.history == this.history) {
  6819. var splitIds = [other.id];
  6820. linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
  6821. other.history = new History(null);
  6822. other.history.done = copyHistoryArray(this.history.done, splitIds);
  6823. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  6824. }
  6825. },
  6826. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  6827. getMode: function() {return this.mode;},
  6828. getEditor: function() {return this.cm;}
  6829. });
  6830. // Public alias.
  6831. Doc.prototype.eachLine = Doc.prototype.iter;
  6832. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  6833. var dontDelegate = "iter insert remove copy getEditor".split(" ");
  6834. for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  6835. CodeMirror.prototype[prop] = (function(method) {
  6836. return function() {return method.apply(this.doc, arguments);};
  6837. })(Doc.prototype[prop]);
  6838. eventMixin(Doc);
  6839. // Call f for all linked documents.
  6840. function linkedDocs(doc, f, sharedHistOnly) {
  6841. function propagate(doc, skip, sharedHist) {
  6842. if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
  6843. var rel = doc.linked[i];
  6844. if (rel.doc == skip) continue;
  6845. var shared = sharedHist && rel.sharedHist;
  6846. if (sharedHistOnly && !shared) continue;
  6847. f(rel.doc, shared);
  6848. propagate(rel.doc, doc, shared);
  6849. }
  6850. }
  6851. propagate(doc, null, true);
  6852. }
  6853. // Attach a document to an editor.
  6854. function attachDoc(cm, doc) {
  6855. if (doc.cm) throw new Error("This document is already in use.");
  6856. cm.doc = doc;
  6857. doc.cm = cm;
  6858. estimateLineHeights(cm);
  6859. loadMode(cm);
  6860. if (!cm.options.lineWrapping) findMaxLine(cm);
  6861. cm.options.mode = doc.modeOption;
  6862. regChange(cm);
  6863. }
  6864. // LINE UTILITIES
  6865. // Find the line object corresponding to the given line number.
  6866. function getLine(doc, n) {
  6867. n -= doc.first;
  6868. if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
  6869. for (var chunk = doc; !chunk.lines;) {
  6870. for (var i = 0;; ++i) {
  6871. var child = chunk.children[i], sz = child.chunkSize();
  6872. if (n < sz) { chunk = child; break; }
  6873. n -= sz;
  6874. }
  6875. }
  6876. return chunk.lines[n];
  6877. }
  6878. // Get the part of a document between two positions, as an array of
  6879. // strings.
  6880. function getBetween(doc, start, end) {
  6881. var out = [], n = start.line;
  6882. doc.iter(start.line, end.line + 1, function(line) {
  6883. var text = line.text;
  6884. if (n == end.line) text = text.slice(0, end.ch);
  6885. if (n == start.line) text = text.slice(start.ch);
  6886. out.push(text);
  6887. ++n;
  6888. });
  6889. return out;
  6890. }
  6891. // Get the lines between from and to, as array of strings.
  6892. function getLines(doc, from, to) {
  6893. var out = [];
  6894. doc.iter(from, to, function(line) { out.push(line.text); });
  6895. return out;
  6896. }
  6897. // Update the height of a line, propagating the height change
  6898. // upwards to parent nodes.
  6899. function updateLineHeight(line, height) {
  6900. var diff = height - line.height;
  6901. if (diff) for (var n = line; n; n = n.parent) n.height += diff;
  6902. }
  6903. // Given a line object, find its line number by walking up through
  6904. // its parent links.
  6905. function lineNo(line) {
  6906. if (line.parent == null) return null;
  6907. var cur = line.parent, no = indexOf(cur.lines, line);
  6908. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  6909. for (var i = 0;; ++i) {
  6910. if (chunk.children[i] == cur) break;
  6911. no += chunk.children[i].chunkSize();
  6912. }
  6913. }
  6914. return no + cur.first;
  6915. }
  6916. // Find the line at the given vertical position, using the height
  6917. // information in the document tree.
  6918. function lineAtHeight(chunk, h) {
  6919. var n = chunk.first;
  6920. outer: do {
  6921. for (var i = 0; i < chunk.children.length; ++i) {
  6922. var child = chunk.children[i], ch = child.height;
  6923. if (h < ch) { chunk = child; continue outer; }
  6924. h -= ch;
  6925. n += child.chunkSize();
  6926. }
  6927. return n;
  6928. } while (!chunk.lines);
  6929. for (var i = 0; i < chunk.lines.length; ++i) {
  6930. var line = chunk.lines[i], lh = line.height;
  6931. if (h < lh) break;
  6932. h -= lh;
  6933. }
  6934. return n + i;
  6935. }
  6936. // Find the height above the given line.
  6937. function heightAtLine(lineObj) {
  6938. lineObj = visualLine(lineObj);
  6939. var h = 0, chunk = lineObj.parent;
  6940. for (var i = 0; i < chunk.lines.length; ++i) {
  6941. var line = chunk.lines[i];
  6942. if (line == lineObj) break;
  6943. else h += line.height;
  6944. }
  6945. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  6946. for (var i = 0; i < p.children.length; ++i) {
  6947. var cur = p.children[i];
  6948. if (cur == chunk) break;
  6949. else h += cur.height;
  6950. }
  6951. }
  6952. return h;
  6953. }
  6954. // Get the bidi ordering for the given line (and cache it). Returns
  6955. // false for lines that are fully left-to-right, and an array of
  6956. // BidiSpan objects otherwise.
  6957. function getOrder(line) {
  6958. var order = line.order;
  6959. if (order == null) order = line.order = bidiOrdering(line.text);
  6960. return order;
  6961. }
  6962. // HISTORY
  6963. function History(startGen) {
  6964. // Arrays of change events and selections. Doing something adds an
  6965. // event to done and clears undo. Undoing moves events from done
  6966. // to undone, redoing moves them in the other direction.
  6967. this.done = []; this.undone = [];
  6968. this.undoDepth = Infinity;
  6969. // Used to track when changes can be merged into a single undo
  6970. // event
  6971. this.lastModTime = this.lastSelTime = 0;
  6972. this.lastOp = this.lastSelOp = null;
  6973. this.lastOrigin = this.lastSelOrigin = null;
  6974. // Used by the isClean() method
  6975. this.generation = this.maxGeneration = startGen || 1;
  6976. }
  6977. // Create a history change event from an updateDoc-style change
  6978. // object.
  6979. function historyChangeFromChange(doc, change) {
  6980. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  6981. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  6982. linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
  6983. return histChange;
  6984. }
  6985. // Pop all selection events off the end of a history array. Stop at
  6986. // a change event.
  6987. function clearSelectionEvents(array) {
  6988. while (array.length) {
  6989. var last = lst(array);
  6990. if (last.ranges) array.pop();
  6991. else break;
  6992. }
  6993. }
  6994. // Find the top change event in the history. Pop off selection
  6995. // events that are in the way.
  6996. function lastChangeEvent(hist, force) {
  6997. if (force) {
  6998. clearSelectionEvents(hist.done);
  6999. return lst(hist.done);
  7000. } else if (hist.done.length && !lst(hist.done).ranges) {
  7001. return lst(hist.done);
  7002. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  7003. hist.done.pop();
  7004. return lst(hist.done);
  7005. }
  7006. }
  7007. // Register a change in the history. Merges changes that are within
  7008. // a single operation, ore are close together with an origin that
  7009. // allows merging (starting with "+") into a single event.
  7010. function addChangeToHistory(doc, change, selAfter, opId) {
  7011. var hist = doc.history;
  7012. hist.undone.length = 0;
  7013. var time = +new Date, cur;
  7014. if ((hist.lastOp == opId ||
  7015. hist.lastOrigin == change.origin && change.origin &&
  7016. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  7017. change.origin.charAt(0) == "*")) &&
  7018. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  7019. // Merge this change into the last event
  7020. var last = lst(cur.changes);
  7021. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  7022. // Optimized case for simple insertion -- don't want to add
  7023. // new changesets for every character typed
  7024. last.to = changeEnd(change);
  7025. } else {
  7026. // Add new sub-event
  7027. cur.changes.push(historyChangeFromChange(doc, change));
  7028. }
  7029. } else {
  7030. // Can not be merged, start a new event.
  7031. var before = lst(hist.done);
  7032. if (!before || !before.ranges)
  7033. pushSelectionToHistory(doc.sel, hist.done);
  7034. cur = {changes: [historyChangeFromChange(doc, change)],
  7035. generation: hist.generation};
  7036. hist.done.push(cur);
  7037. while (hist.done.length > hist.undoDepth) {
  7038. hist.done.shift();
  7039. if (!hist.done[0].ranges) hist.done.shift();
  7040. }
  7041. }
  7042. hist.done.push(selAfter);
  7043. hist.generation = ++hist.maxGeneration;
  7044. hist.lastModTime = hist.lastSelTime = time;
  7045. hist.lastOp = hist.lastSelOp = opId;
  7046. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  7047. if (!last) signal(doc, "historyAdded");
  7048. }
  7049. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  7050. var ch = origin.charAt(0);
  7051. return ch == "*" ||
  7052. ch == "+" &&
  7053. prev.ranges.length == sel.ranges.length &&
  7054. prev.somethingSelected() == sel.somethingSelected() &&
  7055. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
  7056. }
  7057. // Called whenever the selection changes, sets the new selection as
  7058. // the pending selection in the history, and pushes the old pending
  7059. // selection into the 'done' array when it was significantly
  7060. // different (in number of selected ranges, emptiness, or time).
  7061. function addSelectionToHistory(doc, sel, opId, options) {
  7062. var hist = doc.history, origin = options && options.origin;
  7063. // A new event is started when the previous origin does not match
  7064. // the current, or the origins don't allow matching. Origins
  7065. // starting with * are always merged, those starting with + are
  7066. // merged when similar and close together in time.
  7067. if (opId == hist.lastSelOp ||
  7068. (origin && hist.lastSelOrigin == origin &&
  7069. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  7070. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  7071. hist.done[hist.done.length - 1] = sel;
  7072. else
  7073. pushSelectionToHistory(sel, hist.done);
  7074. hist.lastSelTime = +new Date;
  7075. hist.lastSelOrigin = origin;
  7076. hist.lastSelOp = opId;
  7077. if (options && options.clearRedo !== false)
  7078. clearSelectionEvents(hist.undone);
  7079. }
  7080. function pushSelectionToHistory(sel, dest) {
  7081. var top = lst(dest);
  7082. if (!(top && top.ranges && top.equals(sel)))
  7083. dest.push(sel);
  7084. }
  7085. // Used to store marked span information in the history.
  7086. function attachLocalSpans(doc, change, from, to) {
  7087. var existing = change["spans_" + doc.id], n = 0;
  7088. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
  7089. if (line.markedSpans)
  7090. (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
  7091. ++n;
  7092. });
  7093. }
  7094. // When un/re-doing restores text containing marked spans, those
  7095. // that have been explicitly cleared should not be restored.
  7096. function removeClearedSpans(spans) {
  7097. if (!spans) return null;
  7098. for (var i = 0, out; i < spans.length; ++i) {
  7099. if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
  7100. else if (out) out.push(spans[i]);
  7101. }
  7102. return !out ? spans : out.length ? out : null;
  7103. }
  7104. // Retrieve and filter the old marked spans stored in a change event.
  7105. function getOldSpans(doc, change) {
  7106. var found = change["spans_" + doc.id];
  7107. if (!found) return null;
  7108. for (var i = 0, nw = []; i < change.text.length; ++i)
  7109. nw.push(removeClearedSpans(found[i]));
  7110. return nw;
  7111. }
  7112. // Used both to provide a JSON-safe object in .getHistory, and, when
  7113. // detaching a document, to split the history in two
  7114. function copyHistoryArray(events, newGroup, instantiateSel) {
  7115. for (var i = 0, copy = []; i < events.length; ++i) {
  7116. var event = events[i];
  7117. if (event.ranges) {
  7118. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  7119. continue;
  7120. }
  7121. var changes = event.changes, newChanges = [];
  7122. copy.push({changes: newChanges});
  7123. for (var j = 0; j < changes.length; ++j) {
  7124. var change = changes[j], m;
  7125. newChanges.push({from: change.from, to: change.to, text: change.text});
  7126. if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
  7127. if (indexOf(newGroup, Number(m[1])) > -1) {
  7128. lst(newChanges)[prop] = change[prop];
  7129. delete change[prop];
  7130. }
  7131. }
  7132. }
  7133. }
  7134. return copy;
  7135. }
  7136. // Rebasing/resetting history to deal with externally-sourced changes
  7137. function rebaseHistSelSingle(pos, from, to, diff) {
  7138. if (to < pos.line) {
  7139. pos.line += diff;
  7140. } else if (from < pos.line) {
  7141. pos.line = from;
  7142. pos.ch = 0;
  7143. }
  7144. }
  7145. // Tries to rebase an array of history events given a change in the
  7146. // document. If the change touches the same lines as the event, the
  7147. // event, and everything 'behind' it, is discarded. If the change is
  7148. // before the event, the event's positions are updated. Uses a
  7149. // copy-on-write scheme for the positions, to avoid having to
  7150. // reallocate them all on every rebase, but also avoid problems with
  7151. // shared position objects being unsafely updated.
  7152. function rebaseHistArray(array, from, to, diff) {
  7153. for (var i = 0; i < array.length; ++i) {
  7154. var sub = array[i], ok = true;
  7155. if (sub.ranges) {
  7156. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  7157. for (var j = 0; j < sub.ranges.length; j++) {
  7158. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  7159. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  7160. }
  7161. continue;
  7162. }
  7163. for (var j = 0; j < sub.changes.length; ++j) {
  7164. var cur = sub.changes[j];
  7165. if (to < cur.from.line) {
  7166. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  7167. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  7168. } else if (from <= cur.to.line) {
  7169. ok = false;
  7170. break;
  7171. }
  7172. }
  7173. if (!ok) {
  7174. array.splice(0, i + 1);
  7175. i = 0;
  7176. }
  7177. }
  7178. }
  7179. function rebaseHist(hist, change) {
  7180. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  7181. rebaseHistArray(hist.done, from, to, diff);
  7182. rebaseHistArray(hist.undone, from, to, diff);
  7183. }
  7184. // EVENT UTILITIES
  7185. // Due to the fact that we still support jurassic IE versions, some
  7186. // compatibility wrappers are needed.
  7187. var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
  7188. if (e.preventDefault) e.preventDefault();
  7189. else e.returnValue = false;
  7190. };
  7191. var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
  7192. if (e.stopPropagation) e.stopPropagation();
  7193. else e.cancelBubble = true;
  7194. };
  7195. function e_defaultPrevented(e) {
  7196. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
  7197. }
  7198. var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
  7199. function e_target(e) {return e.target || e.srcElement;}
  7200. function e_button(e) {
  7201. var b = e.which;
  7202. if (b == null) {
  7203. if (e.button & 1) b = 1;
  7204. else if (e.button & 2) b = 3;
  7205. else if (e.button & 4) b = 2;
  7206. }
  7207. if (mac && e.ctrlKey && b == 1) b = 3;
  7208. return b;
  7209. }
  7210. // EVENT HANDLING
  7211. // Lightweight event framework. on/off also work on DOM nodes,
  7212. // registering native DOM handlers.
  7213. var on = CodeMirror.on = function(emitter, type, f) {
  7214. if (emitter.addEventListener)
  7215. emitter.addEventListener(type, f, false);
  7216. else if (emitter.attachEvent)
  7217. emitter.attachEvent("on" + type, f);
  7218. else {
  7219. var map = emitter._handlers || (emitter._handlers = {});
  7220. var arr = map[type] || (map[type] = []);
  7221. arr.push(f);
  7222. }
  7223. };
  7224. var off = CodeMirror.off = function(emitter, type, f) {
  7225. if (emitter.removeEventListener)
  7226. emitter.removeEventListener(type, f, false);
  7227. else if (emitter.detachEvent)
  7228. emitter.detachEvent("on" + type, f);
  7229. else {
  7230. var arr = emitter._handlers && emitter._handlers[type];
  7231. if (!arr) return;
  7232. for (var i = 0; i < arr.length; ++i)
  7233. if (arr[i] == f) { arr.splice(i, 1); break; }
  7234. }
  7235. };
  7236. var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
  7237. var arr = emitter._handlers && emitter._handlers[type];
  7238. if (!arr) return;
  7239. var args = Array.prototype.slice.call(arguments, 2);
  7240. for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
  7241. };
  7242. var orphanDelayedCallbacks = null;
  7243. // Often, we want to signal events at a point where we are in the
  7244. // middle of some work, but don't want the handler to start calling
  7245. // other methods on the editor, which might be in an inconsistent
  7246. // state or simply not expect any other events to happen.
  7247. // signalLater looks whether there are any handlers, and schedules
  7248. // them to be executed when the last operation ends, or, if no
  7249. // operation is active, when a timeout fires.
  7250. function signalLater(emitter, type /*, values...*/) {
  7251. var arr = emitter._handlers && emitter._handlers[type];
  7252. if (!arr) return;
  7253. var args = Array.prototype.slice.call(arguments, 2), list;
  7254. if (operationGroup) {
  7255. list = operationGroup.delayedCallbacks;
  7256. } else if (orphanDelayedCallbacks) {
  7257. list = orphanDelayedCallbacks;
  7258. } else {
  7259. list = orphanDelayedCallbacks = [];
  7260. setTimeout(fireOrphanDelayed, 0);
  7261. }
  7262. function bnd(f) {return function(){f.apply(null, args);};};
  7263. for (var i = 0; i < arr.length; ++i)
  7264. list.push(bnd(arr[i]));
  7265. }
  7266. function fireOrphanDelayed() {
  7267. var delayed = orphanDelayedCallbacks;
  7268. orphanDelayedCallbacks = null;
  7269. for (var i = 0; i < delayed.length; ++i) delayed[i]();
  7270. }
  7271. // The DOM events that CodeMirror handles can be overridden by
  7272. // registering a (non-DOM) handler on the editor for the event name,
  7273. // and preventDefault-ing the event in that handler.
  7274. function signalDOMEvent(cm, e, override) {
  7275. if (typeof e == "string")
  7276. e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
  7277. signal(cm, override || e.type, cm, e);
  7278. return e_defaultPrevented(e) || e.codemirrorIgnore;
  7279. }
  7280. function signalCursorActivity(cm) {
  7281. var arr = cm._handlers && cm._handlers.cursorActivity;
  7282. if (!arr) return;
  7283. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  7284. for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
  7285. set.push(arr[i]);
  7286. }
  7287. function hasHandler(emitter, type) {
  7288. var arr = emitter._handlers && emitter._handlers[type];
  7289. return arr && arr.length > 0;
  7290. }
  7291. // Add on and off methods to a constructor's prototype, to make
  7292. // registering events on such objects more convenient.
  7293. function eventMixin(ctor) {
  7294. ctor.prototype.on = function(type, f) {on(this, type, f);};
  7295. ctor.prototype.off = function(type, f) {off(this, type, f);};
  7296. }
  7297. // MISC UTILITIES
  7298. // Number of pixels added to scroller and sizer to hide scrollbar
  7299. var scrollerGap = 30;
  7300. // Returned or thrown by various protocols to signal 'I'm not
  7301. // handling this'.
  7302. var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
  7303. // Reused option objects for setSelection & friends
  7304. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  7305. function Delayed() {this.id = null;}
  7306. Delayed.prototype.set = function(ms, f) {
  7307. clearTimeout(this.id);
  7308. this.id = setTimeout(f, ms);
  7309. };
  7310. // Counts the column offset in a string, taking tabs into account.
  7311. // Used mostly to find indentation.
  7312. var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
  7313. if (end == null) {
  7314. end = string.search(/[^\s\u00a0]/);
  7315. if (end == -1) end = string.length;
  7316. }
  7317. for (var i = startIndex || 0, n = startValue || 0;;) {
  7318. var nextTab = string.indexOf("\t", i);
  7319. if (nextTab < 0 || nextTab >= end)
  7320. return n + (end - i);
  7321. n += nextTab - i;
  7322. n += tabSize - (n % tabSize);
  7323. i = nextTab + 1;
  7324. }
  7325. };
  7326. // The inverse of countColumn -- find the offset that corresponds to
  7327. // a particular column.
  7328. function findColumn(string, goal, tabSize) {
  7329. for (var pos = 0, col = 0;;) {
  7330. var nextTab = string.indexOf("\t", pos);
  7331. if (nextTab == -1) nextTab = string.length;
  7332. var skipped = nextTab - pos;
  7333. if (nextTab == string.length || col + skipped >= goal)
  7334. return pos + Math.min(skipped, goal - col);
  7335. col += nextTab - pos;
  7336. col += tabSize - (col % tabSize);
  7337. pos = nextTab + 1;
  7338. if (col >= goal) return pos;
  7339. }
  7340. }
  7341. var spaceStrs = [""];
  7342. function spaceStr(n) {
  7343. while (spaceStrs.length <= n)
  7344. spaceStrs.push(lst(spaceStrs) + " ");
  7345. return spaceStrs[n];
  7346. }
  7347. function lst(arr) { return arr[arr.length-1]; }
  7348. var selectInput = function(node) { node.select(); };
  7349. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  7350. selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
  7351. else if (ie) // Suppress mysterious IE10 errors
  7352. selectInput = function(node) { try { node.select(); } catch(_e) {} };
  7353. function indexOf(array, elt) {
  7354. for (var i = 0; i < array.length; ++i)
  7355. if (array[i] == elt) return i;
  7356. return -1;
  7357. }
  7358. function map(array, f) {
  7359. var out = [];
  7360. for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
  7361. return out;
  7362. }
  7363. function nothing() {}
  7364. function createObj(base, props) {
  7365. var inst;
  7366. if (Object.create) {
  7367. inst = Object.create(base);
  7368. } else {
  7369. nothing.prototype = base;
  7370. inst = new nothing();
  7371. }
  7372. if (props) copyObj(props, inst);
  7373. return inst;
  7374. };
  7375. function copyObj(obj, target, overwrite) {
  7376. if (!target) target = {};
  7377. for (var prop in obj)
  7378. if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  7379. target[prop] = obj[prop];
  7380. return target;
  7381. }
  7382. function bind(f) {
  7383. var args = Array.prototype.slice.call(arguments, 1);
  7384. return function(){return f.apply(null, args);};
  7385. }
  7386. var nonASCIISingleCaseWordChar = /[\u00df\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  7387. var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
  7388. return /\w/.test(ch) || ch > "\x80" &&
  7389. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
  7390. };
  7391. function isWordChar(ch, helper) {
  7392. if (!helper) return isWordCharBasic(ch);
  7393. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
  7394. return helper.test(ch);
  7395. }
  7396. function isEmpty(obj) {
  7397. for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
  7398. return true;
  7399. }
  7400. // Extending unicode characters. A series of a non-extending char +
  7401. // any number of extending chars is treated as a single unit as far
  7402. // as editing and measuring is concerned. This is not fully correct,
  7403. // since some scripts/fonts/browsers also treat other configurations
  7404. // of code points as a group.
  7405. var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
  7406. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
  7407. // DOM UTILITIES
  7408. function elt(tag, content, className, style) {
  7409. var e = document.createElement(tag);
  7410. if (className) e.className = className;
  7411. if (style) e.style.cssText = style;
  7412. if (typeof content == "string") e.appendChild(document.createTextNode(content));
  7413. else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
  7414. return e;
  7415. }
  7416. var range;
  7417. if (document.createRange) range = function(node, start, end, endNode) {
  7418. var r = document.createRange();
  7419. r.setEnd(endNode || node, end);
  7420. r.setStart(node, start);
  7421. return r;
  7422. };
  7423. else range = function(node, start, end) {
  7424. var r = document.body.createTextRange();
  7425. try { r.moveToElementText(node.parentNode); }
  7426. catch(e) { return r; }
  7427. r.collapse(true);
  7428. r.moveEnd("character", end);
  7429. r.moveStart("character", start);
  7430. return r;
  7431. };
  7432. function removeChildren(e) {
  7433. for (var count = e.childNodes.length; count > 0; --count)
  7434. e.removeChild(e.firstChild);
  7435. return e;
  7436. }
  7437. function removeChildrenAndAdd(parent, e) {
  7438. return removeChildren(parent).appendChild(e);
  7439. }
  7440. var contains = CodeMirror.contains = function(parent, child) {
  7441. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  7442. child = child.parentNode;
  7443. if (parent.contains)
  7444. return parent.contains(child);
  7445. do {
  7446. if (child.nodeType == 11) child = child.host;
  7447. if (child == parent) return true;
  7448. } while (child = child.parentNode);
  7449. };
  7450. function activeElt() { return document.activeElement; }
  7451. // Older versions of IE throws unspecified error when touching
  7452. // document.activeElement in some cases (during loading, in iframe)
  7453. if (ie && ie_version < 11) activeElt = function() {
  7454. try { return document.activeElement; }
  7455. catch(e) { return document.body; }
  7456. };
  7457. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
  7458. var rmClass = CodeMirror.rmClass = function(node, cls) {
  7459. var current = node.className;
  7460. var match = classTest(cls).exec(current);
  7461. if (match) {
  7462. var after = current.slice(match.index + match[0].length);
  7463. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  7464. }
  7465. };
  7466. var addClass = CodeMirror.addClass = function(node, cls) {
  7467. var current = node.className;
  7468. if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
  7469. };
  7470. function joinClasses(a, b) {
  7471. var as = a.split(" ");
  7472. for (var i = 0; i < as.length; i++)
  7473. if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
  7474. return b;
  7475. }
  7476. // WINDOW-WIDE EVENTS
  7477. // These must be handled carefully, because naively registering a
  7478. // handler for each editor will cause the editors to never be
  7479. // garbage collected.
  7480. function forEachCodeMirror(f) {
  7481. if (!document.body.getElementsByClassName) return;
  7482. var byClass = document.body.getElementsByClassName("CodeMirror");
  7483. for (var i = 0; i < byClass.length; i++) {
  7484. var cm = byClass[i].CodeMirror;
  7485. if (cm) f(cm);
  7486. }
  7487. }
  7488. var globalsRegistered = false;
  7489. function ensureGlobalHandlers() {
  7490. if (globalsRegistered) return;
  7491. registerGlobalHandlers();
  7492. globalsRegistered = true;
  7493. }
  7494. function registerGlobalHandlers() {
  7495. // When the window resizes, we need to refresh active editors.
  7496. var resizeTimer;
  7497. on(window, "resize", function() {
  7498. if (resizeTimer == null) resizeTimer = setTimeout(function() {
  7499. resizeTimer = null;
  7500. forEachCodeMirror(onResize);
  7501. }, 100);
  7502. });
  7503. // When the window loses focus, we want to show the editor as blurred
  7504. on(window, "blur", function() {
  7505. forEachCodeMirror(onBlur);
  7506. });
  7507. }
  7508. // FEATURE DETECTION
  7509. // Detect drag-and-drop
  7510. var dragAndDrop = function() {
  7511. // There is *some* kind of drag-and-drop support in IE6-8, but I
  7512. // couldn't get it to work yet.
  7513. if (ie && ie_version < 9) return false;
  7514. var div = elt('div');
  7515. return "draggable" in div || "dragDrop" in div;
  7516. }();
  7517. var zwspSupported;
  7518. function zeroWidthElement(measure) {
  7519. if (zwspSupported == null) {
  7520. var test = elt("span", "\u200b");
  7521. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  7522. if (measure.firstChild.offsetHeight != 0)
  7523. zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
  7524. }
  7525. var node = zwspSupported ? elt("span", "\u200b") :
  7526. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  7527. node.setAttribute("cm-text", "");
  7528. return node;
  7529. }
  7530. // Feature-detect IE's crummy client rect reporting for bidi text
  7531. var badBidiRects;
  7532. function hasBadBidiRects(measure) {
  7533. if (badBidiRects != null) return badBidiRects;
  7534. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  7535. var r0 = range(txt, 0, 1).getBoundingClientRect();
  7536. if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
  7537. var r1 = range(txt, 1, 2).getBoundingClientRect();
  7538. return badBidiRects = (r1.right - r0.right < 3);
  7539. }
  7540. // See if "".split is the broken IE version, if so, provide an
  7541. // alternative way to split lines.
  7542. var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
  7543. var pos = 0, result = [], l = string.length;
  7544. while (pos <= l) {
  7545. var nl = string.indexOf("\n", pos);
  7546. if (nl == -1) nl = string.length;
  7547. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  7548. var rt = line.indexOf("\r");
  7549. if (rt != -1) {
  7550. result.push(line.slice(0, rt));
  7551. pos += rt + 1;
  7552. } else {
  7553. result.push(line);
  7554. pos = nl + 1;
  7555. }
  7556. }
  7557. return result;
  7558. } : function(string){return string.split(/\r\n?|\n/);};
  7559. var hasSelection = window.getSelection ? function(te) {
  7560. try { return te.selectionStart != te.selectionEnd; }
  7561. catch(e) { return false; }
  7562. } : function(te) {
  7563. try {var range = te.ownerDocument.selection.createRange();}
  7564. catch(e) {}
  7565. if (!range || range.parentElement() != te) return false;
  7566. return range.compareEndPoints("StartToEnd", range) != 0;
  7567. };
  7568. var hasCopyEvent = (function() {
  7569. var e = elt("div");
  7570. if ("oncopy" in e) return true;
  7571. e.setAttribute("oncopy", "return;");
  7572. return typeof e.oncopy == "function";
  7573. })();
  7574. var badZoomedRects = null;
  7575. function hasBadZoomedRects(measure) {
  7576. if (badZoomedRects != null) return badZoomedRects;
  7577. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  7578. var normal = node.getBoundingClientRect();
  7579. var fromRange = range(node, 0, 1).getBoundingClientRect();
  7580. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
  7581. }
  7582. // KEY NAMES
  7583. var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  7584. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  7585. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  7586. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete",
  7587. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  7588. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  7589. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"};
  7590. CodeMirror.keyNames = keyNames;
  7591. (function() {
  7592. // Number keys
  7593. for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
  7594. // Alphabetic keys
  7595. for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
  7596. // Function keys
  7597. for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
  7598. })();
  7599. // BIDI HELPERS
  7600. function iterateBidiSections(order, from, to, f) {
  7601. if (!order) return f(from, to, "ltr");
  7602. var found = false;
  7603. for (var i = 0; i < order.length; ++i) {
  7604. var part = order[i];
  7605. if (part.from < to && part.to > from || from == to && part.to == from) {
  7606. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
  7607. found = true;
  7608. }
  7609. }
  7610. if (!found) f(from, to, "ltr");
  7611. }
  7612. function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
  7613. function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
  7614. function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
  7615. function lineRight(line) {
  7616. var order = getOrder(line);
  7617. if (!order) return line.text.length;
  7618. return bidiRight(lst(order));
  7619. }
  7620. function lineStart(cm, lineN) {
  7621. var line = getLine(cm.doc, lineN);
  7622. var visual = visualLine(line);
  7623. if (visual != line) lineN = lineNo(visual);
  7624. var order = getOrder(visual);
  7625. var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
  7626. return Pos(lineN, ch);
  7627. }
  7628. function lineEnd(cm, lineN) {
  7629. var merged, line = getLine(cm.doc, lineN);
  7630. while (merged = collapsedSpanAtEnd(line)) {
  7631. line = merged.find(1, true).line;
  7632. lineN = null;
  7633. }
  7634. var order = getOrder(line);
  7635. var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
  7636. return Pos(lineN == null ? lineNo(line) : lineN, ch);
  7637. }
  7638. function lineStartSmart(cm, pos) {
  7639. var start = lineStart(cm, pos.line);
  7640. var line = getLine(cm.doc, start.line);
  7641. var order = getOrder(line);
  7642. if (!order || order[0].level == 0) {
  7643. var firstNonWS = Math.max(0, line.text.search(/\S/));
  7644. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  7645. return Pos(start.line, inWS ? 0 : firstNonWS);
  7646. }
  7647. return start;
  7648. }
  7649. function compareBidiLevel(order, a, b) {
  7650. var linedir = order[0].level;
  7651. if (a == linedir) return true;
  7652. if (b == linedir) return false;
  7653. return a < b;
  7654. }
  7655. var bidiOther;
  7656. function getBidiPartAt(order, pos) {
  7657. bidiOther = null;
  7658. for (var i = 0, found; i < order.length; ++i) {
  7659. var cur = order[i];
  7660. if (cur.from < pos && cur.to > pos) return i;
  7661. if ((cur.from == pos || cur.to == pos)) {
  7662. if (found == null) {
  7663. found = i;
  7664. } else if (compareBidiLevel(order, cur.level, order[found].level)) {
  7665. if (cur.from != cur.to) bidiOther = found;
  7666. return i;
  7667. } else {
  7668. if (cur.from != cur.to) bidiOther = i;
  7669. return found;
  7670. }
  7671. }
  7672. }
  7673. return found;
  7674. }
  7675. function moveInLine(line, pos, dir, byUnit) {
  7676. if (!byUnit) return pos + dir;
  7677. do pos += dir;
  7678. while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
  7679. return pos;
  7680. }
  7681. // This is needed in order to move 'visually' through bi-directional
  7682. // text -- i.e., pressing left should make the cursor go left, even
  7683. // when in RTL text. The tricky part is the 'jumps', where RTL and
  7684. // LTR text touch each other. This often requires the cursor offset
  7685. // to move more than one unit, in order to visually move one unit.
  7686. function moveVisually(line, start, dir, byUnit) {
  7687. var bidi = getOrder(line);
  7688. if (!bidi) return moveLogically(line, start, dir, byUnit);
  7689. var pos = getBidiPartAt(bidi, start), part = bidi[pos];
  7690. var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
  7691. for (;;) {
  7692. if (target > part.from && target < part.to) return target;
  7693. if (target == part.from || target == part.to) {
  7694. if (getBidiPartAt(bidi, target) == pos) return target;
  7695. part = bidi[pos += dir];
  7696. return (dir > 0) == part.level % 2 ? part.to : part.from;
  7697. } else {
  7698. part = bidi[pos += dir];
  7699. if (!part) return null;
  7700. if ((dir > 0) == part.level % 2)
  7701. target = moveInLine(line, part.to, -1, byUnit);
  7702. else
  7703. target = moveInLine(line, part.from, 1, byUnit);
  7704. }
  7705. }
  7706. }
  7707. function moveLogically(line, start, dir, byUnit) {
  7708. var target = start + dir;
  7709. if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
  7710. return target < 0 || target > line.text.length ? null : target;
  7711. }
  7712. // Bidirectional ordering algorithm
  7713. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  7714. // that this (partially) implements.
  7715. // One-char codes used for character types:
  7716. // L (L): Left-to-Right
  7717. // R (R): Right-to-Left
  7718. // r (AL): Right-to-Left Arabic
  7719. // 1 (EN): European Number
  7720. // + (ES): European Number Separator
  7721. // % (ET): European Number Terminator
  7722. // n (AN): Arabic Number
  7723. // , (CS): Common Number Separator
  7724. // m (NSM): Non-Spacing Mark
  7725. // b (BN): Boundary Neutral
  7726. // s (B): Paragraph Separator
  7727. // t (S): Segment Separator
  7728. // w (WS): Whitespace
  7729. // N (ON): Other Neutrals
  7730. // Returns null if characters are ordered as they appear
  7731. // (left-to-right), or an array of sections ({from, to, level}
  7732. // objects) in the order in which they occur visually.
  7733. var bidiOrdering = (function() {
  7734. // Character types for codepoints 0 to 0xff
  7735. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  7736. // Character types for codepoints 0x600 to 0x6ff
  7737. var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
  7738. function charType(code) {
  7739. if (code <= 0xf7) return lowTypes.charAt(code);
  7740. else if (0x590 <= code && code <= 0x5f4) return "R";
  7741. else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
  7742. else if (0x6ee <= code && code <= 0x8ac) return "r";
  7743. else if (0x2000 <= code && code <= 0x200b) return "w";
  7744. else if (code == 0x200c) return "b";
  7745. else return "L";
  7746. }
  7747. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  7748. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  7749. // Browsers seem to always treat the boundaries of block elements as being L.
  7750. var outerType = "L";
  7751. function BidiSpan(level, from, to) {
  7752. this.level = level;
  7753. this.from = from; this.to = to;
  7754. }
  7755. return function(str) {
  7756. if (!bidiRE.test(str)) return false;
  7757. var len = str.length, types = [];
  7758. for (var i = 0, type; i < len; ++i)
  7759. types.push(type = charType(str.charCodeAt(i)));
  7760. // W1. Examine each non-spacing mark (NSM) in the level run, and
  7761. // change the type of the NSM to the type of the previous
  7762. // character. If the NSM is at the start of the level run, it will
  7763. // get the type of sor.
  7764. for (var i = 0, prev = outerType; i < len; ++i) {
  7765. var type = types[i];
  7766. if (type == "m") types[i] = prev;
  7767. else prev = type;
  7768. }
  7769. // W2. Search backwards from each instance of a European number
  7770. // until the first strong type (R, L, AL, or sor) is found. If an
  7771. // AL is found, change the type of the European number to Arabic
  7772. // number.
  7773. // W3. Change all ALs to R.
  7774. for (var i = 0, cur = outerType; i < len; ++i) {
  7775. var type = types[i];
  7776. if (type == "1" && cur == "r") types[i] = "n";
  7777. else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
  7778. }
  7779. // W4. A single European separator between two European numbers
  7780. // changes to a European number. A single common separator between
  7781. // two numbers of the same type changes to that type.
  7782. for (var i = 1, prev = types[0]; i < len - 1; ++i) {
  7783. var type = types[i];
  7784. if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
  7785. else if (type == "," && prev == types[i+1] &&
  7786. (prev == "1" || prev == "n")) types[i] = prev;
  7787. prev = type;
  7788. }
  7789. // W5. A sequence of European terminators adjacent to European
  7790. // numbers changes to all European numbers.
  7791. // W6. Otherwise, separators and terminators change to Other
  7792. // Neutral.
  7793. for (var i = 0; i < len; ++i) {
  7794. var type = types[i];
  7795. if (type == ",") types[i] = "N";
  7796. else if (type == "%") {
  7797. for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
  7798. var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  7799. for (var j = i; j < end; ++j) types[j] = replace;
  7800. i = end - 1;
  7801. }
  7802. }
  7803. // W7. Search backwards from each instance of a European number
  7804. // until the first strong type (R, L, or sor) is found. If an L is
  7805. // found, then change the type of the European number to L.
  7806. for (var i = 0, cur = outerType; i < len; ++i) {
  7807. var type = types[i];
  7808. if (cur == "L" && type == "1") types[i] = "L";
  7809. else if (isStrong.test(type)) cur = type;
  7810. }
  7811. // N1. A sequence of neutrals takes the direction of the
  7812. // surrounding strong text if the text on both sides has the same
  7813. // direction. European and Arabic numbers act as if they were R in
  7814. // terms of their influence on neutrals. Start-of-level-run (sor)
  7815. // and end-of-level-run (eor) are used at level run boundaries.
  7816. // N2. Any remaining neutrals take the embedding direction.
  7817. for (var i = 0; i < len; ++i) {
  7818. if (isNeutral.test(types[i])) {
  7819. for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
  7820. var before = (i ? types[i-1] : outerType) == "L";
  7821. var after = (end < len ? types[end] : outerType) == "L";
  7822. var replace = before || after ? "L" : "R";
  7823. for (var j = i; j < end; ++j) types[j] = replace;
  7824. i = end - 1;
  7825. }
  7826. }
  7827. // Here we depart from the documented algorithm, in order to avoid
  7828. // building up an actual levels array. Since there are only three
  7829. // levels (0, 1, 2) in an implementation that doesn't take
  7830. // explicit embedding into account, we can build up the order on
  7831. // the fly, without following the level-based algorithm.
  7832. var order = [], m;
  7833. for (var i = 0; i < len;) {
  7834. if (countsAsLeft.test(types[i])) {
  7835. var start = i;
  7836. for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
  7837. order.push(new BidiSpan(0, start, i));
  7838. } else {
  7839. var pos = i, at = order.length;
  7840. for (++i; i < len && types[i] != "L"; ++i) {}
  7841. for (var j = pos; j < i;) {
  7842. if (countsAsNum.test(types[j])) {
  7843. if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
  7844. var nstart = j;
  7845. for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
  7846. order.splice(at, 0, new BidiSpan(2, nstart, j));
  7847. pos = j;
  7848. } else ++j;
  7849. }
  7850. if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
  7851. }
  7852. }
  7853. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  7854. order[0].from = m[0].length;
  7855. order.unshift(new BidiSpan(0, 0, m[0].length));
  7856. }
  7857. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  7858. lst(order).to -= m[0].length;
  7859. order.push(new BidiSpan(0, len - m[0].length, len));
  7860. }
  7861. if (order[0].level != lst(order).level)
  7862. order.push(new BidiSpan(order[0].level, len, len));
  7863. return order;
  7864. };
  7865. })();
  7866. // THE END
  7867. CodeMirror.version = "5.1.0";
  7868. return CodeMirror;
  7869. });